]> code.delx.au - gnu-emacs-elpa/blob - packages/gnugo/gnugo.el
[gnugo] Validate position arg of GTP commands ‘undo’, ‘gg-undo’.
[gnu-emacs-elpa] / packages / gnugo / gnugo.el
1 ;;; gnugo.el --- play GNU Go in a buffer -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
4
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
6 ;; Version: 2.3.1
7 ;; Package-Requires: ((ascii-art-to-unicode "1.5"))
8
9 ;; This program is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; This program is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;; Playing
25 ;; -------
26 ;;
27 ;; This file provides the command `gnugo' which allows you to play the game of
28 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
29 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
30 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
31 ;; Go" to refer to the process object created by running the external program.
32 ;;
33 ;; At the start of a new game, you can pass additional command-line arguments
34 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
35 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
36 ;; both komi and handicap.
37 ;;
38 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
39 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
40 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
41 ;; back through an arbitrary stone that you played, place the cursor on a
42 ;; stone and type `U' (note: uppercase).
43 ;;
44 ;; There are a great many other commands. Other keybindings are described in
45 ;; the `gnugo-board-mode' documentation, which you may view with the command
46 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
47 ;; the last move and who is currently to play. Capture counts and other info
48 ;; are shown on the mode line immediately following the major mode name.
49 ;;
50 ;; While GNU Go is pondering its next move, certain commands that rely on its
51 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
52 ;; is normal. When it is your turn again you may retry the command. In the
53 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
54 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
55 ;;
56 ;; If GNU Go should crash during a game the mode line will show "no process".
57 ;; Please report the event to the GNU Go maintainers so that they can improve
58 ;; the program.
59 ;;
60 ;;
61 ;; Meta-Playing (aka Customizing)
62 ;; ------------------------------
63 ;;
64 ;; Customization is presently limited to
65 ;; vars: `gnugo-program'
66 ;; `gnugo-animation-string'
67 ;; `gnugo-mode-line'
68 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
69 ;; `gnugo-xpms'
70 ;; normal hooks: `gnugo-board-mode-hook'
71 ;; `gnugo-frolic-mode-hook'
72 ;; `gnugo-start-game-hook'
73 ;; `gnugo-post-move-hook'
74 ;; and the keymap: `gnugo-board-mode-map'
75 ;;
76 ;; The variable `gnugo-xpms' is a special case. To set it you need to load
77 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
78 ;; interface.
79
80 ;;; Code:
81
82 (eval-when-compile (require 'cl)) ; use the source luke!
83 (require 'ascii-art-to-unicode) ; for `aa2u'
84 (require 'time-date) ; for `time-subtract'
85
86 ;;;---------------------------------------------------------------------------
87 ;;; Political arts
88
89 (defconst gnugo-version "2.3.1"
90 "Version of gnugo.el currently loaded.
91 This follows a MAJOR.MINOR.PATCH scheme.")
92
93 ;;;---------------------------------------------------------------------------
94 ;;; Variables for the uninquisitive programmer
95
96 (defvar gnugo-program "gnugo"
97 "Name of the GNU Go program (executable file).
98 \\[gnugo] validates this using `executable-find'.
99 This program must accept command line args:
100 --mode gtp --quiet
101 For more information on GTP and GNU Go, please visit:
102 <http://www.gnu.org/software/gnugo>")
103
104 (defvar gnugo-board-mode-map nil
105 "Keymap for GNUGO Board mode.")
106
107 (defvar gnugo-frolic-mode-map nil
108 "Keymap for GNUGO Frolic mode.")
109
110 (defvar gnugo-board-mode-hook nil
111 "Hook run when entering GNUGO Board mode.")
112
113 (defvar gnugo-start-game-hook nil
114 "Normal hook run immediately before the first move of the game.
115 To find out who is to move first, use `gnugo-current-player'.
116 See also `gnugo-board-mode'.")
117
118 (defvar gnugo-post-move-hook nil
119 "Normal hook run after a move and before the board is refreshed.
120 Initially, when `run-hooks' is called, the current buffer is the GNUGO
121 Board buffer of the game. Hook functions that switch buffers must take
122 care not to call (directly or indirectly through some other function)
123 `gnugo-put' or `gnugo-get' after the switch.")
124
125 (defvar gnugo-animation-string
126 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
127 (concat jam jam jam jam jam
128 ;; "SECRET MESSAGE HERE"
129 blink blink blink blink blink blink blink blink
130 ;; Playing go is like fighting ignorance: when you think you have
131 ;; surrounded something by knowing it very well it often turns
132 ;; out that in the time you spent deepening this understanding,
133 ;; other areas of ignorance have surrounded you.
134 spin spin spin spin spin spin spin spin spin
135 ;; Playing go is not like fighting ignorance: what one person
136 ;; knows many people may come to know; knowledge does not build
137 ;; solely move by move. Wisdom, on the other hand...
138 yada yada yada))
139 "String whose individual characters are used for animation.
140 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
141 render the stones in their respective result groups as the first character
142 in the string, then the next, and so on.")
143
144 (defvar gnugo-mode-line "~b ~w :~m :~u"
145 "A `mode-line-format'-compliant value for GNUGO Board mode.
146 If a single string, the following special escape sequences are
147 replaced with their associated information:
148 ~b,~w black,white captures (a number)
149 ~p current player (black or white)
150 ~m move number
151 ~t time waiting for the current move
152 ~u time taken for the Ultimate (most recent) move
153 The times are in seconds, or \"-\" if that information is not available.
154 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
155
156 (defvar gnugo-X-face 'font-lock-string-face
157 "Name of face to use for X (black) stones.")
158
159 (defvar gnugo-O-face 'font-lock-builtin-face
160 "Name of face to use for O (white) stones.")
161
162 (defvar gnugo-grid-face 'default
163 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
164
165 ;;;---------------------------------------------------------------------------
166 ;;; Variables for the inquisitive programmer
167
168 (defconst gnugo-font-lock-keywords
169 '(("X" . gnugo-X-face)
170 ("O" . gnugo-O-face))
171 "Font lock keywords for `gnugo-board-mode'.")
172
173 (defvar gnugo-option-history nil)
174
175 (defvar gnugo-state nil) ; hint: C-c C-p
176
177 (eval-when-compile
178 (defvar gnugo-xpms nil))
179
180 (defvar gnugo-frolic-parent-buffer nil)
181 (defvar gnugo-frolic-origin nil)
182
183 ;;;---------------------------------------------------------------------------
184 ;;; Support functions
185
186 (defsubst gnugo--mkht (&rest etc)
187 (apply 'make-hash-table :test 'eq etc))
188
189 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
190 (compare-strings s1 beg1 nil s2 beg2 nil))
191
192 (defun gnugo-put (key value)
193 "Associate move/game/board-specific property KEY with VALUE.
194
195 There are many properties, each named by a keyword, that record and control
196 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
197 of properties, stored in the hash table `gnugo-state'. Here we document
198 some of the more stable properties. You may wish to use them as part of
199 a `gnugo-post-move-hook' function, for example. Be careful to preserve
200 the current buffer as `gnugo-state' is made into a buffer-local variable.
201 NOTE: In the following, \"see foo\" actually means \"see foo source or
202 you may never really understand to any degree of personal satisfaction\".
203
204 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
205
206 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
207
208 :game-over -- nil until game over at which time its value is set to
209 the alist `((live GROUP ...) (dead GROUP ...))'
210
211 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
212 a simple list of one or more gametrees, updated in
213 conjunction w/ :sgf-gametree and :monkey
214
215 :sgf-gametree -- one of the gametrees in :sgf-collection
216
217 :monkey -- vector of two elements:
218 MEM, a pointer to one of the branches in the gametree;
219 BIDX, the index of the \"current branch\"
220
221 :gnugo-color -- either \"black\" or \"white\"
222 :user-color
223 :last-mover
224
225 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
226 :waiting-start
227
228 :black-captures -- these are strings since gnugo.el doesn't do anything
229 :white-captures w/ the information besides display it in the mode line;
230 gory details in functions `gnugo-propertize-board-buffer'
231 and `gnugo-merge-showboard-results' (almost more effort
232 than they are worth!)
233
234 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
235 `gnugo-toggle-image-display' and `gnugo-refresh',
236 as well as gnugo-xpms.el (available elsewhere)
237
238 :all-yy -- list of 46 keywords used as the `category' text property
239 (so that their plists, typically w/ property `display' or
240 `do-not-display') are consulted by the Emacs display engine;
241 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
242 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
243
244 :paren-ov -- a pair (left and right) of overlays shuffled about to indicate
245 the last move; only one is used when displaying using images
246
247 :last-user-bpos -- board position; keep the hapless human happy
248
249 As things stabilize probably more info will be added to this docstring."
250 (declare (indent 1))
251 (puthash key value gnugo-state))
252
253 (defun gnugo-get (key)
254 "Return the move/game/board-specific value for KEY.
255 See `gnugo-put'."
256 (gethash key gnugo-state))
257
258 (defun gnugo--forget (&rest keys)
259 (dolist (key keys)
260 (remhash key gnugo-state)))
261
262 (defsubst gnugo--tree-mnum (tree)
263 (aref tree 1))
264
265 (defsubst gnugo--tree-ends (tree)
266 (aref tree 0))
267
268 (defsubst gnugo--set-tree-ends (tree ls)
269 (aset tree 0 (apply 'vector ls))
270 (gnugo--tree-ends tree))
271
272 (defun gnugo--root-node (&optional tree)
273 (aref (or tree (gnugo-get :sgf-gametree))
274 2))
275
276 (defun gnugo-describe-internal-properties ()
277 "Pretty-print `gnugo-state' properties in another buffer.
278 Handle the big, slow-to-render, and/or uninteresting ones specially."
279 (interactive)
280 (let ((buf (current-buffer))
281 (d (gnugo-get :diamond))
282 acc)
283 (loop for key being the hash-keys of gnugo-state
284 using (hash-values val)
285 do (push (cons key
286 (case key
287 ((:xpms :local-xpms)
288 (format "hash: %X (%d images)"
289 (sxhash val)
290 (length val)))
291 (:sgf-collection
292 (length val))
293 (:sgf-gametree
294 (list (hash-table-count
295 (gnugo--tree-mnum val))
296 (gnugo--root-node val)
297 (gnugo--tree-ends val)))
298 (:monkey
299 (let ((mem (aref val 0)))
300 (list (aref val 1)
301 (car mem))))
302 (t val)))
303 acc))
304 (switch-to-buffer (get-buffer-create
305 (format "%s*GNUGO Board Properties*"
306 (gnugo-get :diamond))))
307 (erase-buffer)
308 (emacs-lisp-mode)
309 (setq truncate-lines t)
310 (save-excursion
311 (pp acc
312 (current-buffer))
313 (goto-char (point-min))
314 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
315 (if (string= "" d)
316 ".+\n"
317 ""))))
318 (while (re-search-forward rx (point-max) t)
319 (let ((pos (get-text-property (string-to-number (match-string 1))
320 'gnugo-position buf)))
321 (delete-region (+ 2 (match-beginning 0)) (point))
322 (insert (format " %S" pos))))))
323 (message "%d properties" (length acc))))
324
325 (defun gnugo-board-buffer-p (&optional buffer)
326 "Return non-nil if BUFFER is a GNUGO Board buffer."
327 (eq 'gnugo-board-mode
328 (buffer-local-value
329 'major-mode
330 (or buffer (current-buffer)))))
331
332 (defun gnugo-board-user-play-ok-p (&optional buffer)
333 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
334 (with-current-buffer (or buffer (current-buffer))
335 (and gnugo-state (not (gnugo-get :waiting)))))
336
337 (defsubst gnugo--blackp (string)
338 (string= "black" string))
339
340 (defun gnugo-other (color)
341 (if (gnugo--blackp color) "white" "black"))
342
343 (defun gnugo-current-player ()
344 "Return the current player, either \"black\" or \"white\"."
345 (gnugo-other (gnugo-get :last-mover)))
346
347 (defsubst gnugo--prop<-color (color)
348 (if (gnugo--blackp color) :B :W))
349
350 (defsubst gnugo--gate-game-over (enable)
351 (when (and enable (gnugo-get :game-over))
352 (user-error "Sorry, game over")))
353
354 (defun gnugo--ERR-wait (color why)
355 (user-error "%s -- please wait for \"(%s to play)\""
356 why color))
357
358 (defun gnugo-gate (&optional in-progress-p)
359 (unless (gnugo-board-buffer-p)
360 (user-error "Wrong buffer -- try M-x gnugo"))
361 (unless (gnugo-get :proc)
362 (user-error "No \"gnugo\" process!"))
363 (let ((slow (gnugo-get :waiting)))
364 (when slow
365 (gnugo--ERR-wait (gnugo-get :user-color)
366 (if (cdr slow)
367 "Still thinking"
368 "Not your turn yet"))))
369 (gnugo--gate-game-over in-progress-p))
370
371 (defun gnugo-sentinel (proc string)
372 (let ((status (process-status proc)))
373 (when (memq status '(exit signal))
374 (let ((buf (process-buffer proc)))
375 (when (buffer-live-p buf)
376 (with-current-buffer buf
377 (setq mode-line-process
378 (list " [%s ("
379 (propertize (car (split-string string))
380 'face 'font-lock-warning-face)
381 ")]"))
382 (when (eq proc (gnugo-get :proc))
383 (gnugo--forget :proc))))))))
384
385 (defun gnugo--begin-exchange (proc filter line)
386 (declare (indent 2)) ; good time, for a rime
387 ; nice style, for a wile...
388 (set-process-filter proc filter)
389 (process-send-string proc line)
390 (process-send-string proc "\n"))
391
392 (defun gnugo--q (fmt &rest args)
393 "Send formatted command \"FMT ARGS...\"; wait for / return response.
394 The response is a string whose first two characters indicate the
395 status of the command. See also `gnugo-query'."
396 (let ((slow (gnugo-get :waiting))
397 (proc (gnugo-get :proc)))
398 (when slow
399 (user-error "Sorry, still waiting for %s to %s"
400 (car slow) (if (cdr slow)
401 "receive a suggestion"
402 "play")))
403 (process-put proc :incomplete t)
404 (process-put proc :srs "") ; synchronous return stash
405 (gnugo--begin-exchange
406 proc (lambda (proc string)
407 (let ((full (concat (process-get proc :srs)
408 string)))
409 (process-put proc :srs full)
410 (unless (numberp (gnugo--compare-strings
411 full (max 0 (- (length full)
412 2))
413 "\n\n" nil))
414 (process-put proc :incomplete nil))))
415 (if (null args)
416 fmt
417 (apply #'format fmt args)))
418 (while (process-get proc :incomplete)
419 (accept-process-output proc 30))
420 (prog1 (substring (process-get proc :srs) 0 -2)
421 (process-put proc :srs ""))))
422
423 (defun gnugo--q/ue (fmt &rest args)
424 (let ((ans (apply 'gnugo--q fmt args)))
425 (unless (= ?= (aref ans 0))
426 (user-error "%s" ans))
427 (substring ans 2)))
428
429 (defun gnugo-query (message-format &rest args)
430 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
431 Return a string that omits the first two characters (corresponding
432 to the status indicator in the Go Text Protocol). Use this function
433 when you are sure the command cannot fail."
434 (substring (apply 'gnugo--q message-format args)
435 2))
436
437 (defun gnugo--nquery (cmd)
438 (string-to-number (gnugo-query cmd)))
439
440 (defun gnugo-lsquery (message-format &rest args)
441 (split-string (apply 'gnugo-query message-format args)))
442
443 (defsubst gnugo--count-query (fmt &rest args)
444 (length (apply 'gnugo-lsquery fmt args)))
445
446 (defsubst gnugo--root-prop (prop &optional tree)
447 (cdr (assq prop (gnugo--root-node tree))))
448
449 (defun gnugo--set-root-prop (prop value &optional tree)
450 (let* ((root (gnugo--root-node tree))
451 (cur (assq prop root)))
452 (if cur
453 (setcdr cur value)
454 (push (cons prop value)
455 (cdr (last root))))))
456
457 (defun gnugo-goto-pos (pos)
458 "Move point to board position POS, a letter-number string."
459 (goto-char (point-min))
460 (forward-line (- (1+ (gnugo-get :SZ))
461 (string-to-number (substring pos 1))))
462 (forward-char 1)
463 (forward-char (+ (if (= 32 (following-char)) 1 2)
464 (* 2 (- (let ((letter (aref pos 0)))
465 (if (> ?I letter)
466 letter
467 (1- letter)))
468 ?A)))))
469
470 (defun gnugo-f (frag)
471 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
472
473 (defun gnugo-yang (c)
474 (cdr (assq c '((?+ . hoshi)
475 (?. . empty)
476 (?X . (bmoku . bpmoku))
477 (?O . (wmoku . wpmoku))))))
478
479 (defun gnugo-yy (yin yang &optional momentaryp)
480 (gnugo-f (format "%d-%s"
481 yin (cond ((and (consp yang) momentaryp) (cdr yang))
482 ((consp yang) (car yang))
483 (t yang)))))
484
485 (defun gnugo-toggle-image-display ()
486 (unless (and (fboundp 'display-images-p) (display-images-p))
487 (user-error "Display does not support images, sorry"))
488 (require 'gnugo-xpms)
489 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
490 (user-error "Could not load `gnugo-xpms', sorry"))
491 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
492 (unless (eq fresh (gnugo-get :xpms))
493 (gnugo-put :xpms fresh)
494 (gnugo--forget :all-yy)))
495 (let* ((new (not (gnugo-get :display-using-images)))
496 (act (if new 'display 'do-not-display)))
497 (mapc (lambda (yy)
498 (setcar (symbol-plist yy) act))
499 (or (gnugo-get :all-yy)
500 (gnugo-put :all-yy
501 (prog1 (mapcar (lambda (ent)
502 (let* ((k (car ent))
503 (yy (gnugo-yy (cdr k) (car k))))
504 (setplist yy `(not-yet ,(cdr ent)))
505 yy))
506 (gnugo-get :xpms))
507 (gnugo-put :imul
508 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
509 'not-yet)))))))
510 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
511 (gnugo-put :highlight-last-move-spec
512 (if new
513 '((lambda (p)
514 (get (gnugo-yy (get-text-property p 'gnugo-yin)
515 (get-text-property p 'gnugo-yang)
516 t)
517 'display))
518 0 delete-overlay)
519 (gnugo-get :default-highlight-last-move-spec)))
520 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
521 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
522 (mapc 'delete-overlay (cdar group))
523 (setcdr (car group) nil))
524 (gnugo-put :mul (if new
525 (gnugo-get :imul)
526 '(1 . 1)))
527 (gnugo-put :display-using-images new)))
528
529 (defun gnugo-toggle-grid ()
530 "Turn the grid around the board on or off."
531 (interactive)
532 (funcall (if (memq :nogrid buffer-invisibility-spec)
533 'remove-from-invisibility-spec
534 'add-to-invisibility-spec)
535 :nogrid)
536 (save-excursion (gnugo-refresh)))
537
538 (defun gnugo-propertize-board-buffer ()
539 (erase-buffer)
540 (insert (substring (gnugo--q "showboard") 3))
541 (let* ((grid-props (list 'invisible :nogrid
542 'font-lock-face gnugo-grid-face))
543 (%gpad (gnugo-f 'gpad))
544 (%gspc (gnugo-f 'gspc))
545 (%lpad (gnugo-f 'lpad))
546 (%rpad (gnugo-f 'rpad))
547 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
548 (size (gnugo-get :SZ))
549 (size-string (number-to-string size)))
550 (goto-char (point-min))
551 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
552 (skip-chars-forward " ")
553 (put-text-property (1- (point)) (point) 'category %gpad)
554 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
555 (forward-char 1)
556 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
557 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
558 (let* ((row (match-string-no-properties 1))
559 (edge (match-end 0))
560 (other-edge (+ edge (* 2 size) -1))
561 (right-empty (+ other-edge (length row) 1))
562 (top-p (string= size-string row))
563 (bot-p (string= "1" row)))
564 (let* ((nL (- edge 1 (length size-string)))
565 (nR (- edge 1))
566 (ov (make-overlay nL nR (current-buffer) t)))
567 (add-text-properties nL nR grid-props)
568 ;; We redundantly set `invisible' in the overlay to workaround
569 ;; a display bug whereby text *following* the overlaid text is
570 ;; displayed with the face of the overlaid text, but only when
571 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
572 ;; This has something to do w/ the bletcherous `before-string'.
573 (overlay-put ov 'invisible :nogrid)
574 (overlay-put ov 'category %lpad))
575 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
576 ((< other-edge p))
577 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
578 (truncate (- p edge) 2))
579 row))
580 (yin (let ((A-p (= edge p))
581 (Z-p (= (1- other-edge) p)))
582 (cond ((and top-p A-p) 1)
583 ((and top-p Z-p) 3)
584 ((and bot-p A-p) 7)
585 ((and bot-p Z-p) 9)
586 (top-p 2)
587 (bot-p 8)
588 (A-p 4)
589 (Z-p 6)
590 (t 5))))
591 (yang (gnugo-yang (char-after p))))
592 (add-text-properties p (1+ p)
593 `(gnugo-position
594 ,position
595 gnugo-yin
596 ,yin
597 gnugo-yang
598 ,yang
599 category
600 ,(gnugo-yy yin yang)
601 front-sticky
602 (gnugo-position gnugo-yin))))
603 (unless (= (1- other-edge) p)
604 (add-text-properties (1+ p) (+ 2 p) ispc-props)
605 (put-text-property p (+ 2 p) 'intangible ival)))
606 (add-text-properties (1+ other-edge) right-empty grid-props)
607 (goto-char right-empty)
608 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
609 (let ((prop (if (string= "WH" (match-string 1))
610 :white-captures
611 :black-captures))
612 (beg (match-beginning 2))
613 (end (match-end 2)))
614 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
615 (gnugo-put prop (match-string-no-properties 2))))
616 (end-of-line)
617 (put-text-property right-empty (point) 'category %rpad)
618 (forward-char 1)))
619 (add-text-properties (1- (point)) (point-max) grid-props)
620 (skip-chars-forward " ")
621 (put-text-property (1- (point)) (point) 'category %gpad)
622 (put-text-property (point) (progn (end-of-line) (point))
623 'category %gspc)))
624
625 (defun gnugo-merge-showboard-results ()
626 (let ((aft (substring (gnugo--q "showboard") 3))
627 (adj 1) ; string to buffer position adjustment
628
629 (sync "[0-9]* stones$")
630 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
631 ;; restrictive a condition that fails in the case of:
632 ;;
633 ;; (before)
634 ;; ... WHITE has captured 1 stones
635 ;; ^
636 ;; (after)
637 ;; ... WHITE has captured 14 stones
638 ;; ^
639 ;;
640 ;; where the after count has more digits than the before count,
641 ;; but shares the same leading digits. In this case, the result
642 ;; of `compare-strings' points to the SPC following the before
643 ;; count (indicated by caret in this example).
644
645 (bef (buffer-substring-no-properties (point-min) (point-max)))
646 (bef-start 0) (bef-idx 0)
647 (aft-start 0) (aft-idx 0)
648 aft-sync-backtrack mis inc cut new very-strange
649
650 (inhibit-read-only t))
651 (while (numberp (setq mis (gnugo--compare-strings
652 bef bef-start
653 aft aft-start)))
654 (setq aft-sync-backtrack nil
655 inc (if (cl-minusp mis)
656 (- (+ 1 mis))
657 (- mis 1))
658 bef-idx (+ bef-start inc)
659 aft-idx (+ aft-start inc)
660 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
661 (match-end 0)
662 (1+ bef-idx))
663 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
664 (let ((peek (1- aft-idx)))
665 (while (not (= 32 (aref aft peek)))
666 (setq peek (1- peek)))
667 (setq aft-sync-backtrack (1+ peek))))
668 (match-end 0)
669 (1+ aft-idx))
670 cut (+ bef-idx adj
671 (if aft-sync-backtrack
672 (- aft-sync-backtrack aft-idx)
673 0)))
674 (goto-char cut)
675 (if aft-sync-backtrack
676 (let* ((asb aft-sync-backtrack)
677 (l-p (get-text-property cut :gnugo-cf))
678 (old-len (car l-p))
679 (capprop (cdr l-p))
680 (keep (text-properties-at cut)))
681 (setq new (substring aft asb (string-match " " aft asb)))
682 (plist-put keep :gnugo-cf (cons (length new) capprop))
683 (gnugo-put capprop new)
684 (delete-char old-len)
685 (insert (apply 'propertize new keep))
686 (incf adj (- (length new) old-len)))
687 (setq new (aref aft aft-idx))
688 (insert-and-inherit (char-to-string new))
689 (let ((yin (get-text-property cut 'gnugo-yin))
690 (yang (gnugo-yang new)))
691 (add-text-properties cut (1+ cut)
692 `(gnugo-yang
693 ,yang
694 category
695 ,(gnugo-yy yin yang))))
696 (delete-char 1)
697 ;; do this last to avoid complications w/ font lock
698 ;; (this also means we cannot include `intangible' in `front-sticky')
699 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
700 (put-text-property cut (1+ cut) 'intangible very-strange))))))
701
702 (defsubst gnugo--move-prop (node)
703 (or (assq :B node)
704 (assq :W node)))
705
706 (defun gnugo--as-pos-func ()
707 (lexical-let ((size (gnugo-get :SZ)))
708 ;; rv
709 (lambda (cc)
710 (if (string= "" cc)
711 "PASS"
712 (let ((col (aref cc 0)))
713 (format "%c%d"
714 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
715 (- size (- (aref cc 1) ?a))))))))
716
717 (defun gnugo-move-history (&optional rsel color)
718 "Determine and return the game's move history.
719 Optional arg RSEL controls side effects and return value.
720 If nil, display the history in the echo area as \"(N moves)\"
721 followed by the space-separated list of moves. When called
722 interactively with a prefix arg (i.e., RSEL is `(4)'), display
723 similarly, but suffix with the mover (either \":B\" or \":W\").
724 RSEL may also be a symbol that selects what to return:
725 car -- the most-recent move
726 cadr -- the next-to-most-recent move
727 two -- the last two moves as a list, oldest last
728 bpos -- the last stone on the board placed by COLOR
729 For all other values of RSEL, do nothing and return nil."
730 (interactive "P")
731 (let* ((monkey (gnugo-get :monkey))
732 (mem (aref monkey 0))
733 (as-pos (gnugo--as-pos-func))
734 acc node mprop move)
735 (cl-flet*
736 ((as-pos-maybe (x) (if (string= "resign" x)
737 x
738 (funcall as-pos x)))
739 (remem () (setq node (pop mem)
740 mprop (gnugo--move-prop node)))
741 (pretty () (setq move (as-pos-maybe (cdr mprop))))
742 (next (byp) (when (remem)
743 (pretty)
744 (push (if byp
745 (format "%s%s" move (car mprop))
746 move)
747 acc)))
748 (nn () (next nil))
749 (tell () (message "(%d moves) %s"
750 (length acc)
751 (mapconcat 'identity (nreverse acc) " ")))
752 (finish (byp) (while mem (next byp)) (tell)))
753 (pcase rsel
754 (`(4) (finish t))
755 (`nil (finish nil))
756 (`car (car (nn)))
757 (`cadr (nn) (car (nn)))
758 (`two (nn) (nn) acc)
759 (`bpos (loop with prop = (gnugo--prop<-color color)
760 when (and (remem)
761 (eq prop (car mprop))
762 (pretty)
763 (not (string= "resign" move))
764 (not (gnugo--passp move)))
765 return move))
766 (_ nil)))))
767
768 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
769 "A special mode for manipulating a GNUGO gametree.
770
771 \\{gnugo-frolic-mode-map}"
772 (setq truncate-lines t)
773 (buffer-disable-undo))
774
775 (defun gnugo-frolic-quit ()
776 "Kill GNUGO Frolic buffer and switch to its parent buffer."
777 (interactive)
778 (let ((bye (current-buffer)))
779 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
780 gnugo-frolic-parent-buffer))
781 (kill-buffer bye)))
782
783 (defun gnugo-frolic-return-to-origin ()
784 "Move point to the board's current position."
785 (interactive)
786 (if (not gnugo-frolic-origin)
787 (message "No origin")
788 (goto-char gnugo-frolic-origin)
789 (recenter (- (count-lines (line-beginning-position)
790 (point-max))))))
791
792 (defun gnugo-frolic-in-the-leaves ()
793 "Display the game tree in a *GNUGO Frolic* buffer.
794 This looks something like:
795
796 1 B -- E7 E7 E7 E7
797 2 W -- K10 K10 K10 K10
798 3 B -- E2 E2 E2 E2
799 4 W -- J3 J3 J3 J3
800 5 B -- A6 A6 A6 A6
801 6 W -- C9 C9 C9 C9
802
803 ├─────┬─────┐
804 │ │ │
805 7 B -- H7 !B8 C8 C8
806
807 ├─────┐
808 │ │
809 8 W -- D9 D9 D9 E9
810 9 B -- H8 H8
811 10 W -- PASS PASS
812 11 B -- H5 PASS
813 12 W -- PASS
814 13 B -- *PASS
815
816 with 0, 1, ... N (in this case N is 3) in the header line
817 to indicate the branches. Branch 0 is the \"main line\".
818 Point (* in this example) indicates the current position,
819 \"!\" indicates comment properties (e.g., B8, branch 1),
820 and moves not actually on the game tree (e.g., E7, branch 3)
821 are dimmed. Type \\[describe-mode] in that buffer for details."
822 (interactive)
823 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
824 "*GNUGO Frolic*")))
825 (from (or gnugo-frolic-parent-buffer
826 (current-buffer)))
827 ;; todo: use defface once we finally succumb to ‘customize’
828 (dimmed-node-face (list :inherit 'default
829 :foreground "gray50"))
830 (tree (gnugo-get :sgf-gametree))
831 (ends (copy-sequence (gnugo--tree-ends tree)))
832 (mnum (gnugo--tree-mnum tree))
833 (seen (gnugo--mkht))
834 (soil (gnugo--mkht))
835 (width (length ends))
836 (lanes (number-sequence 0 (1- width)))
837 (monkey (gnugo-get :monkey))
838 (as-pos (gnugo--as-pos-func))
839 (at (car (aref monkey 0)))
840 (bidx (aref monkey 1))
841 (valid (map 'vector (lambda (end)
842 (gethash (car end) mnum))
843 ends))
844 (max-move-num (apply 'max (append valid nil)))
845 (inhibit-read-only t)
846 finish)
847 (cl-flet
848 ((on (node)
849 (gethash node seen))
850 (emph (s face)
851 (propertize s 'face face))
852 (fsi (properties fmt &rest args)
853 (insert (apply 'propertize
854 (apply 'format fmt args)
855 properties))))
856 ;; breathe in
857 (loop
858 for bx below width
859 do (loop
860 with fork
861 for node in (aref ends bx)
862 do (if (setq fork (on node))
863 (cl-flet
864 ((tip-p (bix)
865 ;; todo: ignore non-"move" nodes
866 (eq node (car (aref ends bix))))
867 (link (other)
868 (pushnew other (gethash node soil))))
869 (unless (tip-p bx)
870 (unless (tip-p fork)
871 (link fork))
872 (link bx)))
873 (puthash node bx seen))
874 until fork))
875 ;; breathe out
876 (switch-to-buffer buf)
877 (gnugo-frolic-mode)
878 (erase-buffer)
879 (setq header-line-format
880 (lexical-let ((full (concat
881 (make-string 11 ?\s)
882 (mapconcat (lambda (n)
883 (format "%-5s" n))
884 lanes
885 " "))))
886 `((:eval
887 (funcall
888 ,(lambda ()
889 (cl-flet
890 ((sp (w) (propertize
891 " " 'display
892 `(space :width ,w))))
893 (concat
894 (when (eq 'left scroll-bar-mode)
895 (let ((w (or scroll-bar-width
896 (frame-parameter
897 nil 'scroll-bar-width)))
898 (cw (frame-char-width)))
899 (sp (if w
900 (/ w cw)
901 2))))
902 (let ((fc (fringe-columns 'left t)))
903 (unless (zerop fc)
904 (sp fc)))
905 (condition-case nil
906 (substring full (window-hscroll))
907 (error ""))))))))))
908 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
909 (set (make-local-variable 'gnugo-state)
910 (buffer-local-value 'gnugo-state from))
911 (loop
912 with props
913 for n ; move number
914 from max-move-num downto 1
915 do (setq props (list 'n n))
916 do
917 (loop
918 with (move forks br)
919 initially (progn
920 (goto-char (point-min))
921 (fsi props
922 "%3d %s -- "
923 n (aref ["W" "B"] (logand 1 n))))
924 for bx below width
925 do (let* ((node (unless (< (aref valid bx) n)
926 ;; todo: ignore non-"move" nodes
927 (pop (aref ends bx))))
928 (zow (list* 'bx bx props))
929 (ok (when node
930 (= bx (on node))))
931 (comment (when ok
932 (cdr (assq :C node))))
933 (s (cond ((not node) "")
934 ((not (setq move (gnugo--move-prop node))) "-")
935 (t (funcall as-pos (cdr move))))))
936 (when comment
937 (push comment zow)
938 (push 'help-echo zow))
939 (when (and ok (setq br (gethash node soil)))
940 (push (cons bx (sort br '<))
941 forks))
942 (fsi zow
943 "%c%-5s"
944 (if comment ?! ?\s)
945 (cond ((and (eq at node)
946 (or ok (= bx bidx)))
947 (when (= bx bidx)
948 (setq finish (point-marker)))
949 (emph s (list :inherit 'default
950 :foreground (frame-parameter
951 nil 'cursor-color))))
952 ((not ok)
953 (emph s dimmed-node-face))
954 (t s))))
955 finally do
956 (when (progn (fsi props "\n")
957 (setq forks (nreverse forks)))
958 (let* ((margin (make-string 11 ?\s))
959 (heads (mapcar #'car forks))
960 (tails (mapcar #'cdr forks)))
961 (cl-flet*
962 ((spaced (lanes func)
963 (mapconcat func lanes " "))
964 ;; live to play ~ ~ ()
965 ;; play to learn (+) (-) . o O
966 ;; learn to live --ttn .M. _____U
967 (dashed (lanes func) ;;; _____ ^^^^
968 (mapconcat func lanes "-----"))
969 (cnxn (lanes set)
970 (spaced lanes (lambda (bx)
971 (if (memq bx set)
972 "|"
973 " "))))
974 (pad-unless (condition)
975 (if condition
976 ""
977 " "))
978 (edge (set)
979 (insert margin
980 (cnxn lanes set)
981 "\n")))
982 (edge heads)
983 (loop with bef
984 for ls on forks
985 do (let* ((one (car ls))
986 (yes (append
987 ;; "aft" heads
988 (mapcar 'car (cdr ls))
989 ;; ‘bef’ tails
990 (apply 'append (mapcar 'cdr bef))))
991 (ord (sort one '<))
992 (beg (car ord))
993 (end (car (last ord))))
994 (cl-flet
995 ((also (b e) (cnxn (number-sequence b e)
996 yes)))
997 (insert
998 margin
999 (also 0 (1- beg))
1000 (pad-unless (zerop beg))
1001 (dashed (number-sequence beg end)
1002 (lambda (bx)
1003 (cond ((memq bx ord) "+")
1004 ((memq bx yes) "|")
1005 (t "-"))))
1006 (pad-unless (>= end width))
1007 (also (1+ end) (1- width))
1008 "\n"))
1009 (push one bef)))
1010 (edge (apply 'append tails))
1011 (aa2u (line-beginning-position
1012 (- (1+ (length forks))))
1013 (point))))))))
1014 (when finish
1015 (set (make-local-variable 'gnugo-frolic-origin) finish)
1016 (gnugo-frolic-return-to-origin))))
1017
1018 (defun gnugo--awake (how)
1019 ;; Valid HOW elements:
1020 ;; require-valid-branch
1021 ;; (line . numeric)
1022 ;; (line . move-string)
1023 ;; Invalid elements blissfully ignored. :-D
1024 (let* ((tree (gnugo-get :sgf-gametree))
1025 (ends (gnugo--tree-ends tree))
1026 (width (length ends))
1027 (monkey (gnugo-get :monkey))
1028 (line (case (cdr (assq 'line how))
1029 (numeric
1030 (count-lines (point-min) (line-beginning-position)))
1031 (move-string
1032 (save-excursion
1033 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1034 (match-string 0))))
1035 (t nil)))
1036 (col (current-column))
1037 (a (unless (> 10 col)
1038 (let ((try (/ (- col 10)
1039 6)))
1040 (unless (<= width try)
1041 try))))
1042 (rv (list a)))
1043 (when (memq 'require-valid-branch how)
1044 (unless a
1045 (user-error "No branch here")))
1046 (loop with omit = (cdr (assq 'omit how))
1047 for (name . value) in `((line . ,line)
1048 (bidx . ,(aref monkey 1))
1049 (monkey . ,monkey)
1050 (width . ,width)
1051 (ends . ,ends)
1052 (tree . ,tree))
1053 do (unless (memq name omit)
1054 (push value rv)))
1055 rv))
1056
1057 (defmacro gnugo--awakened (how &rest body)
1058 (declare (indent 1))
1059 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1060 with ls = (list 'a)
1061 for name in '(line bidx monkey
1062 width ends
1063 tree)
1064 do (unless (memq name omit)
1065 (push name ls))
1066 finally return ls)
1067 (gnugo--awake ',how)
1068 ,@body))
1069
1070 (defsubst gnugo--move-to-bcol (bidx)
1071 (move-to-column (+ 10 (* 6 bidx))))
1072
1073 (defun gnugo--swiz (direction &optional blunt)
1074 (gnugo--awakened (require-valid-branch
1075 (omit tree)
1076 (line . numeric))
1077 (let* ((b (cond ((numberp blunt)
1078 (unless (and (< -1 blunt)
1079 (< blunt width))
1080 (user-error "No such branch: %s" blunt))
1081 blunt)
1082 (t (mod (+ direction a) width))))
1083 (flit (if blunt (lambda (n)
1084 (cond ((= n a) b)
1085 ((= n b) a)
1086 (t n)))
1087 (lambda (n)
1088 (mod (+ direction n) width))))
1089 (was (copy-sequence ends))
1090 (new-bidx (funcall flit bidx)))
1091 (loop for bx below width
1092 do (aset ends (funcall flit bx)
1093 (aref was bx)))
1094 (unless (= new-bidx bidx)
1095 (aset monkey 1 new-bidx))
1096 (gnugo-frolic-in-the-leaves)
1097 (goto-char (point-min))
1098 (forward-line line)
1099 (gnugo--move-to-bcol b))))
1100
1101 (defun gnugo-frolic-exchange-left ()
1102 "Exchange the current branch with the one to its left."
1103 (interactive)
1104 (gnugo--swiz -1 t))
1105
1106 (defun gnugo-frolic-rotate-left ()
1107 "Rotate all branches left."
1108 (interactive)
1109 (gnugo--swiz -1))
1110
1111 (defun gnugo-frolic-exchange-right ()
1112 "Exchange the current branch with the one to its right."
1113 (interactive)
1114 (gnugo--swiz 1 t))
1115
1116 (defun gnugo-frolic-rotate-right ()
1117 "Rotate all branches right."
1118 (interactive)
1119 (gnugo--swiz 1))
1120
1121 (defun gnugo-frolic-set-as-main-line ()
1122 "Make the current branch the main line."
1123 (interactive)
1124 (gnugo--swiz nil 0))
1125
1126 (defun gnugo-frolic-prune-branch ()
1127 "Remove the current branch from the gametree.
1128 This fails if there is only one branch in the tree.
1129 This fails if the monkey is on the current branch
1130 \(a restriction that will probably be lifted Real Soon Now\)."
1131 (interactive)
1132 (gnugo--awakened (require-valid-branch
1133 (line . move-string))
1134 ;; todo: define meaningful eviction semantics; remove restriction
1135 (when (= a bidx)
1136 (user-error "Cannot prune with monkey on branch"))
1137 (when (= 1 width)
1138 (user-error "Cannot prune last remaining branch"))
1139 (let ((new (append ends nil)))
1140 ;; Explicit ignorance avoids byte-compiler warning.
1141 (ignore (pop (nthcdr a new)))
1142 (gnugo--set-tree-ends tree new))
1143 (when (< a bidx)
1144 (aset monkey 1 (decf bidx)))
1145 (gnugo-frolic-in-the-leaves)
1146 (when line
1147 (goto-char (point-min))
1148 (search-forward line)
1149 (gnugo--move-to-bcol (min a (- width 2))))))
1150
1151 (defun gnugo--sideways (backwards n)
1152 (gnugo--awakened ((omit tree ends monkey bidx line))
1153 (gnugo--move-to-bcol (mod (if backwards
1154 (- (or a width) n)
1155 (+ (or a -1) n))
1156 width))))
1157
1158 (defun gnugo-frolic-backward-branch (&optional n)
1159 "Move backward N (default 1) branches."
1160 (interactive "p")
1161 (gnugo--sideways t n))
1162
1163 (defun gnugo-frolic-forward-branch (&optional n)
1164 "Move forward N (default 1) branches."
1165 (interactive "p")
1166 (gnugo--sideways nil n))
1167
1168 (defun gnugo--vertical (n direction)
1169 (when (> 0 n)
1170 (setq n (- n)
1171 direction (- direction)))
1172 (gnugo--awakened ((line . numeric)
1173 (omit tree ends width monkey bidx))
1174 (let ((stop (if (> 0 direction)
1175 0
1176 (max 0 (1- (count-lines (point-min)
1177 (point-max))))))
1178 (col (unless a
1179 (current-column))))
1180 (loop while (not (= line stop))
1181 do (loop do (progn
1182 (forward-line direction)
1183 (incf line direction))
1184 until (get-text-property (point) 'n))
1185 until (zerop (decf n)))
1186 (if a
1187 (gnugo--move-to-bcol a)
1188 (move-to-column col)))))
1189
1190 (defun gnugo-frolic-previous-move (&optional n)
1191 "Move to the Nth (default 1) previous move."
1192 (interactive "p")
1193 (gnugo--vertical n -1))
1194
1195 (defun gnugo-frolic-next-move (&optional n)
1196 "Move to the Nth (default 1) next move."
1197 (interactive "p")
1198 (gnugo--vertical n 1))
1199
1200 (defun gnugo-boss-is-near ()
1201 "Do `bury-buffer' until the current one is not a GNU Board."
1202 (interactive)
1203 (while (gnugo-board-buffer-p)
1204 (bury-buffer)))
1205
1206 (defsubst gnugo--passp (string)
1207 (string= "PASS" string))
1208
1209 (defsubst gnugo--no-regrets (monkey ends)
1210 (eq (aref ends (aref monkey 1))
1211 (aref monkey 0)))
1212
1213 (defun gnugo--as-cc-func ()
1214 (lexical-let ((size (gnugo-get :SZ)))
1215 (lambda (pos)
1216 (let* ((col (aref pos 0))
1217 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1218 (two (+ ?a (- size (string-to-number
1219 (substring pos 1))))))
1220 (format "%c%c" one two)))))
1221
1222 (defsubst gnugo--decorate (node alist)
1223 ;; NB: ALIST should not have :B or :W keys.
1224 (setcdr (last node) alist))
1225
1226 (defun gnugo-close-game (end-time resign)
1227 (gnugo-put :game-end-time end-time)
1228 (let ((now (or end-time (current-time))))
1229 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1230 (cadr now))))
1231 (gnugo-put :game-over
1232 (if (or (eq t resign)
1233 (and (stringp resign)
1234 (string-match "[BW][+][Rr]esign" resign)))
1235 (cl-flet
1236 ((ls (color) (mapcar
1237 (lambda (x)
1238 (cons (list color)
1239 (split-string x)))
1240 (split-string
1241 (gnugo-query "worm_stones %s" color)
1242 "\n"))))
1243 (let ((live (append (ls "black") (ls "white"))))
1244 `((live ,@live)
1245 (dead))))
1246 (let ((dd (gnugo-query "dragon_data"))
1247 (start 0) mem color ent live dead)
1248 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1249 dd start)
1250 (setq mem (match-string 1 dd)
1251 color (match-string 2 dd)
1252 start (match-end 0)
1253 ent (cons (list color)
1254 (sort (gnugo-lsquery "dragon_stones %s" mem)
1255 'string<)))
1256 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1257 dd start)
1258 (if (match-string 2 dd)
1259 (push ent live)
1260 (push ent dead))
1261 (setq start (match-end 0)))
1262 `((live ,@live)
1263 (dead ,@dead))))))
1264
1265 (defun gnugo--unclose-game ()
1266 (gnugo--forget :game-over ; all those in -close-game
1267 :scoring-seed
1268 :game-end-time)
1269 (let* ((root (gnugo--root-node))
1270 (cur (assq :RE root)))
1271 (when cur
1272 (assert (not (eq cur (car root))) nil
1273 ":RE at head of root node: %S"
1274 root)
1275 (delq cur root))))
1276
1277 (defun gnugo-push-move (who move)
1278 (let* ((simple (booleanp who))
1279 (ucolor (gnugo-get :user-color))
1280 (color (if simple
1281 (if who
1282 ucolor
1283 (gnugo-get :gnugo-color))
1284 who))
1285 (start (gnugo-get :waiting-start))
1286 (now (current-time))
1287 (resignp (string= "resign" move))
1288 (passp (gnugo--passp move))
1289 (head (gnugo-move-history 'car))
1290 (onep (and head (gnugo--passp head)))
1291 (donep (or resignp (and onep passp))))
1292 (unless resignp
1293 (gnugo--q/ue "play %s %s" color move))
1294 (unless passp
1295 (gnugo-merge-showboard-results))
1296 (gnugo-put :last-mover color)
1297 (when (if simple
1298 who
1299 (string= ucolor color))
1300 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1301 ;; update :sgf-gametree and :monkey
1302 (let* ((property (gnugo--prop<-color color))
1303 (pair (cons property (cond (resignp move)
1304 (passp "")
1305 (t (funcall (gnugo--as-cc-func)
1306 move)))))
1307 (fruit (list pair))
1308 (monkey (gnugo-get :monkey))
1309 (mem (aref monkey 0))
1310 (tip (car mem))
1311 (tree (gnugo-get :sgf-gametree))
1312 (ends (gnugo--tree-ends tree))
1313 (mnum (gnugo--tree-mnum tree))
1314 (count (length ends))
1315 (tip-move-num (gethash tip mnum))
1316 (bidx (aref monkey 1)))
1317 ;; Detect déjà-vu. That is, when placing "A", avoid:
1318 ;;
1319 ;; X---Y---A new
1320 ;; \
1321 ;; --A---B old
1322 ;;
1323 ;; (such "variations" do not actually vary!) in favor of:
1324 ;;
1325 ;; X---Y---A new
1326 ;; \
1327 ;; --B old
1328 ;;
1329 ;; This linear search loses for multiple ‘old’ w/ "A",
1330 ;; a very unusual (but not invalid, sigh) situation.
1331 (loop
1332 with (bx previous)
1333 for i
1334 ;; Start with latest / highest likelihood for hit.
1335 ;; (See "to the right" comment, below.)
1336 from (if (gnugo--no-regrets monkey ends)
1337 1
1338 0)
1339 below count
1340 if (setq bx (mod (+ bidx i) count)
1341 previous
1342 (loop with node
1343 for m on (aref ends bx)
1344 while (< tip-move-num
1345 (gethash (setq node (car m))
1346 mnum))
1347 if (eq mem (cdr m))
1348 return
1349 (when (equal pair (assq property node))
1350 m)
1351 finally return
1352 nil))
1353 ;; yes => follow
1354 return
1355 (progn
1356 (unless (= bidx bx)
1357 (rotatef (aref ends bidx)
1358 (aref ends bx)))
1359 (setq mem previous))
1360 ;; no => construct
1361 finally do
1362 (progn
1363 (unless (gnugo--no-regrets monkey ends)
1364 (setq ends (gnugo--set-tree-ends
1365 tree (let ((ls (append ends nil)))
1366 ;; copy old to the right of new
1367 (push mem (nthcdr bidx ls))
1368 ls))))
1369 (puthash fruit (1+ (gethash tip mnum)) mnum)
1370 (push fruit mem)
1371 (aset ends bidx mem)))
1372 (setf (aref monkey 0) mem))
1373 (when start
1374 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1375 (when donep
1376 (gnugo-close-game now resignp))
1377 (gnugo-put :waiting-start (and (not donep) now))
1378 donep))
1379
1380 (defun gnugo-venerate (yin yang)
1381 (let* ((fg-yy (gnugo-yy yin yang))
1382 (fg-disp (or (get fg-yy 'display)
1383 (get fg-yy 'do-not-display)))
1384 (fg-data (plist-get (cdr fg-disp) :data))
1385 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1386 (bg-disp (or (get bg-yy 'display)
1387 (get bg-yy 'do-not-display)))
1388 (bg-data (plist-get (cdr bg-disp) :data))
1389 (bop (lambda (s)
1390 (let* ((start 0)
1391 (ncolors
1392 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1393 (setq start (match-end 0))
1394 (string-to-number (match-string 1 s)))))
1395 (while (and (not (cl-minusp ncolors))
1396 (string-match ",\n" s start))
1397 (setq start (match-end 0)
1398 ncolors (1- ncolors)))
1399 (string-match "\"" s start)
1400 (match-end 0))))
1401 (new (copy-sequence fg-data))
1402 (lx (length fg-data))
1403 (sx (funcall bop fg-data))
1404 (sb (funcall bop bg-data))
1405 (color-key (aref new sx))) ; blech, heuristic
1406 (while (< sx lx)
1407 (when (and (not (= color-key (aref new sx)))
1408 (cl-plusp (random 4)))
1409 (aset new sx (aref bg-data sb)))
1410 (incf sx)
1411 (incf sb))
1412 (create-image new 'xpm t :ascent 'center)))
1413
1414 (defun gnugo-refresh (&optional nocache)
1415 "Update GNUGO Board buffer display.
1416 While a game is in progress, parenthesize the last-played stone (no parens
1417 for pass). If the buffer is currently displayed in the selected window,
1418 recenter the board (presuming there is extra space in the window). Update
1419 the mode line. Lastly, move point to the last position played by the user,
1420 if that move was not a pass.
1421
1422 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1423 be slow. (This should normally be unnecessary; specify it only if the display
1424 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1425 its move."
1426 (interactive "P")
1427 (let* ((last-mover (gnugo-get :last-mover))
1428 (other (gnugo-other last-mover))
1429 (move (gnugo-move-history 'car))
1430 (game-over (gnugo-get :game-over))
1431 (inhibit-read-only t)
1432 window last)
1433 (when (and nocache (not (gnugo-get :waiting)))
1434 (gnugo-propertize-board-buffer))
1435 ;; last move
1436 (when move
1437 (destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1438 (if (member move '("PASS" "resign"))
1439 (mapc 'delete-overlay (list l-ov r-ov))
1440 (gnugo-goto-pos move)
1441 (let* ((p (point))
1442 (hspec (gnugo-get :highlight-last-move-spec))
1443 (display-value (nth 0 hspec))
1444 (l-offset (nth 1 hspec))
1445 (l-new-pos (+ p l-offset))
1446 (r-action (nth 2 hspec)))
1447 (overlay-put l-ov 'display
1448 (if (functionp display-value)
1449 (funcall display-value p)
1450 display-value))
1451 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1452 (if r-action
1453 (funcall r-action r-ov)
1454 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1455 ;; buffer name
1456 (rename-buffer (concat (gnugo-get :diamond)
1457 (if game-over
1458 (format "%s(game over)"
1459 (if (string= move "resign")
1460 (concat move "ation ")
1461 ""))
1462 (format "%s(%s to play)"
1463 (if move (concat move " ") "")
1464 other))))
1465 ;; pall of death
1466 (when game-over
1467 (let ((live (cdr (assq 'live game-over)))
1468 (dead (cdr (assq 'dead game-over)))
1469 p pall)
1470 (unless (eq game-over (get-text-property 1 'game-over))
1471 (dolist (group (append live dead))
1472 (dolist (pos (cdr group))
1473 (gnugo-goto-pos pos)
1474 (setq p (point))
1475 (put-text-property p (1+ p) 'group group)))
1476 (put-text-property 1 2 'game-over game-over))
1477 (dolist (group live)
1478 (when (setq pall (cdar group))
1479 (mapc 'delete-overlay pall)
1480 (setcdr (car group) nil)))
1481 (dolist (group dead)
1482 (unless (cdar group)
1483 (let (ov pall c (color (caar group)))
1484 (setq c (if (gnugo--blackp color) "x" "o"))
1485 (dolist (pos (cdr group))
1486 (gnugo-goto-pos pos)
1487 (setq p (point) ov (make-overlay p (1+ p)))
1488 (overlay-put
1489 ov 'display
1490 (if (gnugo-get :display-using-images)
1491 ;; respect the dead individually; it takes more time
1492 ;; but that's not a problem (for them)
1493 (gnugo-venerate (get-text-property p 'gnugo-yin)
1494 (gnugo-yang (aref (upcase c) 0)))
1495 (propertize c 'face 'font-lock-warning-face)))
1496 (push ov pall))
1497 (setcdr (car group) pall))))))
1498 ;; window update
1499 (when (setq window (get-buffer-window (current-buffer)))
1500 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1501 (size (gnugo-get :SZ))
1502 (under10p (< size 10))
1503 (mul (gnugo-get :mul))
1504 (h (- (truncate (- (window-height window)
1505 (* size (cdr mul))
1506 (if gridp 2 0))
1507 2)
1508 (if gridp 0 1)))
1509 (edges (window-edges window))
1510 (right-w-edge (nth 2 edges))
1511 (avail-width (- right-w-edge (nth 0 edges)))
1512 (wmul (car mul))
1513 (imagesp (symbol-plist (gnugo-f 'ispc)))
1514 (w (/ (- avail-width
1515 (* size wmul)
1516 (if imagesp
1517 0
1518 (1- size))
1519 2 ; between board and grid
1520 (if gridp
1521 (if under10p 2 4)
1522 0))
1523 2.0)))
1524 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1525 `(display ,(make-string h 10))
1526 '(invisible :nogrid)))
1527 (gpad . (display
1528 (space :align-to
1529 ,(+ w
1530 2.0
1531 (cond (imagesp (+ (* 0.5 wmul)
1532 (if under10p
1533 -0.5
1534 0.5)))
1535 (under10p 0)
1536 (t 1))))))
1537 (gspc . ,(when imagesp
1538 `(display
1539 (space-width
1540 ,(-
1541 ;; DWR: image width alone => OBOE!
1542 ;;- wmul
1543 ;; NB: ‘(* wmul cw)’ is the same
1544 ;; as ‘(car (image-size ... t))’.
1545 (let ((cw (frame-char-width)))
1546 (/ (+ 1.0 (* wmul cw))
1547 cw))
1548 1.0)))))
1549 (lpad . ,(let ((d `(display (space :align-to ,w))))
1550 ;; We distinguish between these cases to
1551 ;; workaround a display bug whereby the
1552 ;; `before-string' is omitted entirely (not
1553 ;; rendered) when interacting w/ the text
1554 ;; mode last-move left-paren for moves in
1555 ;; column A.
1556 (if gridp
1557 `(before-string
1558 ,(apply 'propertize " " d))
1559 d)))
1560 (rpad . (display
1561 (space :align-to ,(1- avail-width))))))
1562 (setplist (gnugo-f (car pair)) (cdr pair)))))
1563 ;; mode line update
1564 (let ((cur (gnugo-get :mode-line)))
1565 (unless (equal cur gnugo-mode-line)
1566 (setq cur gnugo-mode-line)
1567 (gnugo-put :mode-line cur)
1568 (gnugo-put :mode-line-form
1569 (cond ((stringp cur)
1570 (setq cur (copy-sequence cur))
1571 (let (acc cut c)
1572 (while (setq cut (string-match "~[bwpmtu]" cur))
1573 (aset cur cut ?%)
1574 (setq c (aref cur (incf cut)))
1575 (aset cur cut ?s)
1576 (push
1577 `(,(intern (format "squig-%c" c))
1578 ,(case c
1579 (?b '(or (gnugo-get :black-captures) 0))
1580 (?w '(or (gnugo-get :white-captures) 0))
1581 (?p '(gnugo-current-player))
1582 (?t '(let ((ws (gnugo-get :waiting-start)))
1583 (if ws
1584 (cadr (time-since ws))
1585 "-")))
1586 (?u '(or (gnugo-get :last-waiting) "-"))
1587 (?m '(let ((tree (gnugo-get :sgf-gametree))
1588 (monkey (gnugo-get :monkey)))
1589 (gethash (car (aref monkey 0))
1590 (gnugo--tree-mnum tree)
1591 ;; should be unnecessary
1592 "?")))))
1593 acc))
1594 `(let ,(delete-dups (copy-sequence acc))
1595 (format ,cur ,@(reverse (mapcar 'car acc))))))
1596 (t cur))))
1597 (let ((form (gnugo-get :mode-line-form)))
1598 (setq mode-line-process
1599 (and form
1600 ;; this dynamicism is nice but excessive in its wantonness
1601 ;;- `(" [" (:eval ,form) "]")
1602 ;; this dynamicism is ok because the user triggers it
1603 (list (format " [%s]" (eval form))
1604 '(:eval (if (gnugo-get :abd)
1605 " Abd"
1606 ""))))))
1607 (force-mode-line-update))
1608 ;; last user move
1609 (when (setq last (gnugo-get :last-user-bpos))
1610 (gnugo-goto-pos last))))
1611
1612 (defun gnugo--finish-move (buf)
1613 (run-hooks 'gnugo-post-move-hook)
1614 (with-current-buffer buf
1615 (gnugo-refresh)))
1616
1617 ;;;---------------------------------------------------------------------------
1618 ;;; Game play actions
1619
1620 (defun gnugo--rename-buffer-portion (&optional back)
1621 (let ((old "to play")
1622 (new "waiting for suggestion"))
1623 (when back
1624 (rotatef old new))
1625 (let ((name (buffer-name)))
1626 (when (string-match old name)
1627 (rename-buffer (replace-match new t t name))))))
1628
1629 (defun gnugo-get-move-insertion-filter (proc string)
1630 (with-current-buffer (process-buffer proc)
1631 (let* ((so-far (gnugo-get :get-move-string))
1632 (full (gnugo-put :get-move-string (concat so-far string))))
1633 (when (string-match "^= \\(.+\\)\n\n" full)
1634 (destructuring-bind (pos-or-pass color . suggestion)
1635 (cons (match-string 1 full)
1636 (gnugo-get :waiting))
1637 (gnugo--forget :get-move-string
1638 :waiting)
1639 (if suggestion
1640 (progn
1641 (gnugo--rename-buffer-portion t)
1642 (unless (or (gnugo--passp full)
1643 (eq 'nowarp suggestion))
1644 (gnugo-goto-pos pos-or-pass))
1645 (message "%sSuggestion: %s"
1646 (gnugo-get :diamond)
1647 pos-or-pass))
1648 (let* ((donep (gnugo-push-move color pos-or-pass))
1649 (buf (current-buffer)))
1650 (gnugo--finish-move buf)
1651 (when (gnugo-get :abd)
1652 (gnugo-put :abd
1653 (unless donep
1654 (run-at-time
1655 2 ;;; sec (frettoloso? dubioso!)
1656 nil (lambda (buf color)
1657 (with-current-buffer buf
1658 (gnugo-get-move color)))
1659 buf
1660 (gnugo-other color))))))))))))
1661
1662 (defun gnugo-get-move (color &optional suggestion)
1663 (gnugo-put :waiting (cons color suggestion))
1664 (gnugo--begin-exchange
1665 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1666 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1667 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1668 (concat "reg_genmove " color))
1669 (accept-process-output))
1670
1671 (defun gnugo-cleanup ()
1672 (when (gnugo-board-buffer-p)
1673 (unless (zerop (buffer-size))
1674 (message "Thank you for playing GNU Go."))
1675 (mapc (lambda (sym)
1676 (setplist sym nil) ; "...is next to fordliness." --Huxley
1677 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1678 ;; No worries, things will be Much Better w/ structs, RSN...
1679 (unintern sym nil))
1680 (append (gnugo-get :all-yy)
1681 (mapcar 'gnugo-f
1682 '(anim
1683 tpad
1684 gpad
1685 gspc
1686 lpad
1687 rpad
1688 ispc))))
1689 (setq gnugo-state nil)))
1690
1691 (defun gnugo-position ()
1692 (or (get-text-property (point) 'gnugo-position)
1693 (user-error "Not a proper position point")))
1694
1695 (defun gnugo-request-suggestion (&optional nowarp)
1696 "Request a move suggestion from GNU Go.
1697 After some time (during which you can do other stuff),
1698 Emacs displays the suggestion in the echo area and warps the
1699 cursor to the suggested position. Prefix arg inhibits warp."
1700 (interactive "P")
1701 (gnugo-gate t)
1702 (gnugo--rename-buffer-portion)
1703 (gnugo-get-move (gnugo-get :user-color)
1704 (if nowarp
1705 'nowarp
1706 t)))
1707
1708 (defun gnugo--user-play (pos-or-pass)
1709 (gnugo-gate t)
1710 (let ((donep (gnugo-push-move t pos-or-pass))
1711 (buf (current-buffer)))
1712 (gnugo--finish-move buf)
1713 (unless donep
1714 (with-current-buffer buf
1715 (gnugo-get-move (gnugo-get :gnugo-color))))))
1716
1717 (defun gnugo-move ()
1718 "Make a move on the GNUGO Board buffer.
1719 The position is computed from current point.
1720 Signal error if done out-of-turn or if game-over.
1721 To start a game try M-x gnugo."
1722 (interactive)
1723 (gnugo--user-play (gnugo-position)))
1724
1725 (defun gnugo-mouse-move (e)
1726 "Do `gnugo-move' at mouse location."
1727 (interactive "@e")
1728 (mouse-set-point e)
1729 (when (memq (following-char) '(?. ?+))
1730 (gnugo-move)))
1731
1732 (defun gnugo-pass ()
1733 "Make a pass on the GNUGO Board buffer.
1734 Signal error if done out-of-turn or if game-over.
1735 To start a game try M-x gnugo."
1736 (interactive)
1737 (gnugo--user-play "PASS"))
1738
1739 (defun gnugo-mouse-pass (e)
1740 "Do `gnugo-pass' at mouse location."
1741 (interactive "@e")
1742 (mouse-set-point e)
1743 (gnugo-pass))
1744
1745 (defun gnugo-resign ()
1746 (interactive)
1747 (gnugo-gate t)
1748 (if (not (y-or-n-p "Resign? "))
1749 (message "(not resigning)")
1750 (gnugo-push-move t "resign")
1751 (gnugo-refresh)))
1752
1753 (defun gnugo-animate-group (w/d)
1754 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1755 (let* ((pos (gnugo-position))
1756 (orig-b-m-p (buffer-modified-p))
1757 blurb stones)
1758 (unless (memq (following-char) '(?X ?O))
1759 (user-error "No stone at %s" pos))
1760 (setq blurb (message "Computing %s stones ..." w/d)
1761 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1762 (message "%s %s in group." blurb (length stones))
1763 (setplist (gnugo-f 'anim) nil)
1764 (let* ((spec (if (gnugo-get :display-using-images)
1765 (loop with yin = (get-text-property (point) 'gnugo-yin)
1766 with yang = (gnugo-yang (following-char))
1767 with up = (get (gnugo-yy yin yang t) 'display)
1768 with dn = (get (gnugo-yy yin yang) 'display)
1769 for n below (length gnugo-animation-string)
1770 collect (if (zerop (logand 1 n))
1771 dn up))
1772 (split-string gnugo-animation-string "" t)))
1773 (cell (list spec))
1774 (ovs (save-excursion
1775 (mapcar (lambda (pos)
1776 (gnugo-goto-pos pos)
1777 (let* ((p (point))
1778 (ov (make-overlay p (1+ p))))
1779 (overlay-put ov 'category (gnugo-f 'anim))
1780 (overlay-put ov 'priority most-positive-fixnum)
1781 ov))
1782 stones))))
1783 (setplist (gnugo-f 'anim) (cons 'display cell))
1784 (while (and (cdr spec) ; let last linger lest levity lost
1785 (sit-for 0.08675309)) ; jenny jenny i got your number...
1786 (setcar cell (setq spec (cdr spec)))
1787 ;; Force redisplay of overlays.
1788 (set-buffer-modified-p orig-b-m-p))
1789 (sit-for 5)
1790 (mapc 'delete-overlay ovs)
1791 t)))
1792
1793 (defun gnugo-display-group-data (command buffer-name)
1794 (message "Computing %s ..." command)
1795 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1796 (switch-to-buffer buffer-name)
1797 (erase-buffer)
1798 (insert data))
1799 (message "Computing %s ... done." command))
1800
1801 (defun gnugo-worm-stones ()
1802 "In the GNUGO Board buffer, animate \"worm\" at current position.
1803 Signal error if done out-of-turn or if game-over.
1804 See variable `gnugo-animation-string' for customization."
1805 (interactive)
1806 (gnugo-gate)
1807 (gnugo-animate-group 'worm))
1808
1809 (defun gnugo-worm-data ()
1810 "Display in another buffer data from \"worm\" at current position.
1811 Signal error if done out-of-turn or if game-over."
1812 (interactive)
1813 (gnugo-gate)
1814 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1815
1816 (defun gnugo-dragon-stones ()
1817 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1818 Signal error if done out-of-turn or if game-over.
1819 See variable `gnugo-animation-string' for customization."
1820 (interactive)
1821 (gnugo-gate)
1822 (gnugo-animate-group 'dragon))
1823
1824 (defun gnugo-dragon-data ()
1825 "Display in another buffer data from \"dragon\" at current position.
1826 Signal error if done out-of-turn or if game-over."
1827 (interactive)
1828 (gnugo-gate)
1829 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1830
1831 (defun gnugo-estimate-score ()
1832 "Display estimated score of a game of GNU Go.
1833 Output includes number of stones on the board and number of stones
1834 captured by each player, and the estimate of who has the advantage (and
1835 by how many stones)."
1836 (interactive)
1837 (message "Est.score ...")
1838 (let ((black (gnugo--count-query "list_stones black"))
1839 (white (gnugo--count-query "list_stones white"))
1840 (black-captures (gnugo-query "captures black"))
1841 (white-captures (gnugo-query "captures white"))
1842 (est (gnugo-query "estimate_score")))
1843 ;; might as well update this
1844 (gnugo-put :black-captures black-captures)
1845 (gnugo-put :white-captures white-captures)
1846 (message "Est.score ... B %s %s | W %s %s | %s"
1847 black black-captures white white-captures est)))
1848
1849 (defun gnugo-write-sgf-file (filename)
1850 "Save the game history to FILENAME (even if unfinished).
1851 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1852 (interactive "FWrite game as SGF file: ")
1853 (when (and (file-exists-p filename)
1854 (not (y-or-n-p "File exists. Continue? ")))
1855 (user-error "Not writing %s" filename))
1856 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1857 (set-buffer-modified-p nil))
1858
1859 (defun gnugo--who-is-who (wait play samep)
1860 (message "GNU Go %splays as %s, you as %s (%s)"
1861 (if samep "" "now ")
1862 wait play (if samep
1863 "as before"
1864 "NOTE: this is a switch!")))
1865
1866 (defsubst gnugo--nodep (x)
1867 (keywordp (caar x)))
1868
1869 (defun gnugo--SZ! (size)
1870 (gnugo-put :SZ size)
1871 (gnugo-put :center-position
1872 (funcall (gnugo--as-pos-func)
1873 (let ((c (+ -1 ?a (truncate (1+ size) 2))))
1874 (string c c)))))
1875
1876 (defun gnugo--plant-and-climb (collection &optional sel)
1877 (gnugo-put :sgf-collection collection)
1878 (let ((tree (nth (or sel 0) collection)))
1879 (gnugo-put :sgf-gametree tree)
1880 (gnugo-put :monkey (vector
1881 ;; mem
1882 (aref (gnugo--tree-ends tree) 0)
1883 ;; bidx
1884 0))
1885 tree))
1886
1887 (defun gnugo-read-sgf-file (filename)
1888 "Load the first game tree from FILENAME, a file in SGF format."
1889 (interactive "fSGF file to load: ")
1890 (when (file-directory-p filename)
1891 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1892 (let (play wait samep coll tree game-over)
1893 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1894 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1895 (setq play (gnugo--q/ue "loadsgf %s" (expand-file-name filename))
1896 wait (gnugo-other play)
1897 samep (string= (gnugo-get :user-color) play))
1898 (gnugo-put :last-mover wait)
1899 (unless samep
1900 (gnugo-put :gnugo-color wait)
1901 (gnugo-put :user-color play))
1902 (setq coll (gnugo/sgf-create filename)
1903 tree (gnugo--plant-and-climb
1904 coll (let ((n (length coll)))
1905 ;; This is better:
1906 ;; (if (= 1 n)
1907 ;; 0
1908 ;; (let* ((q (format "Which game? (1-%d)" n))
1909 ;; (choice (1- (read-number q 1))))
1910 ;; (if (and (< -1 choice) (< choice n))
1911 ;; choice
1912 ;; (message "(Selecting the first game)")
1913 ;; 0)))
1914 ;; but this is what we use (for now) to accomodate
1915 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1916 (unless (= 1 n)
1917 (message "(Selecting the first game)"))
1918 0)))
1919 ;; This is deliberately undocumented for now.
1920 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1921 (when (setq game-over (or (gnugo--root-prop :RE tree)
1922 (when (equal '("PASS" "PASS")
1923 (gnugo-move-history 'two))
1924 'two-passes)))
1925 (gnugo-close-game nil game-over))
1926 (gnugo-put :last-user-bpos
1927 (gnugo-move-history 'bpos (gnugo-get :user-color)))
1928 (gnugo-refresh t)
1929 (set-buffer-modified-p nil)
1930 (gnugo--who-is-who wait play samep)))
1931
1932 (defun gnugo--mem-with-played-stone (pos)
1933 (let ((color (case (following-char)
1934 (?X :B)
1935 (?O :W))))
1936 (when color
1937 (loop with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
1938 for mem on (aref (gnugo-get :monkey) 0)
1939 when (equal fruit (caar mem))
1940 return mem
1941 finally return nil))))
1942
1943 (defun gnugo-magic-undo (spec &optional noalt keep)
1944 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1945 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1946 check that the position is occupied by a stone of the user's color,
1947 and if so, remove moves from the history until that position is clear.
1948 If SPEC is a positive number, remove exactly that many moves from the
1949 history, signaling an error if the history is exhausted before finishing.
1950 If SPEC Is 0 (zero), remove either one or two moves,
1951 so that you are to play next.
1952 If SPEC is not recognized, signal \"bad spec\" error.
1953
1954 Refresh the board for each move undone. If (in the case where SPEC is
1955 a number) after finishing, the color to play is not the user's color,
1956 schedule a move by GNU Go.
1957
1958 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1959 turn to play. Optional second arg NOALT non-nil inhibits this.
1960
1961 Optional third arg KEEP non-nil means do not prune the undone moves
1962 from the gametree, such that they become a sub-gametree (variation)
1963 when play resumes."
1964 (gnugo-gate)
1965 (let* ((n 0)
1966 (user-color (gnugo-get :user-color))
1967 (monkey (gnugo-get :monkey))
1968 (tree (gnugo-get :sgf-gametree))
1969 (ends (gnugo--tree-ends tree))
1970 (remorseful (not (gnugo--no-regrets monkey ends)))
1971 done)
1972 (cond ((numberp spec)
1973 (setq n (if (zerop spec)
1974 (if (string= user-color (gnugo-get :last-mover))
1975 1
1976 2)
1977 spec)
1978 done (lambda () (zerop n))))
1979 ((string-match "^[a-z]" spec)
1980 (let ((pos (upcase spec)))
1981 (setq done `(lambda ()
1982 (gnugo-goto-pos ,pos)
1983 (memq (following-char) '(?. ?+))))
1984 (when (funcall done)
1985 (user-error "%s already clear" pos))
1986 (when (= (save-excursion
1987 (gnugo-goto-pos pos)
1988 (following-char))
1989 (if (gnugo--blackp user-color)
1990 ?O
1991 ?X))
1992 (user-error "%s not occupied by %s" pos user-color))))
1993 (t (user-error "Bad spec: %S" spec)))
1994 (when (gnugo-get :game-over)
1995 (gnugo--unclose-game))
1996 (while (not (funcall done))
1997 (gnugo--q/ue "undo")
1998 (pop (aref monkey 0))
1999 (gnugo-put :last-mover (gnugo-current-player))
2000 (gnugo-merge-showboard-results) ; all
2001 (gnugo-refresh) ; this
2002 (decf n) ; is
2003 (redisplay)) ; eye candy
2004 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
2005
2006 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
2007 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
2008 ubpos
2009 (gnugo-get :center-position)))
2010 (gnugo-refresh t)
2011 (unless (or keep remorseful)
2012 (aset ends (aref monkey 1) (aref monkey 0)))
2013 (when (and ulastp (not noalt))
2014 (gnugo-get-move (gnugo-get :gnugo-color))))))
2015
2016 (defun gnugo-undo-one-move (&optional me-next)
2017 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
2018 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
2019 Prefix arg ME-NEXT means to arrange for you to play
2020 the color of the next move (and GNU Go the opposite).
2021 This is useful after loading an SGF file whose last
2022 move was done by the color you prefer to play:
2023 \\[gnugo-read-sgf-file] FILENAME RET
2024 C-u \\[gnugo-undo-one-move]
2025
2026 See also `gnugo-undo-two-moves'."
2027 (interactive "P")
2028 (gnugo-gate)
2029 (when me-next
2030 (let* ((play (gnugo-get :last-mover))
2031 (wait (gnugo-other play)))
2032 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
2033 (gnugo-put :user-color play)
2034 (gnugo-put :gnugo-color wait)))
2035 (gnugo-magic-undo 1 t))
2036
2037 (defun gnugo-undo-two-moves ()
2038 "Undo a pair of moves (GNU Go's and yours).
2039 However, if you are the last mover, undo only one move.
2040 Regardless, after undoing, it is your turn to play again."
2041 (interactive)
2042 (gnugo-gate)
2043 (gnugo-magic-undo 0))
2044
2045 (defun gnugo-oops (&optional position)
2046 "Like `gnugo-undo-two-moves', but keep the undone moves.
2047 The kept moves become a sub-gametree (variation) when play resumes.
2048 Prefix arg means, instead, undo repeatedly up to and including
2049 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2050 (interactive "P")
2051 (gnugo-gate)
2052 (gnugo-magic-undo (if position
2053 (gnugo-position)
2054 0)
2055 nil t))
2056
2057 (defun gnugo-okay (&optional full)
2058 "Redo a pair of undone moves.
2059 Prefix arg means to redo all the undone moves."
2060 (interactive "P")
2061 (gnugo-gate)
2062 (let* ((tree (gnugo-get :sgf-gametree))
2063 (ends (gnugo--tree-ends tree))
2064 (monkey (gnugo-get :monkey)))
2065 (if (gnugo--no-regrets monkey ends)
2066 (message "Oop ack!")
2067 (let* ((as-pos (gnugo--as-pos-func))
2068 (mnum (gnugo--tree-mnum tree))
2069 (mem (aref monkey 0))
2070 (bidx (aref monkey 1))
2071 (end (aref ends bidx))
2072 (ucolor (gnugo-get :user-color))
2073 (uprop (gnugo--prop<-color ucolor)))
2074 (cl-flet ((mvno (node) (gethash node mnum)))
2075 (loop
2076 with ok = (if full
2077 (mvno (car end))
2078 (+ 2 (mvno (car mem))))
2079 with (node move todo)
2080 for ls on end
2081 do (progn
2082 (setq node (car ls)
2083 move (gnugo--move-prop node))
2084 (when (and move (>= ok (mvno node)))
2085 (let ((userp (eq uprop (car move))))
2086 (push (list userp
2087 (funcall as-pos (cdr move)))
2088 todo))))
2089 until (eq mem (cdr ls))
2090 finally do
2091 (loop
2092 for (userp pos) in todo
2093 do (progn
2094 (gnugo-push-move userp pos)
2095 (gnugo-refresh)
2096 (redisplay)))))))))
2097
2098 (defun gnugo-display-final-score (&optional comment)
2099 "Display final score and other info in another buffer (when game over).
2100 If the game is still ongoing, Emacs asks if you wish to stop play (by
2101 making sure two \"pass\" moves are played consecutively, if necessary).
2102 Also, add the `:RE' SGF property to the root node of the game tree.
2103 Prefix arg COMMENT means to also attach the text (slightly compacted)
2104 to the last move, as a comment."
2105 (interactive "P")
2106 (let ((game-over (gnugo-get :game-over)))
2107 (unless (or game-over
2108 (and (not (gnugo-get :waiting))
2109 (y-or-n-p "Game still in play. Stop play now? ")))
2110 (user-error "Sorry, game still in play"))
2111 (unless game-over
2112 (cl-flet
2113 ((pass (userp)
2114 (message "Playing PASS for %s ..."
2115 (gnugo-get (if userp :user-color :gnugo-color)))
2116 (sit-for 1)
2117 (gnugo-push-move userp "PASS")))
2118 (unless (pass t)
2119 (pass nil)))
2120 (gnugo-refresh)
2121 (sit-for 3)))
2122 (let ((b= " Black = ")
2123 (w= " White = ")
2124 (res (when (string= "resign" (gnugo-move-history 'car))
2125 (gnugo-get :last-mover)))
2126 blurb result)
2127 (if res
2128 (setq blurb (list
2129 (format "%s wins.\n"
2130 (substring (if (= ?b (aref res 0)) w= b=)
2131 3 8))
2132 "The game is over.\n"
2133 (format "Resignation by %s.\n" res))
2134 result (concat (upcase (substring (gnugo-other res) 0 1))
2135 "+Resign"))
2136 (message "Computing final score ...")
2137 (let* ((g-over (gnugo-get :game-over))
2138 (live (cdr (assq 'live g-over)))
2139 (dead (cdr (assq 'dead g-over)))
2140 (seed (gnugo-get :scoring-seed))
2141 (terr-q (format "final_status_list %%s_territory %d" seed))
2142 (terr "territory")
2143 (capt "captures")
2144 (b-terr (gnugo--count-query terr-q "black"))
2145 (w-terr (gnugo--count-query terr-q "white"))
2146 (b-capt (string-to-number (gnugo-get :black-captures)))
2147 (w-capt (string-to-number (gnugo-get :white-captures)))
2148 (komi (gnugo--root-prop :KM)))
2149 (setq blurb (list "The game is over. Final score:\n")
2150 result (gnugo-query "final_score %d" seed))
2151 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2152 (dolist (group live)
2153 (incf (if (gnugo--blackp (caar group))
2154 b-terr
2155 w-terr)
2156 (length (cdr group))))
2157 (dolist (group dead)
2158 (incf (if (gnugo--blackp (caar group))
2159 w-terr
2160 b-terr)
2161 (length (cdr group))))
2162 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2163 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2164 w-terr terr komi 'komi (+ w-terr komi))
2165 blurb))
2166 (t
2167 (dolist (group dead)
2168 (incf (if (gnugo--blackp (caar group))
2169 w-terr
2170 b-terr)
2171 (* 2 (length (cdr group)))))
2172 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2173 b-terr terr
2174 b-capt capt
2175 (+ b-terr b-capt))
2176 blurb)
2177 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2178 w-terr terr
2179 w-capt capt
2180 komi 'komi
2181 (+ w-terr w-capt komi))
2182 blurb)))
2183 (push (if (string= "0" result)
2184 "The game is a draw.\n"
2185 (format "%s wins by %s.\n"
2186 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2187 (substring result 2)))
2188 blurb)
2189 (message "Computing final score ... done")))
2190 ;; extra info
2191 (let ((beg (gnugo-get :game-start-time))
2192 (end (gnugo-get :game-end-time)))
2193 (when end
2194 (push "\n" blurb)
2195 (cl-flet
2196 ((yep (pretty moment)
2197 (push (format-time-string
2198 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2199 moment)
2200 blurb)))
2201 (yep "Game start" beg)
2202 (yep " end" end))))
2203 (setq blurb (apply 'concat (nreverse blurb)))
2204 (gnugo--set-root-prop :RE result)
2205 (when comment
2206 (let ((node (car (aref (gnugo-get :monkey) 0))))
2207 (gnugo--decorate
2208 (delq (assq :C node) node)
2209 (with-temp-buffer ; lame
2210 (insert blurb)
2211 (when (search-backward "\n\nGame start:" nil t)
2212 (delete-region (point) (point-max)))
2213 (cl-flet ((rep (old new)
2214 (goto-char (point-min))
2215 (while (search-forward old nil t)
2216 (replace-match new))))
2217 (rep "The game is over. " "")
2218 (rep "territory" "T")
2219 (rep "captures" "C")
2220 (rep "komi" "K"))
2221 `((:C . ,(buffer-string)))))))
2222 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2223 (erase-buffer)
2224 (insert blurb)))
2225
2226 (defun gnugo-quit ()
2227 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2228 If the game is not over, ask for confirmation first."
2229 (interactive)
2230 (if (or (gnugo-get :game-over)
2231 (y-or-n-p "Quit? "))
2232 (kill-buffer nil)
2233 (message "(not quitting)")))
2234
2235 (defun gnugo-leave-me-alone ()
2236 "Kill the current buffer unconditionally."
2237 (interactive)
2238 (kill-buffer nil))
2239
2240 (defun gnugo-fancy-undo (count)
2241 "Rewind the game tree in various ways.
2242 Prefix arg COUNT means to undo that many moves.
2243 Otherwise, undo repeatedly up to and including the move
2244 which placed the stone at point."
2245 (interactive "P")
2246 (gnugo-magic-undo
2247 ;; TODO: Move this into `gnugo-magic-undo' proper.
2248 (cond ((numberp count) count)
2249 ((consp count) (car count))
2250 (t (gnugo-position)))))
2251
2252 (defun gnugo-toggle-image-display-command () ; ugh
2253 "Toggle use of images to display the board, then refresh."
2254 (interactive)
2255 (gnugo-toggle-image-display)
2256 (save-excursion (gnugo-refresh)))
2257
2258 (defsubst gnugo--node-with-played-stone (pos)
2259 (car (gnugo--mem-with-played-stone pos)))
2260
2261 (defun gnugo-describe-position ()
2262 "Display the board position under cursor in the echo area.
2263 If there a stone at that position, also display its move number."
2264 (interactive)
2265 (let* ((pos (gnugo-position)) ; do first (can throw)
2266 (node (gnugo--node-with-played-stone pos)))
2267 (message
2268 "%s%s" pos
2269 (or (when node
2270 (let* ((tree (gnugo-get :sgf-gametree))
2271 (mnum (gnugo--tree-mnum tree))
2272 (move-num (gethash node mnum)))
2273 (format " (move %d)" move-num)))
2274 ""))))
2275
2276 (defun gnugo-switch-to-another ()
2277 "Switch to another GNU Go game buffer (if any)."
2278 (interactive)
2279 (loop for buf in (cdr (buffer-list))
2280 if (gnugo-board-buffer-p buf)
2281 return (progn
2282 (bury-buffer)
2283 (switch-to-buffer buf))
2284 finally do (message "(only one)")))
2285
2286 (defun gnugo-comment (node comment)
2287 "Add to NODE a COMMENT (string) property.
2288 Called interactively, NODE is the one corresponding to the
2289 stone at point, and any previous comment is inserted as the
2290 initial-input (see `read-string').
2291
2292 If COMMENT is nil or the empty string, remove the property entirely."
2293 (interactive
2294 (let* ((pos (gnugo-position))
2295 (node (or (gnugo--node-with-played-stone pos)
2296 (user-error "No stone at %s" pos))))
2297 (list node
2298 (read-string (format "Comment for %s: "
2299 (gnugo-describe-position))
2300 (cdr (assq :C node))))))
2301 (setq node (delq (assq :C node) node))
2302 (unless (zerop (length comment))
2303 (gnugo--decorate node `((:C . ,comment)))))
2304
2305 (defun gnugo-toggle-abdication ()
2306 "Toggle abdication, i.e., letting GNU Go play for you.
2307 When enabled, the mode line includes \"Abd\".
2308 Enabling signals error if the game is over.
2309 Disabling signals error if the color \"to play\" is the user color.
2310 This is to ensure that the user is the next to play after disabling."
2311 (interactive)
2312 (let ((last-mover (gnugo-get :last-mover))
2313 (abd (gnugo-get :abd))
2314 (warning ""))
2315 (if abd
2316 ;; disable
2317 (let ((gcolor (gnugo-get :gnugo-color)))
2318 (when (string= last-mover gcolor)
2319 (gnugo--ERR-wait gcolor "Sorry, too soon"))
2320 (when (timerp abd)
2321 (cancel-timer abd))
2322 (gnugo--forget :abd)
2323 (unless (gnugo-get :waiting)
2324 (gnugo-get-move gcolor)))
2325 ;; enable
2326 (gnugo--gate-game-over t)
2327 (gnugo-put :abd t)
2328 (gnugo-get-move (gnugo-other last-mover)))
2329 (message "Abdication %sabled%s"
2330 (if (gnugo-get :abd)
2331 "en"
2332 "dis")
2333 warning)))
2334
2335 ;;;---------------------------------------------------------------------------
2336 ;;; Command properties and gnugo-command
2337
2338 ;; GTP commands entered by the user are never issued directly to GNU Go;
2339 ;; instead, their behavior and output are controlled by the property
2340 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2341 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2342 ;;
2343 ;; :full -- completely interpret the command string; the value is a
2344 ;; func that takes the list of words derived from splitting the
2345 ;; command string (minus the command) and handles everything.
2346 ;;
2347 ;; :output -- either a keyword specifying the preferred output method:
2348 ;; :message -- show output in minibuffer
2349 ;; :discard -- sometimes you just don't care;
2350 ;; or a function that takes one arg, the output string, and
2351 ;; handles it completely. default is to switch to buffer
2352 ;; "*gnugo command output*" if the output has a newline,
2353 ;; otherwise use `message'.
2354 ;;
2355 ;; :post-thunk -- run after output processing (at the very end).
2356
2357 (defun gnugo-command (command)
2358 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2359 Output and Emacs behavior depend on which command is given (some
2360 commands are handled completely by Emacs w/o using the subprocess;
2361 some commands have their output displayed in specially prepared
2362 buffers or in the echo area; some commands are instrumented to do
2363 gnugo.el-specific housekeeping).
2364
2365 For example, for the command \"help\", Emacs visits the
2366 GTP command reference info page.
2367
2368 NOTE: At this time, GTP command handling specification is still
2369 incomplete. Thus, some commands WILL confuse gnugo.el."
2370 (interactive "sCommand: ")
2371 (if (string= "" command)
2372 (message "(no command given)")
2373 (let* ((split (split-string command))
2374 (cmd (intern (car split)))
2375 (spec (get cmd :gnugo-gtp-command-spec))
2376 (full (plist-get spec :full)))
2377 (if full
2378 (funcall full (cdr split))
2379 (message "Doing %s ..." command)
2380 (let* ((ans (gnugo--q command))
2381 (where (plist-get spec :output)))
2382 (if (string-match "unknown.command" ans)
2383 (message "%s" ans)
2384 (cond ((functionp where) (funcall where ans))
2385 ((eq :discard where) (message ""))
2386 ((or (eq :message where)
2387 (not (string-match "\n" ans)))
2388 (message "%s" ans))
2389 (t (switch-to-buffer "*gnugo command output*")
2390 (erase-buffer)
2391 (insert ans)
2392 (message "Doing %s ... done." command)))
2393 (let ((thunk (plist-get spec :post-thunk)))
2394 (when thunk (funcall thunk)))))))))
2395
2396 ;;;---------------------------------------------------------------------------
2397 ;;; Major mode for interacting with a GNUGO subprocess
2398
2399 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2400 "Major mode for playing GNU Go.
2401 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2402 In this mode, keys do not self insert.
2403
2404 \\{gnugo-board-mode-map}"
2405 (buffer-disable-undo) ; todo: undo undo undoing
2406 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2407 truncate-lines t)
2408 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2409 (set (make-local-variable 'gnugo-state)
2410 (gnugo--mkht :size (1- 42)))
2411 (gnugo-put :highlight-last-move-spec
2412 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2413 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2414 (let ((ov (make-overlay 1 1)))
2415 (overlay-put ov 'display ")")
2416 ov)))
2417 (gnugo-put :mul '(1 . 1))
2418 (add-to-invisibility-spec :nogrid))
2419
2420 ;;;---------------------------------------------------------------------------
2421 ;;; Entry point
2422
2423 ;;;###autoload
2424 (defun gnugo (&optional new-game)
2425 "Run gnugo in a buffer, or resume a game in progress.
2426 If there is already a game in progress you may resume it instead
2427 of starting a new one. Prefix arg means skip the game-in-progress
2428 check and start a new game straight away.
2429
2430 Before starting, Emacs queries you for additional command-line
2431 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2432
2433 Note that specifying \"--infile FILENAME\" (or, \"-l FILENAME\")
2434 silently clobbers certain other options, such as \"--color\".
2435 For details, see info node `(gnugo) Invoking GNU Go'.
2436
2437 \\<gnugo-board-mode-map>
2438 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2439 See `gnugo-board-mode' for a full list of commands."
2440 (interactive "P")
2441 (let* ((all (let (acc)
2442 (dolist (buf (buffer-list))
2443 (when (gnugo-board-buffer-p buf)
2444 (push (cons (buffer-name buf) buf) acc)))
2445 acc))
2446 (n (length all)))
2447 (if (and (not new-game)
2448 (cl-plusp n)
2449 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2450 (if (= 1 n) "" "s"))))
2451 ;; resume
2452 (switch-to-buffer
2453 (cdr (if (= 1 n)
2454 (car all)
2455 (let ((sel (completing-read "Which one? " all nil t)))
2456 (if (string= "" sel)
2457 (car all)
2458 (assoc sel all))))))
2459 ;; sanity check
2460 (unless (executable-find gnugo-program)
2461 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2462 ;; set up a new board
2463 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2464 (gnugo-board-mode)
2465 (let* ((filename nil)
2466 (user-color "black")
2467 (args (loop
2468 with ls = (split-string
2469 ;; todo: grok ‘gnugo --help’; completion
2470 (read-string
2471 "GNU Go options: "
2472 (car gnugo-option-history)
2473 'gnugo-option-history))
2474 with ok
2475 while ls do
2476 (let ((arg (pop ls)))
2477 (cl-flet
2478 ((ex (opt fn)
2479 (if filename
2480 (warn "%s %s ignored" opt fn)
2481 (setq filename fn))))
2482 (cond
2483 ((string= "--color" arg)
2484 (push arg ok)
2485 (push
2486 ;; Unfortunately, GTP does not provide
2487 ;; a way to query the user color, so
2488 ;; we must resort to this weirdness.
2489 (setq user-color
2490 (pop ls))
2491 ok))
2492 ((string= "--infile" arg)
2493 (ex "--infile" (pop ls)))
2494 ((string-match "^-l" arg)
2495 (ex "-l" (if (< 2 (length arg))
2496 (substring arg 2)
2497 (pop ls))))
2498 (t (push arg ok)))))
2499 finally return (nreverse ok)))
2500 (proc (apply 'start-process "gnugo"
2501 (current-buffer)
2502 gnugo-program
2503 "--mode" "gtp" "--quiet"
2504 args))
2505 root board-size handicap komi)
2506 (gnugo-put :user-color user-color)
2507 (gnugo-put :proc proc)
2508 (set-process-sentinel proc 'gnugo-sentinel)
2509 ;; Emacs is too protective sometimes, blech.
2510 (set-process-query-on-exit-flag proc nil)
2511 (gnugo-put :diamond (substring (process-name proc) 5))
2512 (gnugo-put :gnugo-color (gnugo-other user-color))
2513 (if filename
2514 (gnugo-read-sgf-file (expand-file-name filename))
2515 (cl-flet
2516 ((r! (&rest plist)
2517 (gnugo--decorate
2518 root (loop ; hmm, available elsewhere?
2519 while plist
2520 collect (let* ((k (pop plist))
2521 (v (pop plist)))
2522 (cons k v))))))
2523 (gnugo--SZ!
2524 (setq root (gnugo--root-node
2525 (gnugo--plant-and-climb
2526 (gnugo/sgf-create "(;FF[4]GM[1])" t)))
2527 komi (gnugo--nquery "get_komi")
2528 handicap (gnugo--nquery "get_handicap")
2529 board-size (gnugo--nquery "query_boardsize")))
2530 (r! :SZ board-size
2531 :DT (format-time-string "%Y-%m-%d")
2532 :RU (if (member "--chinese-rules" args)
2533 "Chinese"
2534 "Japanese")
2535 :AP (cons "gnugo.el" gnugo-version)
2536 :KM komi)
2537 (let ((ub (gnugo--blackp user-color)))
2538 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2539 (if ub :PB :PW) (user-full-name)))
2540 (unless (zerop handicap)
2541 (r! :HA handicap
2542 :AB (mapcar (gnugo--as-cc-func)
2543 (gnugo-lsquery "fixed_handicap %d"
2544 handicap)))))))
2545 (gnugo-put :waiting-start (current-time))
2546 (gnugo-refresh t)
2547 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2548 (gnugo-get :center-position)))
2549 ;; first move
2550 (gnugo-put :game-start-time (current-time))
2551 (let ((g (gnugo-get :gnugo-color))
2552 (n (or (gnugo--root-prop :HA) 0))
2553 (u (gnugo-get :user-color)))
2554 (unless (gnugo-get :last-mover)
2555 (gnugo-put :last-mover
2556 (if (or (and (gnugo--blackp u) (< 1 n))
2557 (and (gnugo--blackp g) (< n 2)))
2558 u
2559 g)))
2560 (run-hooks 'gnugo-start-game-hook)
2561 (when (and (not (gnugo-get :game-over))
2562 (string= g (gnugo-current-player)))
2563 (gnugo-refresh t)
2564 (gnugo-get-move g))))))
2565
2566 ;;;---------------------------------------------------------------------------
2567 ;;; Load-time actions
2568
2569 (unless gnugo-frolic-mode-map
2570 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2571 (suppress-keymap gnugo-frolic-mode-map)
2572 (mapc (lambda (pair)
2573 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2574 '(("q" . gnugo-frolic-quit)
2575 ("Q" . gnugo-frolic-quit)
2576 ("\C-q" . gnugo-frolic-quit)
2577 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2578 ("\C-b" . gnugo-frolic-backward-branch)
2579 ("\C-f" . gnugo-frolic-forward-branch)
2580 ("\C-p" . gnugo-frolic-previous-move)
2581 ("\C-n" . gnugo-frolic-next-move)
2582 ("j" . gnugo-frolic-exchange-left)
2583 ("J" . gnugo-frolic-rotate-left)
2584 ("k" . gnugo-frolic-exchange-right)
2585 ("K" . gnugo-frolic-rotate-right)
2586 ("\C-m" . gnugo-frolic-set-as-main-line)
2587 ("\C-\M-p" . gnugo-frolic-prune-branch)
2588 ("o" . gnugo-frolic-return-to-origin))))
2589
2590 (unless gnugo-board-mode-map
2591 (setq gnugo-board-mode-map (make-sparse-keymap))
2592 (suppress-keymap gnugo-board-mode-map)
2593 (mapc (lambda (pair)
2594 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2595 '(("?" . describe-mode)
2596 ("S" . gnugo-request-suggestion)
2597 ("\C-m" . gnugo-move)
2598 (" " . gnugo-move)
2599 ("P" . gnugo-pass)
2600 ("R" . gnugo-resign)
2601 ("q" . gnugo-quit)
2602 ("Q" . gnugo-leave-me-alone)
2603 ("U" . gnugo-fancy-undo)
2604 ("\M-u" . gnugo-undo-one-move)
2605 ("u" . gnugo-undo-two-moves)
2606 ("\C-?" . gnugo-undo-two-moves)
2607 ("o" . gnugo-oops)
2608 ("O" . gnugo-okay)
2609 ("\C-l" . gnugo-refresh)
2610 ("\M-_" . gnugo-boss-is-near)
2611 ("_" . gnugo-boss-is-near)
2612 ("h" . gnugo-move-history)
2613 ("L" . gnugo-frolic-in-the-leaves)
2614 ("\C-c\C-l" . gnugo-frolic-in-the-leaves)
2615 ("i" . gnugo-toggle-image-display-command)
2616 ("w" . gnugo-worm-stones)
2617 ("W" . gnugo-worm-data)
2618 ("d" . gnugo-dragon-stones)
2619 ("D" . gnugo-dragon-data)
2620 ("g" . gnugo-toggle-grid)
2621 ("!" . gnugo-estimate-score)
2622 (":" . gnugo-command)
2623 (";" . gnugo-command)
2624 ("=" . gnugo-describe-position)
2625 ("s" . gnugo-write-sgf-file)
2626 ("\C-x\C-s" . gnugo-write-sgf-file)
2627 ("\C-x\C-w" . gnugo-write-sgf-file)
2628 ("l" . gnugo-read-sgf-file)
2629 ("F" . gnugo-display-final-score)
2630 ("A" . gnugo-switch-to-another)
2631 ("C" . gnugo-comment)
2632 ("\C-c\C-a" . gnugo-toggle-abdication)
2633 ;; mouse
2634 ([(down-mouse-1)] . gnugo-mouse-move)
2635 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2636 ([(down-mouse-3)] . gnugo-mouse-pass)
2637 ;; delving into the curiosities
2638 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2639
2640 (unless (get 'help :gnugo-gtp-command-spec)
2641 (cl-flet*
2642 ((sget (x) (get x :gnugo-gtp-command-spec))
2643 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2644 (plist-put (sget cmd) prop val)))
2645 (validpos (s &optional go)
2646 (let ((pos (upcase s)))
2647 (loop with size = (gnugo-get :SZ)
2648 for c across (funcall (gnugo--as-cc-func)
2649 pos)
2650 do (let ((norm (- c ?a)))
2651 (unless (and (< -1 norm)
2652 (> size norm))
2653 (user-error "Invalid position: %s"
2654 pos))))
2655 (when go
2656 (gnugo-goto-pos pos))
2657 pos))
2658 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2659 (let ((ls props))
2660 (while ls
2661 (jam cmd (car ls) (cadr ls))
2662 (setq ls (cddr ls)))))))
2663 (cl-macrolet ((deffull (who &body body)
2664 (declare (indent 1))
2665 `(defgtp ',who :full (lambda (sel)
2666 ,@body))))
2667
2668 (deffull help
2669 (info "(gnugo)GTP command reference")
2670 (when sel (setq sel (intern (car sel))))
2671 (let (buffer-read-only pad cur spec output found)
2672 (cl-flet
2673 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2674 (goto-char (point-min))
2675 (save-excursion
2676 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2677 (point-max) t)
2678 (unless pad
2679 (setq pad (make-string (- (match-beginning 1)
2680 (match-beginning 0))
2681 32)))
2682 (when (plist-get
2683 (setq spec
2684 (get (setq cur (intern (match-string 1)))
2685 :gnugo-gtp-command-spec))
2686 :full)
2687 (note "handles this command completely"))
2688 (when (setq output (plist-get spec :output))
2689 (if (functionp output)
2690 (note "handles the output specially")
2691 (case output
2692 (:discard (note "discards the output"))
2693 (:message (note "displays the output in the echo area")))))
2694 (when (eq sel cur)
2695 (setq found (match-beginning 0))))))
2696 (cond (found (goto-char found))
2697 ((not sel))
2698 (t (message "(no such command: %s)" sel)))))
2699
2700 (deffull final_score
2701 ;; Explicit ignorance avoids byte-compiler warning.
2702 (ignore sel)
2703 (gnugo-display-final-score))
2704
2705 (defgtp '(boardsize
2706 clear_board
2707 fixed_handicap)
2708 :output :discard
2709 :post-thunk (lambda ()
2710 (gnugo--unclose-game)
2711 (gnugo--forget :last-mover)
2712 ;; ugh
2713 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2714 (gnugo-refresh t)))
2715
2716 (deffull loadsgf
2717 (gnugo-read-sgf-file (car sel)))
2718
2719 (deffull (undo gg-undo)
2720 (gnugo-magic-undo
2721 (let (n)
2722 (cond ((not sel) 1)
2723 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2724 (t (validpos (car sel) t)))))))))
2725
2726 (provide 'gnugo)
2727
2728 \f
2729 ;;;---------------------------------------------------------------------------
2730 ;;; The remainder of this file defines a simplified SGF-handling library.
2731 ;;; When/if it should start to attain generality, it should be split off into
2732 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2733 ;;; "gnugo/" prefix.
2734
2735 (defconst gnugo/sgf-*r4-properties*
2736 '((AB "Add Black" setup list stone)
2737 (AE "Add Empty" game list point)
2738 (AN "Annotation" game simpletext)
2739 (AP "Application" root (simpletext . simpletext))
2740 (AR "Arrow" - list (point . point))
2741 (AS "Who adds stones" - simpletext) ; (LOA)
2742 (AW "Add White" setup list stone)
2743 (B "Black" move move)
2744 (BL "Black time left" move real)
2745 (BM "Bad move" move double)
2746 (BR "Black rank" game simpletext)
2747 (BT "Black team" game simpletext)
2748 (C "Comment" - text)
2749 (CA "Charset" root simpletext)
2750 (CP "Copyright" game simpletext)
2751 (CR "Circle" - list point)
2752 (DD "Dim points" - elist point) ; (inherit)
2753 (DM "Even position" - double)
2754 (DO "Doubtful" move none)
2755 (DT "Date" game simpletext)
2756 (EV "Event" game simpletext)
2757 (FF "Fileformat" root [number (1 . 4)])
2758 (FG "Figure" - (or none (number . simpletext)))
2759 (GB "Good for Black" - double)
2760 (GC "Game comment" game text)
2761 (GM "Game" root [number (1 . 20)])
2762 (GN "Game name" game simpletext)
2763 (GW "Good for White" - double)
2764 (HA "Handicap" game number) ; (Go)
2765 (HO "Hotspot" - double)
2766 (IP "Initial pos." game simpletext) ; (LOA)
2767 (IT "Interesting" move none)
2768 (IY "Invert Y-axis" game simpletext) ; (LOA)
2769 (KM "Komi" game real) ; (Go)
2770 (KO "Ko" move none)
2771 (LB "Label" - list (point . simpletext))
2772 (LN "Line" - list (point . point))
2773 (MA "Mark" - list point)
2774 (MN "set move number" move number)
2775 (N "Nodename" - simpletext)
2776 (OB "OtStones Black" move number)
2777 (ON "Opening" game text)
2778 (OT "Overtime" game simpletext)
2779 (OW "OtStones White" move number)
2780 (PB "Player Black" game simpletext)
2781 (PC "Place" game simpletext)
2782 (PL "Player to play" setup color)
2783 (PM "Print move mode" - number) ; (inherit)
2784 (PW "Player White" game simpletext)
2785 (RE "Result" game simpletext)
2786 (RO "Round" game simpletext)
2787 (RU "Rules" game simpletext)
2788 (SE "Markup" - point) ; (LOA)
2789 (SL "Selected" - list point)
2790 (SO "Source" game simpletext)
2791 (SQ "Square" - list point)
2792 (ST "Style" root [number (0 . 3)])
2793 (SU "Setup type" game simpletext) ; (LOA)
2794 (SZ "Size" root (or number (number . number)))
2795 (TB "Territory Black" - elist point) ; (Go)
2796 (TE "Tesuji" move double)
2797 (TM "Timelimit" game real)
2798 (TR "Triangle" - list point)
2799 (TW "Territory White" - elist point) ; (Go)
2800 (UC "Unclear pos" - double)
2801 (US "User" game simpletext)
2802 (V "Value" - real)
2803 (VW "View" - elist point) ; (inherit)
2804 (W "White" move move)
2805 (WL "White time left" move real)
2806 (WR "White rank" game simpletext)
2807 (WT "White team" game simpletext)
2808 (LT "Lose on time" setup simpletext))
2809 ;; r4-specific notes
2810 ;; - changed: DT FG LB RE RU SZ
2811 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2812 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2813
2814 (defun gnugo/sgf-create (file-or-data &optional data-p)
2815 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2816 FILE-OR-DATA is a file name or SGF[4] data.
2817 Optional arg DATA-P non-nil means FILE-OR-DATA is
2818 a string containing SGF[4] data.
2819 A collection is a list of gametrees, each a vector of four elements:
2820
2821 ENDS -- a vector of node lists, with shared tails
2822 (last element of all the lists is the root node)
2823
2824 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2825 have a move number of the previous \"move\" node (or zero)
2826
2827 ROOT -- the root node"
2828 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2829 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2830 (put 'gnugo/sgf-*r4-properties* :keywords
2831 (mapcar (lambda (full)
2832 (cons (car full)
2833 (intern (format ":%s" (car full)))))
2834 gnugo/sgf-*r4-properties*))))
2835 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2836 (put 'gnugo/sgf-*r4-properties* :specs
2837 (mapcar (lambda (full)
2838 (cons (car full) (cdddr full)))
2839 gnugo/sgf-*r4-properties*))))
2840 SZ)
2841 (cl-labels
2842 ((sw () (skip-chars-forward " \t\n"))
2843 (x (end preserve-whitespace)
2844 (let ((beg (point))
2845 (endp (case end
2846 (:end (lambda (char) (= ?\] char)))
2847 (:mid (lambda (char) (= ?\: char)))
2848 (t (lambda (char) (or (= ?\: char)
2849 (= ?\] char))))))
2850 c)
2851 (while (not (funcall endp (setq c (following-char))))
2852 (cond ((= ?\\ c)
2853 (delete-char 1)
2854 (if (eolp)
2855 (kill-line 1)
2856 (forward-char 1)))
2857 ((unless preserve-whitespace
2858 (looking-at "\\s-+"))
2859 (delete-region (point) (match-end 0))
2860 (insert " "))
2861 (t (forward-char 1))))
2862 (buffer-substring-no-properties beg (point))))
2863 (one (type end) (let ((s (progn
2864 (forward-char 1)
2865 (x end (eq 'text type)))))
2866 (case type
2867 ((stone point move)
2868 ;; blech, begone bu"tt"-ugly blatherings
2869 ;; (but bide brobdingnagian boards)...
2870 (if (and (string= "tt" s)
2871 SZ
2872 (>= 19 SZ))
2873 ""
2874 s))
2875 ((simpletext color) s)
2876 ((number real double) (string-to-number s))
2877 ((text) s)
2878 ((none) "")
2879 (t (error "Unhandled type: %S" type)))))
2880 (val (spec) (cond ((symbolp spec)
2881 (one spec :end))
2882 ((vectorp spec)
2883 ;; todo: check range here.
2884 (one (aref spec 0) :end))
2885 ((eq 'or (car spec))
2886 (let ((v (one (cadr spec) t)))
2887 (if (= ?\] (following-char))
2888 v
2889 (forward-char 1)
2890 ;; todo: this assumes `spec' has the form
2891 ;; (or foo (foo . bar))
2892 ;; i.e., foo is not rescanned. e.g., `SZ'.
2893 ;; probably this assumption is consistent
2894 ;; w/ the SGF authors' desire to make the
2895 ;; parsing easy, but you never know...
2896 (cons v (one (cdaddr spec) :end)))))
2897 (t (cons (one (car spec) :mid)
2898 (one (cdr spec) :end)))))
2899 (short (who) (when (eobp)
2900 (error "Unexpected EOF while reading %s" who)))
2901 (atvalp () (= ?\[ (following-char)))
2902 (PROP () (let (name spec ltype)
2903 (sw) (short 'property)
2904 (when (looking-at "[A-Z]")
2905 (setq name (read (current-buffer))
2906 spec (cdr (assq name specs)))
2907 (sw)
2908 (cons
2909 (cdr (assq name keywords))
2910 (prog1 (if (= 1 (length spec))
2911 (val (car spec))
2912 (unless (memq (setq ltype (car spec))
2913 '(elist list))
2914 (error "Bad spec: %S" spec))
2915 (if (and (eq 'elist ltype) (sw)
2916 (not (atvalp)))
2917 nil
2918 (let ((type (cadr spec))
2919 mo ls)
2920 (while (and (sw) (atvalp)
2921 (setq mo (val type)))
2922 (push mo ls)
2923 (forward-char 1))
2924 (forward-char -1)
2925 (nreverse ls))))
2926 (forward-char 1))))))
2927 (morep () (and (sw) (not (eobp))))
2928 (seek (c) (and (morep) (= c (following-char))))
2929 (seek-into (c) (when (seek c)
2930 (forward-char 1)
2931 t))
2932 (NODE () (when (seek-into ?\;)
2933 (loop with prop
2934 while (setq prop (PROP))
2935 collect (progn
2936 (when (eq :SZ (car prop))
2937 (setq SZ (cdr prop)))
2938 prop))))
2939 (TREE (parent mnum)
2940 (let ((ls parent)
2941 prev node)
2942 (seek-into ?\()
2943 (while (seek ?\;)
2944 (setq prev (car ls)
2945 node (NODE))
2946 (puthash node (+ (if (gnugo--move-prop node)
2947 1
2948 0)
2949 (gethash prev mnum 0))
2950 mnum)
2951 (push node
2952 ls))
2953 (prog1
2954 (if (not (seek ?\())
2955 ;; singular
2956 (list ls)
2957 ;; multiple
2958 (loop while (seek ?\()
2959 append (TREE ls mnum)))
2960 (seek-into ?\))))))
2961 (with-temp-buffer
2962 (if (not data-p)
2963 (insert-file-contents file-or-data)
2964 (insert file-or-data)
2965 (goto-char (point-min)))
2966 (loop while (morep)
2967 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2968 (ends (TREE nil mnum))
2969 (root (car (last (car ends)))))
2970 (vector (apply 'vector ends)
2971 mnum
2972 root)))))))
2973
2974 (defun gnugo/sgf-write-file (collection filename)
2975 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2976 (me (cons "gnugo.el" gnugo-version))
2977 (specs (mapcar (lambda (full)
2978 (cons (intern (format ":%s" (car full)))
2979 (cdddr full)))
2980 gnugo/sgf-*r4-properties*))
2981 p name v spec)
2982 (cl-labels
2983 ((esc (composed fmt arg)
2984 (mapconcat (lambda (c)
2985 (case c
2986 ;; ‘?\[’ is not strictly required
2987 ;; but neither is it forbidden.
2988 ((?\[ ?\] ?\\) (format "\\%c" c))
2989 (?: (concat (if composed "\\" "") ":"))
2990 (t (string c))))
2991 (string-to-list (format fmt arg))
2992 ""))
2993 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2994 (>>two (v) (insert "["
2995 (esc t "%s" (car v))
2996 ":"
2997 (esc t "%s" (cdr v))
2998 "]"))
2999 (>>nl () (cond ((memq name aft-newline-appreciated)
3000 (insert "\n"))
3001 ((< 60 (current-column))
3002 (save-excursion
3003 (goto-char p)
3004 (insert "\n")))))
3005 (>>prop (prop)
3006 (setq p (point)
3007 name (car prop)
3008 v (cdr prop))
3009 (insert (substring (symbol-name name) 1))
3010 (cond ((not v))
3011 ((and (consp v)
3012 (setq spec (cdr (assq name specs)))
3013 (memq (car spec)
3014 '(list elist)))
3015 (>>nl)
3016 (let ((>> (if (consp (cadr spec))
3017 #'>>two
3018 #'>>one)))
3019 (dolist (little-v v)
3020 (setq p (point))
3021 (funcall >> little-v)
3022 (>>nl))))
3023 ((consp v)
3024 (>>two v) (>>nl))
3025 (t
3026 (>>one v) (>>nl))))
3027 (>>node (node)
3028 (loop initially (insert ";")
3029 for prop in node
3030 do (>>prop prop)))
3031 (>>tree (tree)
3032 (unless (zerop (current-column))
3033 (newline))
3034 (insert "(")
3035 (dolist (x tree)
3036 (funcall (if (gnugo--nodep x)
3037 #'>>node
3038 #'>>tree)
3039 x))
3040 (insert ")")))
3041 (with-temp-buffer
3042 (dolist (tree collection)
3043 ;; take responsibility for our actions
3044 (gnugo--set-root-prop :AP me tree)
3045 ;; write it out
3046 (let ((ht (gnugo--mkht))
3047 (leaves (append (gnugo--tree-ends tree) nil)))
3048 (cl-flet
3049 ((hang (stack)
3050 (loop
3051 with rh ; rectified history
3052 with bp ; branch point
3053 for node in stack
3054 until (setq bp (gethash node ht))
3055 do (puthash node
3056 (push node rh) ; good for now: ½τ
3057 ht)
3058 finally return
3059 (if (not bp)
3060 ;; first run: main line
3061 rh
3062 ;; subsequent runs: grafts (value discarded)
3063 (setcdr bp (nconc
3064 ;; Maintain order of ‘leaves’.
3065 (let ((was (cdr bp)))
3066 (if (gnugo--nodep (car was))
3067 (list was)
3068 was))
3069 (list rh)))))))
3070 (setq tree (hang (pop leaves)))
3071 (mapc #'hang leaves)
3072 (>>tree tree))))
3073 (newline)
3074 (write-file filename)))))
3075
3076 ;;; gnugo.el ends here