(life-grim-reaper): store-match-data => set-match-data.
[bpt/emacs.git] / lisp / play / gametree.el
1 ;;; gametree.el --- manage game analysis trees in Emacs
2
3 ;; Copyright (C) 1997 Free Software Foundation, Inc
4
5 ;; Author: Ian T Zimmerman <itz@rahul.net>
6 ;; Created: Wed Dec 10 07:41:46 PST 1997
7 ;; Keywords: games
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;; This little hack has enabled me to keep track of my email chess
29 ;; games in Emacs. For a long time I dreamt about writing a real,
30 ;; graphical tree editor; but, then the idea struck me, why do it
31 ;; graphically, when it can be done in Emacs? :-) And in fact Emacs
32 ;; almost had what I needed out of the box, namely the powerful
33 ;; Outline mode. This code is built entirely on Outline mode, it
34 ;; only adds two commands that I found indispensable when dealing
35 ;; with the special kind of trees that analysis trees comprise.
36
37 ;; The built-in documentation should be enough to explain the use,
38 ;; along with the following example (yes, this is a real game).
39
40 ;; *** 23. f4 ef 24. Nf3 Rf3 -/+
41 ;; 25. Rf3 Qh2 26. Kh1 Qh1 27. Ke2 Qg2 -+
42 ;; ******* 25. gf3 Nce3 26. Qe2 Nf1 -/+
43 ;; 27. Qe5 Ne5 28. Kf1 Nf3 -/+
44 ;; 27. Kf1 Nh2 28. Kf2 Ng4 29. fg4 Rf8 30. Ke1 Qg3 31. Kd1 Rf2 -+
45
46 ;; Place the preceding in a scratch buffer, load this code, and do
47 ;; M-x gametree-mode. Now place the cursor just after the `Nf3' and
48 ;; before the `Rf3' on the first line, and do C-c C-j. The result is
49
50 ;; *** 23. f4 ef 24. Nf3
51 ;; ****** 24: Rf3 -/+
52 ;; 25. Rf3 Qh2 26. Kh1 Qh1 27. Ke2 Qg2 -+
53 ;; ******* 25. gf3 Nce3 26. Qe2 Nf1 -/+
54 ;; 27. Qe5 Ne5 28. Kf1 Nf3 -/+
55 ;; 27. Kf1 Nh2 28. Kf2 Ng4 29. fg4 Rf8 30. Ke1 Qg3 31. Kd1 Rf2 -+
56
57 ;; Now you can add another subvariation on Black's 24th move: with
58 ;; the cursor still on the first line, do C-c C-v, and voila
59
60 ;; *** 23. f4 ef 24. Nf3
61 ;; 24:
62 ;; ****** 24: Rf3 -/+
63 ;; 25. Rf3 Qh2 26. Kh1 Qh1 27. Ke2 Qg2 -+
64 ;; ******* 25. gf3 Nce3 26. Qe2 Nf1 -/+
65 ;; 27. Qe5 Ne5 28. Kf1 Nf3 -/+
66 ;; 27. Kf1 Nh2 28. Kf2 Ng4 29. fg4 Rf8 30. Ke1 Qg3 31. Kd1 Rf2 -+
67
68 ;; and the cursor is positioned on the new line just after the move
69 ;; number, so you can start typing the new analysis. That's it,
70 ;; quite simple. If you want more, read on.
71
72 ;;; ToDo:
73
74 ;; BIG: automatic score reducer. It should be possible to label the
75 ;; leaf variations with numeric scores (instead of the Informant-like
76 ;; symbols used in the example) and have the program apply the
77 ;; min-max algorithm to score the internal nodes. That's about as
78 ;; far as one can go in a postal game while honestly claiming not to
79 ;; use computer analysis.
80
81 ;; I'd definitely like to hear from you if you use this, and even
82 ;; more if you have suggestions for improvement, ranging from bug
83 ;; reports to feature requests. (But be warned that I am a fan of
84 ;; simplicity and orthogonality).
85
86 ;;; Code:
87
88 (require 'derived)
89 (require 'outline)
90
91 ;;;; Configuration variables
92
93 (defvar gametree-half-ply-regexp (regexp-quote ":")
94 "*Matches ends of numbers of moves by the \"second\" player.
95 For instance, it is an almost universal convention in chess to postfix
96 numbers of moves by Black (if considered in isolation) by the ellipsis
97 \"...\". This is NOT a good choice for this program, though, because it
98 conflicts with the use of ellipsis by Outline mode to denote collapsed
99 subtrees. The author uses \":\" because it agrees nicely with a set of
100 LaTeX macros he uses for typesetting annotated games.")
101
102 (defvar gametree-full-ply-regexp (regexp-quote ".")
103 "*Matches ends of numbers of moves by the \"first\" player.
104 For instance, it is an almost universal convention in chess to postfix
105 numbers of moves by White (if considered in isolation) by the dot \".\".")
106
107 (defvar gametree-half-ply-format "%d:"
108 "*Output format for move numbers of moves by the \"second\" player.
109 Has to contain \"%d\" to output the actual number.")
110
111 (defvar gametree-full-ply-format "%d."
112 "*Output format for move numbers of moves by the \"first\" player.
113 Has to contain \"%d\" to output the actual number.")
114
115 (defvar gametree-make-heading-function
116 (function (lambda (level)
117 (insert (make-string level ?*))))
118 "A function of one numeric argument, LEVEL, to insert a heading at point.
119 You should change this if you change `outline-regexp'.")
120
121 (defvar gametree-local-layout nil
122 "A list encoding the layout (i.e. the show or hide state) of the file.
123 If Emacs notices a local variable specification of this variable in
124 the first line of the buffer while saving the buffer to the visited
125 file, the local value will be saved there and restored the next time
126 the file is visited (subject to the usual restriction via
127 `enable-local-variables'), and the layout will be set accordingly.")
128
129 ;;;; Helper functions
130
131 (defun gametree-prettify-heading ()
132 "Insert/delete space between leading asterisks and heading text.
133 If the current variation is an internal node (i.e. starts with one or
134 more asterisks), ensure there's at least one space between the
135 asterisks and the text. If on the other hand this is a leaf, there
136 should be no leading white space."
137 (save-excursion
138 (beginning-of-line 1)
139 (if (re-search-forward (concat "\\=" outline-regexp) nil t)
140 (if (not (looking-at "[ \t]+")) (insert " "))
141 (delete-char (save-excursion (skip-chars-forward " \t"))))
142 (if (re-search-forward (concat "\\=[ \t]*[1-9][0-9]*\\("
143 gametree-full-ply-regexp "\\|"
144 gametree-half-ply-regexp "\\)") nil t)
145 (if (not (looking-at "[ \t]+")) (insert " ")
146 (delete-char (1- (save-excursion (skip-chars-forward " \t"))))))))
147
148 (defun gametree-looking-at-ply ()
149 "Read and return the number of the ply under point."
150 (if (eobp) 0
151 (let ((boundary (concat "[ \t]*\\([1-9][0-9]*\\)\\("
152 gametree-full-ply-regexp "\\|"
153 gametree-half-ply-regexp "\\)"))
154 (limit (save-excursion (beginning-of-line 1) (point))))
155 (if (looking-at boundary)
156 (+ (* 2 (string-to-int (match-string 1)))
157 (if (string-match gametree-half-ply-regexp (match-string 2)) 1 0))
158 (save-excursion
159 (re-search-backward boundary limit)
160 (skip-chars-backward "0123456789")
161 (1+ (* 2 (string-to-int
162 (buffer-substring (point) (match-end 1))))))))))
163
164 (defun gametree-current-branch-ply ()
165 "Return the ply number of the first move of the current variation."
166 (save-excursion
167 (beginning-of-line 1)
168 (re-search-forward (concat "\\=" outline-regexp) nil t)
169 (gametree-looking-at-ply)))
170
171 (defun gametree-current-branch-depth ()
172 "Return the depth of the current variation in the analysis tree.
173 This value is simply the outline heading level of the current line."
174 (save-excursion
175 (beginning-of-line 1)
176 (if (looking-at outline-regexp)
177 (outline-level) 0)))
178
179 ;;;; Functions related to the task of saving and restoring current
180 ;;;; outline layout
181
182 (defun gametree-show-children-and-entry ()
183 (show-children)
184 (show-entry))
185
186 (defun gametree-entry-shown-p ()
187 (save-excursion
188 (forward-line 1)
189 (and (bolp) (not (eobp)) (not (looking-at outline-regexp)))))
190
191 (defun gametree-children-shown-p ()
192 (save-excursion
193 (condition-case nil
194 (let ((depth (gametree-current-branch-depth)))
195 (outline-next-visible-heading 1)
196 (< depth (gametree-current-branch-depth)))
197 (error nil))))
198
199 (defun gametree-current-layout (depth &optional top-level)
200 (let ((layout nil) (first-time t))
201 (while (save-excursion
202 (condition-case nil
203 (progn
204 (or (and first-time top-level
205 (bolp) (looking-at outline-regexp))
206 (setq first-time nil)
207 (outline-next-visible-heading 1))
208 (< depth (gametree-current-branch-depth)))
209 (error nil)))
210 (if (not first-time)
211 (outline-next-visible-heading 1))
212 (setq first-time nil)
213 (if (not (gametree-children-shown-p))
214 (setq layout
215 (nconc layout
216 (if (gametree-entry-shown-p)
217 (list 'show-entry)
218 (list nil))))
219 (setq layout (nconc layout (if (gametree-entry-shown-p)
220 (list 'gametree-show-children-and-entry)
221 (list 'show-children))))
222 (let ((sub-layout
223 (gametree-current-layout (gametree-current-branch-depth))))
224 (setq layout (nconc layout (list sub-layout))))))
225 layout))
226
227 (defun gametree-save-layout ()
228 (save-excursion
229 (goto-char (point-min))
230 (setq gametree-local-layout (gametree-current-layout 0 t))))
231
232 (defun gametree-apply-layout (layout depth &optional top-level)
233 (let ((first-time t))
234 (while (and layout
235 (save-excursion
236 (condition-case nil
237 (progn
238 (or (and first-time top-level
239 (bolp) (looking-at outline-regexp))
240 (setq first-time nil)
241 (outline-next-visible-heading 1))
242 (< depth (gametree-current-branch-depth)))
243 (error nil))))
244 (if (not first-time)
245 (outline-next-visible-heading 1))
246 (setq first-time nil)
247 (hide-subtree)
248 (if (nth 0 layout)
249 (funcall (nth 0 layout)))
250 (if (not (and (nth 1 layout) (listp (nth 1 layout))))
251 (setq layout (cdr layout))
252 (gametree-apply-layout (nth 1 layout)
253 (gametree-current-branch-depth))
254 (setq layout (cdr (cdr layout)))))))
255
256 (defun gametree-restore-layout ()
257 (save-excursion
258 (goto-char (point-min))
259 (gametree-apply-layout gametree-local-layout 0 t)))
260
261 (defun gametree-hack-file-layout ()
262 (save-excursion
263 (goto-char (point-min))
264 (if (looking-at "[^\n]*-\*-[^\n]*gametree-local-layout: \\([^;\n]*\\);")
265 (progn
266 (goto-char (match-beginning 1))
267 (delete-region (point) (match-end 1))
268 (let ((standard-output (current-buffer)))
269 (princ gametree-local-layout))))))
270
271 ;;;; Commands
272
273 (defun gametree-insert-new-leaf (&optional at-depth)
274 "Start a new leaf variation under the current branching point.
275 The new variation can later be split to be a branching point itself,
276 with \\[gametree-break-line-here]. If the point is currently on a
277 leaf variation, this command won't work; use \\[gametree-break-line-here]
278 on the current line first.
279
280 With a numeric arg AT-DEPTH, first go up the tree until a node of
281 depth AT-DEPTH or smaller is found."
282 (interactive "P")
283 (if (zerop (gametree-current-branch-depth))
284 (outline-up-heading 0))
285 (if at-depth
286 (while (> (gametree-current-branch-depth)
287 (prefix-numeric-value at-depth))
288 (outline-up-heading 1)))
289 (beginning-of-line 1)
290 (let ((parent-depth (gametree-current-branch-depth)))
291 (show-entry)
292 (condition-case nil
293 (outline-next-visible-heading 1)
294 (error
295 (goto-char (point-max))
296 (if (not (bolp)) (insert "\n"))))
297 (let ((starting-plys
298 (if (> (gametree-current-branch-depth) parent-depth)
299 (gametree-current-branch-ply)
300 (save-excursion (forward-line -1)
301 (gametree-current-branch-ply)))))
302 (goto-char (1- (point)))
303 (insert "\n")
304 (insert (format (if (= 0 (mod starting-plys 2))
305 gametree-full-ply-format
306 gametree-half-ply-format)
307 (/ starting-plys 2))))))
308
309 (defun gametree-break-line-here (&optional at-move)
310 "Split the variation node at the point position.
311 This command works whether the current variation node is a leaf, or is
312 already branching at its end. The new node is created at a level that
313 reflects the number of game plys between the beginning of the current
314 variation and the breaking point.
315
316 With a numerical argument AT-MOVE, split the variation before
317 White's AT-MOVEth move, or Black's if negative. The last option will
318 only work of Black's moves are explicitly numbered, for instance
319 `1. e4 1: e5'."
320 (interactive "P")
321 (if at-move (progn
322 (end-of-line 1)
323 (let ((limit (point)))
324 (beginning-of-line 1)
325 (re-search-forward
326 (concat
327 (regexp-quote
328 (int-to-string (abs (prefix-numeric-value at-move))))
329 (if (> at-move 0) gametree-full-ply-regexp
330 gametree-half-ply-regexp)) limit))
331 (goto-char (match-beginning 0))))
332 (let* ((pt (set-marker (make-marker) (point)))
333 (plys (gametree-current-branch-ply))
334 (depth (gametree-current-branch-depth))
335 (old-depth depth))
336 (if (= depth 0)
337 (progn
338 (save-excursion
339 (outline-previous-visible-heading 1)
340 (setq depth
341 (let ((old-branch-ply
342 (condition-case nil
343 (gametree-current-branch-ply)
344 (error 0))))
345 (if (zerop old-branch-ply)
346 (1+ (gametree-current-branch-depth))
347 (+ (gametree-current-branch-depth)
348 (- plys old-branch-ply))))))
349 (save-excursion
350 (beginning-of-line 1)
351 (funcall gametree-make-heading-function depth)
352 (gametree-prettify-heading))))
353 (save-excursion
354 (if (not (looking-at (concat "[ \t]*[1-9][0-9]*\\("
355 gametree-full-ply-regexp "\\|"
356 gametree-half-ply-regexp "\\)")))
357 (progn
358 (insert (format (if (= 0 (mod (gametree-looking-at-ply) 2))
359 gametree-full-ply-format
360 gametree-half-ply-format)
361 (/ (gametree-looking-at-ply) 2)))
362 (gametree-prettify-heading)
363 (beginning-of-line 1)))
364 (goto-char pt)
365 (insert "\n")
366 (if (not (= 0 old-depth))
367 (funcall gametree-make-heading-function
368 (+ depth (- (gametree-current-branch-ply) plys))))
369 (gametree-prettify-heading))))
370
371 (defun gametree-merge-line ()
372 "Merges a variation with its only child.
373 Does *not* check if the variation has in fact a unique child; users beware."
374 (interactive)
375 (if (zerop (gametree-current-branch-depth))
376 (outline-up-heading 0))
377 (end-of-line 1)
378 (let ((prev-depth (save-excursion (forward-line 1)
379 (gametree-current-branch-depth))))
380 (delete-char (1+ prev-depth))
381 (if (zerop prev-depth)
382 (save-excursion
383 (beginning-of-line 1)
384 (delete-char (gametree-current-branch-depth))
385 (gametree-prettify-heading)))))
386
387 (defun gametree-layout-to-register (register)
388 "Store current tree layout in register REGISTER.
389 Use \\[gametree-apply-register-layout] to restore that configuration.
390 Argument is a character, naming the register."
391 (interactive "cLayout to register: ")
392 (save-excursion
393 (goto-char (point-min))
394 (set-register register
395 (gametree-current-layout 0 t))))
396
397 (defun gametree-apply-register-layout (char)
398 "Return to a tree layout stored in a register.
399 Argument is a character, naming the register."
400 (interactive "cApply layout from register: ")
401 (save-excursion
402 (goto-char (point-min))
403 (gametree-apply-layout (get-register char) 0 t)))
404
405 (defun gametree-save-and-hack-layout ()
406 "Save the current tree layout and hack the file local variable spec.
407 This function saves the current layout in `gametree-local-layout' and,
408 if a local file varible specification for this variable exists in the
409 buffer, it is replaced by the new value. See the documentation for
410 `gametree-local-layout' for more information."
411 (interactive)
412 (gametree-save-layout)
413 (gametree-hack-file-layout)
414 nil)
415
416 (define-derived-mode gametree-mode outline-mode "GameTree"
417 "Major mode for managing game analysis trees.
418 Useful to postal and email chess (and, it is hoped, also checkers, go,
419 shogi, etc.) players, it is a slightly modified version of Outline mode.
420
421 \\{gametree-mode-map}"
422 (auto-fill-mode 0)
423 (make-variable-buffer-local 'write-contents-hooks)
424 (add-hook 'write-contents-hooks 'gametree-save-and-hack-layout))
425
426 ;;;; Key bindings
427
428 (define-key gametree-mode-map "\C-c\C-j" 'gametree-break-line-here)
429 (define-key gametree-mode-map "\C-c\C-v" 'gametree-insert-new-leaf)
430 (define-key gametree-mode-map "\C-c\C-m" 'gametree-merge-line)
431 (define-key gametree-mode-map "\C-c\C-r " 'gametree-layout-to-register)
432 (define-key gametree-mode-map "\C-c\C-r/" 'gametree-layout-to-register)
433 (define-key gametree-mode-map "\C-c\C-rj" 'gametree-apply-register-layout)
434 (define-key gametree-mode-map "\C-c\C-y" 'gametree-save-and-hack-layout)
435
436 ;;;; Goodies for mousing users
437 (and (fboundp 'track-mouse)
438 (defun gametree-mouse-break-line-here (event)
439 (interactive "e")
440 (mouse-set-point event)
441 (gametree-break-line-here))
442 (defun gametree-mouse-show-children-and-entry (event)
443 (interactive "e")
444 (mouse-set-point event)
445 (gametree-show-children-and-entry))
446 (defun gametree-mouse-show-subtree (event)
447 (interactive "e")
448 (mouse-set-point event)
449 (show-subtree))
450 (defun gametree-mouse-hide-subtree (event)
451 (interactive "e")
452 (mouse-set-point event)
453 (hide-subtree))
454 (define-key gametree-mode-map [M-down-mouse-2 M-mouse-2]
455 'gametree-mouse-break-line-here)
456 (define-key gametree-mode-map [S-down-mouse-1 S-mouse-1]
457 'gametree-mouse-show-children-and-entry)
458 (define-key gametree-mode-map [S-down-mouse-2 S-mouse-2]
459 'gametree-mouse-show-subtree)
460 (define-key gametree-mode-map [S-down-mouse-3 S-mouse-3]
461 'gametree-mouse-hide-subtree))
462
463 (provide 'gametree)
464
465 ;;; gametree.el ends here