1 ;;; gnugo.el --- play GNU Go in a buffer
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
7 ;; Package-Requires: ((ascii-art-to-unicode "1.5"))
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.
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.
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/>.
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.
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.
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).
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.
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. :-)
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
61 ;; Meta-Playing (aka Customizing)
62 ;; ------------------------------
64 ;; Customization is presently limited to
65 ;; vars: `gnugo-program'
66 ;; `gnugo-animation-string'
68 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
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'
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
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'
86 ;;;---------------------------------------------------------------------------
89 (defconst gnugo-version "2.3.1"
90 "Version of gnugo.el currently loaded.
91 This follows a MAJOR.MINOR.PATCH scheme.")
93 ;;;---------------------------------------------------------------------------
94 ;;; Variables for the uninquisitive programmer
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:
101 For more information on GTP and GNU Go, please visit:
102 <http://www.gnu.org/software/gnugo>")
104 (defvar gnugo-board-mode-map nil
105 "Keymap for GNUGO Board mode.")
107 (defvar gnugo-frolic-mode-map nil
108 "Keymap for GNUGO Frolic mode.")
110 (defvar gnugo-board-mode-hook nil
111 "Hook run when entering GNUGO Board mode.")
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'.")
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.")
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...
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.")
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)
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.")
156 (defvar gnugo-X-face 'font-lock-string-face
157 "Name of face to use for X (black) stones.")
159 (defvar gnugo-O-face 'font-lock-builtin-face
160 "Name of face to use for O (white) stones.")
162 (defvar gnugo-grid-face 'default
163 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
165 ;;;---------------------------------------------------------------------------
166 ;;; Variables for the inquisitive programmer
168 (defconst gnugo-font-lock-keywords
169 '(("X" . gnugo-X-face)
170 ("O" . gnugo-O-face))
171 "Font lock keywords for `gnugo-board-mode'.")
173 (defvar gnugo-option-history nil)
175 (defvar gnugo-state nil) ; hint: C-c C-p
178 (defvar gnugo-xpms nil))
180 (defvar gnugo-frolic-parent-buffer nil)
181 (defvar gnugo-frolic-origin nil)
183 ;;;---------------------------------------------------------------------------
184 ;;; Support functions
186 (defsubst gnugo--mkht (&rest etc)
187 (apply 'make-hash-table :test 'eq etc))
189 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
190 (compare-strings s1 beg1 nil s2 beg2 nil))
192 (defun gnugo-put (key value)
193 "Associate move/game/board-specific property KEY with VALUE.
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\".
204 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
206 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
208 :game-over -- nil until game over at which time its value is set to
209 the alist `((live GROUP ...) (dead GROUP ...))'
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
215 :sgf-gametree -- one of the gametrees in :sgf-collection
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\"
221 :gnugo-color -- either \"black\" or \"white\"
225 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
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!)
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)
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'
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
247 :last-user-bpos -- board position; keep the hapless human happy
249 As things stabilize probably more info will be added to this docstring."
251 (puthash key value gnugo-state))
253 (defun gnugo-get (key)
254 "Return the move/game/board-specific value for KEY.
256 (gethash key gnugo-state))
258 (defun gnugo--forget (&rest keys)
260 (remhash key gnugo-state)))
262 (defsubst gnugo--tree-mnum (tree)
265 (defsubst gnugo--tree-ends (tree)
268 (defsubst gnugo--set-tree-ends (tree ls)
269 (aset tree 0 (apply 'vector ls))
270 (gnugo--tree-ends tree))
272 (defun gnugo--root-node (&optional tree)
273 (aref (or tree (gnugo-get :sgf-gametree))
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."
280 (let ((buf (current-buffer))
281 (d (gnugo-get :diamond))
283 (loop for key being the hash-keys of gnugo-state
284 using (hash-values val)
288 (format "hash: %X (%d images)"
294 (list (hash-table-count
295 (gnugo--tree-mnum val))
296 (gnugo--root-node val)
297 (gnugo--tree-ends val)))
299 (let ((mem (aref val 0)))
304 (switch-to-buffer (get-buffer-create
305 (format "%s*GNUGO Board Properties*"
306 (gnugo-get :diamond))))
309 (setq truncate-lines t)
313 (goto-char (point-min))
314 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
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))))
325 (defun gnugo-board-buffer-p (&optional buffer)
326 "Return non-nil if BUFFER is a GNUGO Board buffer."
327 (eq 'gnugo-board-mode
330 (or buffer (current-buffer)))))
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)))))
337 (defsubst gnugo--blackp (string)
338 (string= "black" string))
340 (defun gnugo-other (color)
341 (if (gnugo--blackp color) "white" "black"))
343 (defun gnugo-current-player ()
344 "Return the current player, either \"black\" or \"white\"."
345 (gnugo-other (gnugo-get :last-mover)))
347 (defsubst gnugo--gate-game-over (enable)
348 (when (and enable (gnugo-get :game-over))
349 (user-error "Sorry, game over")))
351 (defun gnugo--ERR-wait (color why)
352 (user-error "%s -- please wait for \"(%s to play)\""
355 (defun gnugo-gate (&optional in-progress-p)
356 (unless (gnugo-board-buffer-p)
357 (user-error "Wrong buffer -- try M-x gnugo"))
358 (unless (gnugo-get :proc)
359 (user-error "No \"gnugo\" process!"))
360 (let ((slow (gnugo-get :waiting)))
362 (gnugo--ERR-wait (gnugo-get :user-color)
365 "Not your turn yet"))))
366 (gnugo--gate-game-over in-progress-p))
368 (defun gnugo-sentinel (proc string)
369 (let ((status (process-status proc)))
370 (when (memq status '(exit signal))
371 (let ((buf (process-buffer proc)))
372 (when (buffer-live-p buf)
373 (with-current-buffer buf
374 (setq mode-line-process
376 (propertize (car (split-string string))
377 'face 'font-lock-warning-face)
379 (when (eq proc (gnugo-get :proc))
380 (gnugo--forget :proc))))))))
382 (defun gnugo--begin-exchange (proc filter line)
383 (declare (indent 2)) ; good time, for a rime
384 ; nice style, for a wile...
385 (set-process-filter proc filter)
386 (process-send-string proc line)
387 (process-send-string proc "\n"))
389 (defun gnugo--q (fmt &rest args)
390 "Send formatted command \"FMT ARGS...\"; wait for / return response.
391 The response is a string whose first two characters indicate the
392 status of the command. See also `gnugo-query'."
393 (let ((slow (gnugo-get :waiting))
394 (proc (gnugo-get :proc)))
396 (user-error "Sorry, still waiting for %s to %s"
397 (car slow) (if (cdr slow)
398 "receive a suggestion"
400 (process-put proc :incomplete t)
401 (process-put proc :srs "") ; synchronous return stash
402 (gnugo--begin-exchange
403 proc (lambda (proc string)
404 (let ((full (concat (process-get proc :srs)
406 (process-put proc :srs full)
407 (unless (numberp (gnugo--compare-strings
408 full (max 0 (- (length full)
411 (process-put proc :incomplete nil))))
414 (apply #'format fmt args)))
415 (while (process-get proc :incomplete)
416 (accept-process-output proc 30))
417 (prog1 (substring (process-get proc :srs) 0 -2)
418 (process-put proc :srs ""))))
420 (defun gnugo-query (message-format &rest args)
421 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
422 Return a string that omits the first two characters (corresponding
423 to the status indicator in the Go Text Protocol). Use this function
424 when you are sure the command cannot fail."
425 (substring (apply 'gnugo--q message-format args)
428 (defun gnugo-lsquery (message-format &rest args)
429 (split-string (apply 'gnugo-query message-format args)))
431 (defsubst gnugo--count-query (fmt &rest args)
432 (length (apply 'gnugo-lsquery fmt args)))
434 (defsubst gnugo--root-prop (prop &optional tree)
435 (cdr (assq prop (gnugo--root-node tree))))
437 (defun gnugo--set-root-prop (prop value &optional tree)
438 (let* ((root (gnugo--root-node tree))
439 (cur (assq prop root)))
442 (push (cons prop value)
443 (cdr (last root))))))
445 (defun gnugo-goto-pos (pos)
446 "Move point to board position POS, a letter-number string."
447 (goto-char (point-min))
448 (forward-line (- (1+ (gnugo-get :SZ))
449 (string-to-number (substring pos 1))))
451 (forward-char (+ (if (= 32 (following-char)) 1 2)
452 (* 2 (- (let ((letter (aref pos 0)))
458 (defun gnugo-f (frag)
459 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
461 (defun gnugo-yang (c)
462 (cdr (assq c '((?+ . hoshi)
464 (?X . (bmoku . bpmoku))
465 (?O . (wmoku . wpmoku))))))
467 (defun gnugo-yy (yin yang &optional momentaryp)
468 (gnugo-f (format "%d-%s"
469 yin (cond ((and (consp yang) momentaryp) (cdr yang))
470 ((consp yang) (car yang))
473 (defun gnugo-toggle-image-display ()
474 (unless (and (fboundp 'display-images-p) (display-images-p))
475 (user-error "Display does not support images, sorry"))
476 (require 'gnugo-xpms)
477 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
478 (user-error "Could not load `gnugo-xpms', sorry"))
479 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
480 (unless (eq fresh (gnugo-get :xpms))
481 (gnugo-put :xpms fresh)
482 (gnugo--forget :all-yy)))
483 (let* ((new (not (gnugo-get :display-using-images)))
484 (act (if new 'display 'do-not-display)))
486 (setcar (symbol-plist yy) act))
487 (or (gnugo-get :all-yy)
489 (prog1 (mapcar (lambda (ent)
491 (yy (gnugo-yy (cdr k) (car k))))
492 (setplist yy `(not-yet ,(cdr ent)))
496 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
498 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
499 (gnugo-put :highlight-last-move-spec
502 (get (gnugo-yy (get-text-property p 'gnugo-yin)
503 (get-text-property p 'gnugo-yang)
507 (gnugo-get :default-highlight-last-move-spec)))
508 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
509 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
510 (mapc 'delete-overlay (cdar group))
511 (setcdr (car group) nil))
512 (gnugo-put :mul (if new
515 (gnugo-put :display-using-images new)))
517 (defun gnugo-toggle-grid ()
518 "Turn the grid around the board on or off."
520 (funcall (if (memq :nogrid buffer-invisibility-spec)
521 'remove-from-invisibility-spec
522 'add-to-invisibility-spec)
524 (save-excursion (gnugo-refresh)))
526 (defun gnugo-propertize-board-buffer ()
528 (insert (substring (gnugo--q "showboard") 3))
529 (let* ((grid-props (list 'invisible :nogrid
530 'font-lock-face gnugo-grid-face))
531 (%gpad (gnugo-f 'gpad))
532 (%gspc (gnugo-f 'gspc))
533 (%lpad (gnugo-f 'lpad))
534 (%rpad (gnugo-f 'rpad))
535 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
536 (size (gnugo-get :SZ))
537 (size-string (number-to-string size)))
538 (goto-char (point-min))
539 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
540 (skip-chars-forward " ")
541 (put-text-property (1- (point)) (point) 'category %gpad)
542 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
544 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
545 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
546 (let* ((row (match-string-no-properties 1))
548 (other-edge (+ edge (* 2 size) -1))
549 (right-empty (+ other-edge (length row) 1))
550 (top-p (string= size-string row))
551 (bot-p (string= "1" row)))
552 (let* ((nL (- edge 1 (length size-string)))
554 (ov (make-overlay nL nR (current-buffer) t)))
555 (add-text-properties nL nR grid-props)
556 ;; We redundantly set `invisible' in the overlay to workaround
557 ;; a display bug whereby text *following* the overlaid text is
558 ;; displayed with the face of the overlaid text, but only when
559 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
560 ;; This has something to do w/ the bletcherous `before-string'.
561 (overlay-put ov 'invisible :nogrid)
562 (overlay-put ov 'category %lpad))
563 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
565 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
566 (truncate (- p edge) 2))
568 (yin (let ((A-p (= edge p))
569 (Z-p (= (1- other-edge) p)))
570 (cond ((and top-p A-p) 1)
579 (yang (gnugo-yang (char-after p))))
580 (add-text-properties p (1+ p)
590 (gnugo-position gnugo-yin))))
591 (unless (= (1- other-edge) p)
592 (add-text-properties (1+ p) (+ 2 p) ispc-props)
593 (put-text-property p (+ 2 p) 'intangible ival)))
594 (add-text-properties (1+ other-edge) right-empty grid-props)
595 (goto-char right-empty)
596 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
597 (let ((prop (if (string= "WH" (match-string 1))
600 (beg (match-beginning 2))
602 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
603 (gnugo-put prop (match-string-no-properties 2))))
605 (put-text-property right-empty (point) 'category %rpad)
607 (add-text-properties (1- (point)) (point-max) grid-props)
608 (skip-chars-forward " ")
609 (put-text-property (1- (point)) (point) 'category %gpad)
610 (put-text-property (point) (progn (end-of-line) (point))
613 (defun gnugo-merge-showboard-results ()
614 (let ((aft (substring (gnugo--q "showboard") 3))
615 (adj 1) ; string to buffer position adjustment
617 (sync "[0-9]* stones$")
618 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
619 ;; restrictive a condition that fails in the case of:
622 ;; ... WHITE has captured 1 stones
625 ;; ... WHITE has captured 14 stones
628 ;; where the after count has more digits than the before count,
629 ;; but shares the same leading digits. In this case, the result
630 ;; of `compare-strings' points to the SPC following the before
631 ;; count (indicated by caret in this example).
633 (bef (buffer-substring-no-properties (point-min) (point-max)))
634 (bef-start 0) (bef-idx 0)
635 (aft-start 0) (aft-idx 0)
636 aft-sync-backtrack mis inc cut new very-strange
638 (inhibit-read-only t))
639 (while (numberp (setq mis (gnugo--compare-strings
642 (setq aft-sync-backtrack nil
643 inc (if (cl-minusp mis)
646 bef-idx (+ bef-start inc)
647 aft-idx (+ aft-start inc)
648 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
651 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
652 (let ((peek (1- aft-idx)))
653 (while (not (= 32 (aref aft peek)))
654 (setq peek (1- peek)))
655 (setq aft-sync-backtrack (1+ peek))))
659 (if aft-sync-backtrack
660 (- aft-sync-backtrack aft-idx)
663 (if aft-sync-backtrack
664 (let* ((asb aft-sync-backtrack)
665 (l-p (get-text-property cut :gnugo-cf))
668 (keep (text-properties-at cut)))
669 (setq new (substring aft asb (string-match " " aft asb)))
670 (plist-put keep :gnugo-cf (cons (length new) capprop))
671 (gnugo-put capprop new)
672 (delete-char old-len)
673 (insert (apply 'propertize new keep))
674 (incf adj (- (length new) old-len)))
675 (setq new (aref aft aft-idx))
676 (insert-and-inherit (char-to-string new))
677 (let ((yin (get-text-property cut 'gnugo-yin))
678 (yang (gnugo-yang new)))
679 (add-text-properties cut (1+ cut)
683 ,(gnugo-yy yin yang))))
685 ;; do this last to avoid complications w/ font lock
686 ;; (this also means we cannot include `intangible' in `front-sticky')
687 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
688 (put-text-property cut (1+ cut) 'intangible very-strange))))))
690 (defsubst gnugo--move-prop (node)
694 (defun gnugo--as-pos-func ()
695 (lexical-let ((size (gnugo-get :SZ)))
700 (let ((col (aref cc 0)))
702 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
703 (- size (- (aref cc 1) ?a))))))))
705 (defun gnugo-move-history (&optional rsel)
706 "Determine and return the game's move history.
707 Optional arg RSEL controls side effects and return value.
708 If nil, display the history in the echo area as \"(N moves)\"
709 followed by the space-separated list of moves. When called
710 interactively with a prefix arg (i.e., RSEL is `(4)'), display
711 similarly, but suffix with the mover (either \":B\" or \":W\").
712 RSEL may also be a symbol that selects what to return:
713 car -- the most-recent move
714 cadr -- the next-to-most-recent move
715 two -- the last two moves as a list, oldest last
716 For all other values of RSEL, do nothing and return nil."
718 (let* ((monkey (gnugo-get :monkey))
719 (mem (aref monkey 0))
720 (as-pos (gnugo--as-pos-func))
723 ((as-pos-maybe (x) (if (string= "resign" x)
726 (next (byp) (when (setq node (pop mem)
727 mprop (gnugo--move-prop node))
728 (setq move (as-pos-maybe (cdr mprop)))
730 (format "%s%s" move (car mprop))
734 (tell () (message "(%d moves) %s"
736 (mapconcat 'identity (nreverse acc) " ")))
737 (finish (byp) (while mem (next byp)) (tell)))
742 (`cadr (nn) (car (nn)))
746 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
747 "A special mode for manipulating a GNUGO gametree.
749 \\{gnugo-frolic-mode-map}"
750 (setq truncate-lines t)
751 (buffer-disable-undo))
753 (defun gnugo-frolic-quit ()
754 "Kill GNUGO Frolic buffer and switch to its parent buffer."
756 (let ((bye (current-buffer)))
757 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
758 gnugo-frolic-parent-buffer))
761 (defun gnugo-frolic-return-to-origin ()
762 "Move point to the board's current position."
764 (if (not gnugo-frolic-origin)
765 (message "No origin")
766 (goto-char gnugo-frolic-origin)
767 (recenter (- (count-lines (line-beginning-position)
770 (defun gnugo-frolic-in-the-leaves ()
771 "Display the game tree in a *GNUGO Frolic* buffer.
772 This looks something like:
775 2 W -- K10 K10 K10 K10
794 with 0, 1, ... N (in this case N is 3) in the header line
795 to indicate the branches. Branch 0 is the \"main line\".
796 Point (* in this example) indicates the current position,
797 \"!\" indicates comment properties (e.g., B8, branch 1),
798 and moves not actually on the game tree (e.g., E7, branch 3)
799 are dimmed. Type \\[describe-mode] in that buffer for details."
801 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
803 (from (or gnugo-frolic-parent-buffer
805 ;; todo: use defface once we finally succumb to ‘customize’
806 (dimmed-node-face (list :inherit 'default
807 :foreground "gray50"))
808 (tree (gnugo-get :sgf-gametree))
809 (ends (copy-sequence (gnugo--tree-ends tree)))
810 (mnum (gnugo--tree-mnum tree))
813 (width (length ends))
814 (lanes (number-sequence 0 (1- width)))
815 (monkey (gnugo-get :monkey))
816 (as-pos (gnugo--as-pos-func))
817 (at (car (aref monkey 0)))
818 (bidx (aref monkey 1))
819 (valid (map 'vector (lambda (end)
820 (gethash (car end) mnum))
822 (max-move-num (apply 'max (append valid nil)))
823 (inhibit-read-only t)
829 (propertize s 'face face))
830 (fsi (properties fmt &rest args)
831 (insert (apply 'propertize
832 (apply 'format fmt args)
839 for node in (aref ends bx)
840 do (if (setq fork (on node))
843 ;; todo: ignore non-"move" nodes
844 (eq node (car (aref ends bix))))
846 (pushnew other (gethash node soil))))
851 (puthash node bx seen))
854 (switch-to-buffer buf)
857 (setq header-line-format
858 (lexical-let ((full (concat
860 (mapconcat (lambda (n)
870 `(space :width ,w))))
872 (when (eq 'left scroll-bar-mode)
873 (let ((w (or scroll-bar-width
875 nil 'scroll-bar-width)))
876 (cw (frame-char-width)))
880 (let ((fc (fringe-columns 'left t)))
884 (substring full (window-hscroll))
886 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
887 (set (make-local-variable 'gnugo-state)
888 (buffer-local-value 'gnugo-state from))
892 from max-move-num downto 1
893 do (setq props (list 'n n))
898 (goto-char (point-min))
901 n (aref ["W" "B"] (logand 1 n))))
903 do (let* ((node (unless (< (aref valid bx) n)
904 ;; todo: ignore non-"move" nodes
905 (pop (aref ends bx))))
906 (zow (list* 'bx bx props))
910 (cdr (assq :C node))))
911 (s (cond ((not node) "")
912 ((not (setq move (gnugo--move-prop node))) "-")
913 (t (funcall as-pos (cdr move))))))
916 (push 'help-echo zow))
917 (when (and ok (setq br (gethash node soil)))
918 (push (cons bx (sort br '<))
923 (cond ((and (eq at node)
926 (setq finish (point-marker)))
927 (emph s (list :inherit 'default
928 :foreground (frame-parameter
929 nil 'cursor-color))))
931 (emph s dimmed-node-face))
934 (when (progn (fsi props "\n")
935 (setq forks (nreverse forks)))
936 (let* ((margin (make-string 11 ?\s))
937 (heads (mapcar #'car forks))
938 (tails (mapcar #'cdr forks)))
940 ((spaced (lanes func)
941 (mapconcat func lanes " "))
942 ;; live to play ~ ~ ()
943 ;; play to learn (+) (-) . o O
944 ;; learn to live --ttn .M. _____U
945 (dashed (lanes func) ;;; _____ ^^^^
946 (mapconcat func lanes "-----"))
948 (spaced lanes (lambda (bx)
952 (pad-unless (condition)
963 do (let* ((one (car ls))
966 (mapcar 'car (cdr ls))
968 (apply 'append (mapcar 'cdr bef))))
971 (end (car (last ord))))
973 ((also (b e) (cnxn (number-sequence b e)
978 (pad-unless (zerop beg))
979 (dashed (number-sequence beg end)
981 (cond ((memq bx ord) "+")
984 (pad-unless (>= end width))
985 (also (1+ end) (1- width))
988 (edge (apply 'append tails))
989 (aa2u (line-beginning-position
990 (- (1+ (length forks))))
993 (set (make-local-variable 'gnugo-frolic-origin) finish)
994 (gnugo-frolic-return-to-origin))))
996 (defun gnugo--awake (how)
997 ;; Valid HOW elements:
998 ;; require-valid-branch
1000 ;; (line . move-string)
1001 ;; Invalid elements blissfully ignored. :-D
1002 (let* ((tree (gnugo-get :sgf-gametree))
1003 (ends (gnugo--tree-ends tree))
1004 (width (length ends))
1005 (monkey (gnugo-get :monkey))
1006 (line (case (cdr (assq 'line how))
1008 (count-lines (point-min) (line-beginning-position)))
1011 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1014 (col (current-column))
1015 (a (unless (> 10 col)
1016 (let ((try (/ (- col 10)
1018 (unless (<= width try)
1021 (when (memq 'require-valid-branch how)
1023 (user-error "No branch here")))
1024 (loop with omit = (cdr (assq 'omit how))
1025 for (name . value) in `((line . ,line)
1026 (bidx . ,(aref monkey 1))
1031 do (unless (memq name omit)
1035 (defmacro gnugo--awakened (how &rest body)
1036 (declare (indent 1))
1037 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1039 for name in '(line bidx monkey
1042 do (unless (memq name omit)
1045 (gnugo--awake ',how)
1048 (defsubst gnugo--move-to-bcol (bidx)
1049 (move-to-column (+ 10 (* 6 bidx))))
1051 (defun gnugo--swiz (direction &optional blunt)
1052 (gnugo--awakened (require-valid-branch
1055 (let* ((b (cond ((numberp blunt)
1056 (unless (and (< -1 blunt)
1058 (user-error "No such branch: %s" blunt))
1060 (t (mod (+ direction a) width))))
1061 (flit (if blunt (lambda (n)
1066 (mod (+ direction n) width))))
1067 (was (copy-sequence ends))
1068 (new-bidx (funcall flit bidx)))
1069 (loop for bx below width
1070 do (aset ends (funcall flit bx)
1072 (unless (= new-bidx bidx)
1073 (aset monkey 1 new-bidx))
1074 (gnugo-frolic-in-the-leaves)
1075 (goto-char (point-min))
1077 (gnugo--move-to-bcol b))))
1079 (defun gnugo-frolic-exchange-left ()
1080 "Exchange the current branch with the one to its left."
1084 (defun gnugo-frolic-rotate-left ()
1085 "Rotate all branches left."
1089 (defun gnugo-frolic-exchange-right ()
1090 "Exchange the current branch with the one to its right."
1094 (defun gnugo-frolic-rotate-right ()
1095 "Rotate all branches right."
1099 (defun gnugo-frolic-set-as-main-line ()
1100 "Make the current branch the main line."
1102 (gnugo--swiz nil 0))
1104 (defun gnugo-frolic-prune-branch ()
1105 "Remove the current branch from the gametree.
1106 This fails if there is only one branch in the tree.
1107 This fails if the monkey is on the current branch
1108 \(a restriction that will probably be lifted Real Soon Now\)."
1110 (gnugo--awakened (require-valid-branch
1111 (line . move-string))
1112 ;; todo: define meaningful eviction semantics; remove restriction
1114 (user-error "Cannot prune with monkey on branch"))
1116 (user-error "Cannot prune last remaining branch"))
1117 (let ((new (append ends nil)))
1118 ;; Explicit ignorance avoids byte-compiler warning.
1119 (ignore (pop (nthcdr a new)))
1120 (gnugo--set-tree-ends tree new))
1122 (aset monkey 1 (decf bidx)))
1123 (gnugo-frolic-in-the-leaves)
1125 (goto-char (point-min))
1126 (search-forward line)
1127 (gnugo--move-to-bcol (min a (- width 2))))))
1129 (defun gnugo--sideways (backwards n)
1130 (gnugo--awakened ((omit tree ends monkey bidx line))
1131 (gnugo--move-to-bcol (mod (if backwards
1136 (defun gnugo-frolic-backward-branch (&optional n)
1137 "Move backward N (default 1) branches."
1139 (gnugo--sideways t n))
1141 (defun gnugo-frolic-forward-branch (&optional n)
1142 "Move forward N (default 1) branches."
1144 (gnugo--sideways nil n))
1146 (defun gnugo--vertical (n direction)
1149 direction (- direction)))
1150 (gnugo--awakened ((line . numeric)
1151 (omit tree ends width monkey bidx))
1152 (let ((stop (if (> 0 direction)
1154 (max 0 (1- (count-lines (point-min)
1158 (loop while (not (= line stop))
1160 (forward-line direction)
1161 (incf line direction))
1162 until (get-text-property (point) 'n))
1163 until (zerop (decf n)))
1165 (gnugo--move-to-bcol a)
1166 (move-to-column col)))))
1168 (defun gnugo-frolic-previous-move (&optional n)
1169 "Move to the Nth (default 1) previous move."
1171 (gnugo--vertical n -1))
1173 (defun gnugo-frolic-next-move (&optional n)
1174 "Move to the Nth (default 1) next move."
1176 (gnugo--vertical n 1))
1178 (defun gnugo-boss-is-near ()
1179 "Do `bury-buffer' until the current one is not a GNU Board."
1181 (while (gnugo-board-buffer-p)
1184 (defsubst gnugo--passp (string)
1185 (string= "PASS" string))
1187 (defsubst gnugo--no-regrets (monkey ends)
1188 (eq (aref ends (aref monkey 1))
1191 (defun gnugo--as-cc-func ()
1192 (lexical-let ((size (gnugo-get :SZ)))
1194 (let* ((col (aref pos 0))
1195 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1196 (two (+ ?a (- size (string-to-number
1197 (substring pos 1))))))
1198 (format "%c%c" one two)))))
1200 (defsubst gnugo--decorate (node alist)
1201 ;; NB: ALIST should not have :B or :W keys.
1202 (setcdr (last node) alist))
1204 (defun gnugo-close-game (end-time resign)
1205 (gnugo-put :game-end-time end-time)
1206 (let ((now (or end-time (current-time))))
1207 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1209 (gnugo-put :game-over
1210 (if (or (eq t resign)
1211 (and (stringp resign)
1212 (string-match "[BW][+][Rr]esign" resign)))
1214 ((ls (color) (mapcar
1219 (gnugo-query "worm_stones %s" color)
1221 (let ((live (append (ls "black") (ls "white"))))
1224 (let ((dd (gnugo-query "dragon_data"))
1225 (start 0) mem color ent live dead)
1226 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1228 (setq mem (match-string 1 dd)
1229 color (match-string 2 dd)
1231 ent (cons (list color)
1232 (sort (gnugo-lsquery "dragon_stones %s" mem)
1234 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1236 (if (match-string 2 dd)
1239 (setq start (match-end 0)))
1243 (defun gnugo--unclose-game ()
1244 (gnugo--forget :game-over ; all those in -close-game
1247 (let* ((root (gnugo--root-node))
1248 (cur (assq :RE root)))
1250 (assert (not (eq cur (car root))) nil
1251 ":RE at head of root node: %S"
1255 (defun gnugo-push-move (who move)
1256 (let* ((simple (booleanp who))
1257 (ucolor (gnugo-get :user-color))
1261 (gnugo-get :gnugo-color))
1263 (start (gnugo-get :waiting-start))
1264 (now (current-time))
1265 (resignp (string= "resign" move))
1266 (passp (gnugo--passp move))
1267 (head (gnugo-move-history 'car))
1268 (onep (and head (gnugo--passp head)))
1269 (donep (or resignp (and onep passp))))
1271 (let ((accept (gnugo--q (format "play %s %s" color move))))
1272 (unless (= ?= (aref accept 0))
1273 (user-error "%s" accept))))
1275 (gnugo-merge-showboard-results))
1276 (gnugo-put :last-mover color)
1279 (string= ucolor color))
1280 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1281 ;; update :sgf-gametree and :monkey
1282 (let* ((property (if (gnugo--blackp color)
1284 (pair (cons property (cond (resignp move)
1286 (t (funcall (gnugo--as-cc-func)
1289 (monkey (gnugo-get :monkey))
1290 (mem (aref monkey 0))
1292 (tree (gnugo-get :sgf-gametree))
1293 (ends (gnugo--tree-ends tree))
1294 (mnum (gnugo--tree-mnum tree))
1295 (count (length ends))
1296 (tip-move-num (gethash tip mnum))
1297 (bidx (aref monkey 1)))
1298 ;; Detect déjà-vu. That is, when placing "A", avoid:
1304 ;; (such "variations" do not actually vary!) in favor of:
1310 ;; This linear search loses for multiple ‘old’ w/ "A",
1311 ;; a very unusual (but not invalid, sigh) situation.
1315 ;; Start with latest / highest likelihood for hit.
1316 ;; (See "to the right" comment, below.)
1317 from (if (gnugo--no-regrets monkey ends)
1321 if (setq bx (mod (+ bidx i) count)
1324 for m on (aref ends bx)
1325 while (< tip-move-num
1326 (gethash (setq node (car m))
1330 (when (equal pair (assq property node))
1338 (rotatef (aref ends bidx)
1340 (setq mem previous))
1344 (unless (gnugo--no-regrets monkey ends)
1345 (setq ends (gnugo--set-tree-ends
1346 tree (let ((ls (append ends nil)))
1347 ;; copy old to the right of new
1348 (push mem (nthcdr bidx ls))
1350 (puthash fruit (1+ (gethash tip mnum)) mnum)
1352 (aset ends bidx mem)))
1353 (setf (aref monkey 0) mem))
1355 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1357 (gnugo-close-game now resignp))
1358 (gnugo-put :waiting-start (and (not donep) now))
1361 (defun gnugo-venerate (yin yang)
1362 (let* ((fg-yy (gnugo-yy yin yang))
1363 (fg-disp (or (get fg-yy 'display)
1364 (get fg-yy 'do-not-display)))
1365 (fg-data (plist-get (cdr fg-disp) :data))
1366 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1367 (bg-disp (or (get bg-yy 'display)
1368 (get bg-yy 'do-not-display)))
1369 (bg-data (plist-get (cdr bg-disp) :data))
1373 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1374 (setq start (match-end 0))
1375 (string-to-number (match-string 1 s)))))
1376 (while (and (not (cl-minusp ncolors))
1377 (string-match ",\n" s start))
1378 (setq start (match-end 0)
1379 ncolors (1- ncolors)))
1380 (string-match "\"" s start)
1382 (new (copy-sequence fg-data))
1383 (lx (length fg-data))
1384 (sx (funcall bop fg-data))
1385 (sb (funcall bop bg-data))
1386 (color-key (aref new sx))) ; blech, heuristic
1388 (when (and (not (= color-key (aref new sx)))
1389 (cl-plusp (random 4)))
1390 (aset new sx (aref bg-data sb)))
1393 (create-image new 'xpm t :ascent 'center)))
1395 (defun gnugo-refresh (&optional nocache)
1396 "Update GNUGO Board buffer display.
1397 While a game is in progress, parenthesize the last-played stone (no parens
1398 for pass). If the buffer is currently displayed in the selected window,
1399 recenter the board (presuming there is extra space in the window). Update
1400 the mode line. Lastly, move point to the last position played by the user,
1401 if that move was not a pass.
1403 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1404 be slow. (This should normally be unnecessary; specify it only if the display
1405 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1408 (let* ((last-mover (gnugo-get :last-mover))
1409 (other (gnugo-other last-mover))
1410 (move (gnugo-move-history 'car))
1411 (game-over (gnugo-get :game-over))
1412 (inhibit-read-only t)
1414 (when (and nocache (not (gnugo-get :waiting)))
1415 (gnugo-propertize-board-buffer))
1418 (destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1419 (if (member move '("PASS" "resign"))
1420 (mapc 'delete-overlay (list l-ov r-ov))
1421 (gnugo-goto-pos move)
1423 (hspec (gnugo-get :highlight-last-move-spec))
1424 (display-value (nth 0 hspec))
1425 (l-offset (nth 1 hspec))
1426 (l-new-pos (+ p l-offset))
1427 (r-action (nth 2 hspec)))
1428 (overlay-put l-ov 'display
1429 (if (functionp display-value)
1430 (funcall display-value p)
1432 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1434 (funcall r-action r-ov)
1435 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1437 (rename-buffer (concat (gnugo-get :diamond)
1439 (format "%s(game over)"
1440 (if (string= move "resign")
1441 (concat move "ation ")
1443 (format "%s(%s to play)"
1444 (if move (concat move " ") "")
1448 (let ((live (cdr (assq 'live game-over)))
1449 (dead (cdr (assq 'dead game-over)))
1451 (unless (eq game-over (get-text-property 1 'game-over))
1452 (dolist (group (append live dead))
1453 (dolist (pos (cdr group))
1454 (gnugo-goto-pos pos)
1456 (put-text-property p (1+ p) 'group group)))
1457 (put-text-property 1 2 'game-over game-over))
1458 (dolist (group live)
1459 (when (setq pall (cdar group))
1460 (mapc 'delete-overlay pall)
1461 (setcdr (car group) nil)))
1462 (dolist (group dead)
1463 (unless (cdar group)
1464 (let (ov pall c (color (caar group)))
1465 (setq c (if (gnugo--blackp color) "x" "o"))
1466 (dolist (pos (cdr group))
1467 (gnugo-goto-pos pos)
1468 (setq p (point) ov (make-overlay p (1+ p)))
1471 (if (gnugo-get :display-using-images)
1472 ;; respect the dead individually; it takes more time
1473 ;; but that's not a problem (for them)
1474 (gnugo-venerate (get-text-property p 'gnugo-yin)
1475 (gnugo-yang (aref (upcase c) 0)))
1476 (propertize c 'face 'font-lock-warning-face)))
1478 (setcdr (car group) pall))))))
1480 (when (setq window (get-buffer-window (current-buffer)))
1481 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1482 (size (gnugo-get :SZ))
1483 (under10p (< size 10))
1484 (mul (gnugo-get :mul))
1485 (h (- (truncate (- (window-height window)
1490 (edges (window-edges window))
1491 (right-w-edge (nth 2 edges))
1492 (avail-width (- right-w-edge (nth 0 edges)))
1494 (imagesp (symbol-plist (gnugo-f 'ispc)))
1495 (w (/ (- avail-width
1500 2 ; between board and grid
1505 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1506 `(display ,(make-string h 10))
1507 '(invisible :nogrid)))
1512 (cond (imagesp (+ (* 0.5 wmul)
1518 (gspc . ,(when imagesp
1522 ;; DWR: image width alone => OBOE!
1524 ;; NB: ‘(* wmul cw)’ is the same
1525 ;; as ‘(car (image-size ... t))’.
1526 (let ((cw (frame-char-width)))
1527 (/ (+ 1.0 (* wmul cw))
1530 (lpad . ,(let ((d `(display (space :align-to ,w))))
1531 ;; We distinguish between these cases to
1532 ;; workaround a display bug whereby the
1533 ;; `before-string' is omitted entirely (not
1534 ;; rendered) when interacting w/ the text
1535 ;; mode last-move left-paren for moves in
1539 ,(apply 'propertize " " d))
1542 (space :align-to ,(1- avail-width))))))
1543 (setplist (gnugo-f (car pair)) (cdr pair)))))
1545 (let ((cur (gnugo-get :mode-line)))
1546 (unless (equal cur gnugo-mode-line)
1547 (setq cur gnugo-mode-line)
1548 (gnugo-put :mode-line cur)
1549 (gnugo-put :mode-line-form
1550 (cond ((stringp cur)
1551 (setq cur (copy-sequence cur))
1553 (while (setq cut (string-match "~[bwpmtu]" cur))
1555 (setq c (aref cur (incf cut)))
1558 `(,(intern (format "squig-%c" c))
1560 (?b '(or (gnugo-get :black-captures) 0))
1561 (?w '(or (gnugo-get :white-captures) 0))
1562 (?p '(gnugo-current-player))
1563 (?t '(let ((ws (gnugo-get :waiting-start)))
1565 (cadr (time-since ws))
1567 (?u '(or (gnugo-get :last-waiting) "-"))
1568 (?m '(let ((tree (gnugo-get :sgf-gametree))
1569 (monkey (gnugo-get :monkey)))
1570 (gethash (car (aref monkey 0))
1571 (gnugo--tree-mnum tree)
1572 ;; should be unnecessary
1575 `(let ,(delete-dups (copy-sequence acc))
1576 (format ,cur ,@(reverse (mapcar 'car acc))))))
1578 (let ((form (gnugo-get :mode-line-form)))
1579 (setq mode-line-process
1581 ;; this dynamicism is nice but excessive in its wantonness
1582 ;;- `(" [" (:eval ,form) "]")
1583 ;; this dynamicism is ok because the user triggers it
1584 (list (format " [%s]" (eval form))
1585 '(:eval (if (gnugo-get :abd)
1588 (force-mode-line-update))
1590 (when (setq last (gnugo-get :last-user-bpos))
1591 (gnugo-goto-pos last))))
1593 (defun gnugo--finish-move (buf)
1594 (run-hooks 'gnugo-post-move-hook)
1595 (with-current-buffer buf
1598 ;;;---------------------------------------------------------------------------
1599 ;;; Game play actions
1601 (defun gnugo--rename-buffer-portion (&optional back)
1602 (let ((old "to play")
1603 (new "waiting for suggestion"))
1606 (let ((name (buffer-name)))
1607 (when (string-match old name)
1608 (rename-buffer (replace-match new t t name))))))
1610 (defun gnugo-get-move-insertion-filter (proc string)
1611 (with-current-buffer (process-buffer proc)
1612 (let* ((so-far (gnugo-get :get-move-string))
1613 (full (gnugo-put :get-move-string (concat so-far string))))
1614 (when (string-match "^= \\(.+\\)\n\n" full)
1615 (destructuring-bind (pos-or-pass color . suggestion)
1616 (cons (match-string 1 full)
1617 (gnugo-get :waiting))
1618 (gnugo--forget :get-move-string
1622 (gnugo--rename-buffer-portion t)
1623 (unless (or (gnugo--passp full)
1624 (eq 'nowarp suggestion))
1625 (gnugo-goto-pos pos-or-pass))
1626 (message "%sSuggestion: %s"
1627 (gnugo-get :diamond)
1629 (let* ((donep (gnugo-push-move color pos-or-pass))
1630 (buf (current-buffer)))
1631 (gnugo--finish-move buf)
1632 (when (gnugo-get :abd)
1636 2 ;;; sec (frettoloso? dubioso!)
1637 nil (lambda (buf color)
1638 (with-current-buffer buf
1639 (gnugo-get-move color)))
1641 (gnugo-other color))))))))))))
1643 (defun gnugo-get-move (color &optional suggestion)
1644 (gnugo-put :waiting (cons color suggestion))
1645 (gnugo--begin-exchange
1646 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1647 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1648 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1649 (concat "reg_genmove " color))
1650 (accept-process-output))
1652 (defun gnugo-cleanup ()
1653 (when (gnugo-board-buffer-p)
1654 (unless (zerop (buffer-size))
1655 (message "Thank you for playing GNU Go."))
1657 (setplist sym nil) ; "...is next to fordliness." --Huxley
1658 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1659 ;; No worries, things will be Much Better w/ structs, RSN...
1661 (append (gnugo-get :all-yy)
1670 (setq gnugo-state nil)))
1672 (defun gnugo-position ()
1673 (or (get-text-property (point) 'gnugo-position)
1674 (user-error "Not a proper position point")))
1676 (defun gnugo-request-suggestion (&optional nowarp)
1677 "Request a move suggestion from GNU Go.
1678 After some time (during which you can do other stuff),
1679 Emacs displays the suggestion in the echo area and warps the
1680 cursor to the suggested position. Prefix arg inhibits warp."
1683 (gnugo--rename-buffer-portion)
1684 (gnugo-get-move (gnugo-get :user-color)
1689 (defun gnugo--user-play (pos-or-pass)
1691 (let ((donep (gnugo-push-move t pos-or-pass))
1692 (buf (current-buffer)))
1693 (gnugo--finish-move buf)
1695 (with-current-buffer buf
1696 (gnugo-get-move (gnugo-get :gnugo-color))))))
1698 (defun gnugo-move ()
1699 "Make a move on the GNUGO Board buffer.
1700 The position is computed from current point.
1701 Signal error if done out-of-turn or if game-over.
1702 To start a game try M-x gnugo."
1704 (gnugo--user-play (gnugo-position)))
1706 (defun gnugo-mouse-move (e)
1707 "Do `gnugo-move' at mouse location."
1710 (when (memq (following-char) '(?. ?+))
1713 (defun gnugo-pass ()
1714 "Make a pass on the GNUGO Board buffer.
1715 Signal error if done out-of-turn or if game-over.
1716 To start a game try M-x gnugo."
1718 (gnugo--user-play "PASS"))
1720 (defun gnugo-mouse-pass (e)
1721 "Do `gnugo-pass' at mouse location."
1726 (defun gnugo-resign ()
1729 (if (not (y-or-n-p "Resign? "))
1730 (message "(not resigning)")
1731 (gnugo-push-move t "resign")
1734 (defun gnugo-animate-group (w/d)
1735 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1736 (let* ((pos (gnugo-position))
1737 (orig-b-m-p (buffer-modified-p))
1739 (unless (memq (following-char) '(?X ?O))
1740 (user-error "No stone at %s" pos))
1741 (setq blurb (message "Computing %s stones ..." w/d)
1742 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1743 (message "%s %s in group." blurb (length stones))
1744 (setplist (gnugo-f 'anim) nil)
1745 (let* ((spec (if (gnugo-get :display-using-images)
1746 (loop with yin = (get-text-property (point) 'gnugo-yin)
1747 with yang = (gnugo-yang (following-char))
1748 with up = (get (gnugo-yy yin yang t) 'display)
1749 with dn = (get (gnugo-yy yin yang) 'display)
1750 for n below (length gnugo-animation-string)
1751 collect (if (zerop (logand 1 n))
1753 (split-string gnugo-animation-string "" t)))
1755 (ovs (save-excursion
1756 (mapcar (lambda (pos)
1757 (gnugo-goto-pos pos)
1759 (ov (make-overlay p (1+ p))))
1760 (overlay-put ov 'category (gnugo-f 'anim))
1761 (overlay-put ov 'priority most-positive-fixnum)
1764 (setplist (gnugo-f 'anim) (cons 'display cell))
1765 (while (and (cdr spec) ; let last linger lest levity lost
1766 (sit-for 0.08675309)) ; jenny jenny i got your number...
1767 (setcar cell (setq spec (cdr spec)))
1768 ;; Force redisplay of overlays.
1769 (set-buffer-modified-p orig-b-m-p))
1771 (mapc 'delete-overlay ovs)
1774 (defun gnugo-display-group-data (command buffer-name)
1775 (message "Computing %s ..." command)
1776 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1777 (switch-to-buffer buffer-name)
1780 (message "Computing %s ... done." command))
1782 (defun gnugo-worm-stones ()
1783 "In the GNUGO Board buffer, animate \"worm\" at current position.
1784 Signal error if done out-of-turn or if game-over.
1785 See variable `gnugo-animation-string' for customization."
1788 (gnugo-animate-group 'worm))
1790 (defun gnugo-worm-data ()
1791 "Display in another buffer data from \"worm\" at current position.
1792 Signal error if done out-of-turn or if game-over."
1795 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1797 (defun gnugo-dragon-stones ()
1798 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1799 Signal error if done out-of-turn or if game-over.
1800 See variable `gnugo-animation-string' for customization."
1803 (gnugo-animate-group 'dragon))
1805 (defun gnugo-dragon-data ()
1806 "Display in another buffer data from \"dragon\" at current position.
1807 Signal error if done out-of-turn or if game-over."
1810 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1812 (defun gnugo-estimate-score ()
1813 "Display estimated score of a game of GNU Go.
1814 Output includes number of stones on the board and number of stones
1815 captured by each player, and the estimate of who has the advantage (and
1816 by how many stones)."
1818 (message "Est.score ...")
1819 (let ((black (gnugo--count-query "list_stones black"))
1820 (white (gnugo--count-query "list_stones white"))
1821 (black-captures (gnugo-query "captures black"))
1822 (white-captures (gnugo-query "captures white"))
1823 (est (gnugo-query "estimate_score")))
1824 ;; might as well update this
1825 (gnugo-put :black-captures black-captures)
1826 (gnugo-put :white-captures white-captures)
1827 (message "Est.score ... B %s %s | W %s %s | %s"
1828 black black-captures white white-captures est)))
1830 (defun gnugo-write-sgf-file (filename)
1831 "Save the game history to FILENAME (even if unfinished).
1832 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1833 (interactive "FWrite game as SGF file: ")
1834 (when (and (file-exists-p filename)
1835 (not (y-or-n-p "File exists. Continue? ")))
1836 (user-error "Not writing %s" filename))
1837 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1838 (set-buffer-modified-p nil))
1840 (defun gnugo--who-is-who (wait play samep)
1841 (message "GNU Go %splays as %s, you as %s (%s)"
1842 (if samep "" "now ")
1845 "NOTE: this is a switch!")))
1847 (defsubst gnugo--nodep (x)
1848 (keywordp (caar x)))
1850 (defsubst gnugo--SZ! (size)
1851 (gnugo-put :SZ size))
1853 (defun gnugo--plant-and-climb (collection &optional sel)
1854 (gnugo-put :sgf-collection collection)
1855 (let ((tree (nth (or sel 0) collection)))
1856 (gnugo-put :sgf-gametree tree)
1857 (gnugo-put :monkey (vector
1859 (aref (gnugo--tree-ends tree) 0)
1864 (defun gnugo-read-sgf-file (filename)
1865 "Load the first game tree from FILENAME, a file in SGF format."
1866 (interactive "fSGF file to load: ")
1867 (when (file-directory-p filename)
1868 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1869 (let (ans play wait samep coll tree game-over)
1870 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1871 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1872 (unless (= ?= (aref (setq ans (gnugo--q "loadsgf %s"
1873 (expand-file-name filename)))
1875 (user-error "%s" ans))
1876 (setq play (substring ans 2)
1877 wait (gnugo-other play)
1878 samep (string= (gnugo-get :user-color) play))
1879 (gnugo-put :last-mover wait)
1881 (gnugo-put :gnugo-color wait)
1882 (gnugo-put :user-color play))
1883 (setq coll (gnugo/sgf-create filename)
1884 tree (gnugo--plant-and-climb
1885 coll (let ((n (length coll)))
1889 ;; (let* ((q (format "Which game? (1-%d)" n))
1890 ;; (choice (1- (read-number q 1))))
1891 ;; (if (and (< -1 choice) (< choice n))
1893 ;; (message "(Selecting the first game)")
1895 ;; but this is what we use (for now) to accomodate
1896 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1898 (message "(Selecting the first game)"))
1900 ;; This is deliberately undocumented for now.
1901 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1902 (when (setq game-over (or (gnugo--root-prop :RE tree)
1903 (when (equal '("PASS" "PASS")
1904 (gnugo-move-history 'two))
1906 (gnugo-close-game nil game-over))
1908 (set-buffer-modified-p nil)
1909 (gnugo--who-is-who wait play samep)))
1911 (defun gnugo-magic-undo (spec &optional noalt keep)
1912 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1913 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1914 check that the position is occupied by a stone of the user's color,
1915 and if so, remove moves from the history until that position is clear.
1916 If SPEC is a positive number, remove exactly that many moves from the
1917 history, signaling an error if the history is exhausted before finishing.
1918 If SPEC Is 0 (zero), remove either one or two moves,
1919 so that you are to play next.
1920 If SPEC is not recognized, signal \"bad spec\" error.
1922 Refresh the board for each move undone. If (in the case where SPEC is
1923 a number) after finishing, the color to play is not the user's color,
1924 schedule a move by GNU Go.
1926 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1927 turn to play. Optional second arg NOALT non-nil inhibits this.
1929 Optional third arg KEEP non-nil means do not prune the undone moves
1930 from the gametree, such that they become a sub-gametree (variation)
1934 (user-color (gnugo-get :user-color))
1935 (monkey (gnugo-get :monkey))
1936 (tree (gnugo-get :sgf-gametree))
1937 (ends (gnugo--tree-ends tree))
1938 (remorseful (not (gnugo--no-regrets monkey ends)))
1940 (cond ((numberp spec)
1941 (setq n (if (zerop spec)
1942 (if (string= user-color (gnugo-get :last-mover))
1946 done (lambda () (zerop n))))
1947 ((string-match "^[a-z]" spec)
1948 (let ((pos (upcase spec)))
1949 (setq done `(lambda ()
1950 (gnugo-goto-pos ,pos)
1951 (memq (following-char) '(?. ?+))))
1952 (when (funcall done)
1953 (user-error "%s already clear" pos))
1954 (when (= (save-excursion
1955 (gnugo-goto-pos pos)
1957 (if (gnugo--blackp user-color)
1960 (user-error "%s not occupied by %s" pos user-color))))
1961 (t (user-error "Bad spec: %S" spec)))
1962 (when (gnugo-get :game-over)
1963 (gnugo--unclose-game))
1964 (while (not (funcall done))
1965 (setq ans (gnugo--q "undo"))
1966 (unless (= ?= (aref ans 0))
1967 (user-error "%s" ans))
1968 (pop (aref monkey 0))
1969 (gnugo-put :last-mover (gnugo-current-player))
1970 (gnugo-merge-showboard-results) ; all
1971 (gnugo-refresh) ; this
1973 (redisplay)) ; eye candy
1974 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1976 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1977 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1979 (gnugo-get :center-position)))
1981 (unless (or keep remorseful)
1982 (aset ends (aref monkey 1) (aref monkey 0)))
1983 (when (and ulastp (not noalt))
1984 (gnugo-get-move (gnugo-get :gnugo-color))))))
1986 (defun gnugo-undo-one-move (&optional me-next)
1987 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1988 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1989 Prefix arg ME-NEXT means to arrange for you to play
1990 the color of the next move (and GNU Go the opposite).
1991 This is useful after loading an SGF file whose last
1992 move was done by the color you prefer to play:
1993 \\[gnugo-read-sgf-file] FILENAME RET
1994 C-u \\[gnugo-undo-one-move]
1996 See also `gnugo-undo-two-moves'."
1999 (gnugo-magic-undo 1 t)
2001 (let* ((wait (gnugo-get :last-mover))
2002 (play (gnugo-other wait)))
2003 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
2004 (gnugo-put :user-color play)
2005 (gnugo-put :gnugo-color wait))))
2007 (defun gnugo-undo-two-moves ()
2008 "Undo a pair of moves (GNU Go's and yours).
2009 However, if you are the last mover, undo only one move.
2010 Regardless, after undoing, it is your turn to play again."
2013 (gnugo-magic-undo 0))
2015 (defun gnugo-oops (&optional position)
2016 "Like `gnugo-undo-two-moves', but keep the undone moves.
2017 The kept moves become a sub-gametree (variation) when play resumes.
2018 Prefix arg means, instead, undo repeatedly up to and including
2019 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2022 (gnugo-magic-undo (if position
2027 (defun gnugo-okay (&optional full)
2028 "Redo a pair of undone moves.
2029 Prefix arg means to redo all the undone moves."
2032 (let* ((tree (gnugo-get :sgf-gametree))
2033 (ends (gnugo--tree-ends tree))
2034 (monkey (gnugo-get :monkey)))
2035 (if (gnugo--no-regrets monkey ends)
2036 (message "Oop ack!")
2037 (let* ((as-pos (gnugo--as-pos-func))
2038 (mnum (gnugo--tree-mnum tree))
2039 (mem (aref monkey 0))
2040 (bidx (aref monkey 1))
2041 (end (aref ends bidx))
2042 (ucolor (gnugo-get :user-color))
2043 (uprop (if (gnugo--blackp ucolor)
2045 (cl-flet ((mvno (node) (gethash node mnum)))
2049 (+ 2 (mvno (car mem))))
2050 with (node move todo)
2054 move (gnugo--move-prop node))
2055 (when (and move (>= ok (mvno node)))
2056 (let ((userp (eq uprop (car move))))
2058 (funcall as-pos (cdr move)))
2060 until (eq mem (cdr ls))
2063 for (userp pos) in todo
2065 (gnugo-push-move userp pos)
2069 (defun gnugo-display-final-score (&optional comment)
2070 "Display final score and other info in another buffer (when game over).
2071 If the game is still ongoing, Emacs asks if you wish to stop play (by
2072 making sure two \"pass\" moves are played consecutively, if necessary).
2073 Also, add the `:RE' SGF property to the root node of the game tree.
2074 Prefix arg COMMENT means to also attach the text (slightly compacted)
2075 to the last move, as a comment."
2077 (let ((game-over (gnugo-get :game-over)))
2078 (unless (or game-over
2079 (and (not (gnugo-get :waiting))
2080 (y-or-n-p "Game still in play. Stop play now? ")))
2081 (user-error "Sorry, game still in play"))
2085 (message "Playing PASS for %s ..."
2086 (gnugo-get (if userp :user-color :gnugo-color)))
2088 (gnugo-push-move userp "PASS")))
2093 (let ((b= " Black = ")
2095 (res (when (string= "resign" (gnugo-move-history 'car))
2096 (gnugo-get :last-mover)))
2100 (format "%s wins.\n"
2101 (substring (if (= ?b (aref res 0)) w= b=)
2103 "The game is over.\n"
2104 (format "Resignation by %s.\n" res))
2105 result (concat (upcase (substring (gnugo-other res) 0 1))
2107 (message "Computing final score ...")
2108 (let* ((g-over (gnugo-get :game-over))
2109 (live (cdr (assq 'live g-over)))
2110 (dead (cdr (assq 'dead g-over)))
2111 (seed (gnugo-get :scoring-seed))
2112 (terr-q (format "final_status_list %%s_territory %d" seed))
2115 (b-terr (gnugo--count-query terr-q "black"))
2116 (w-terr (gnugo--count-query terr-q "white"))
2117 (b-capt (string-to-number (gnugo-get :black-captures)))
2118 (w-capt (string-to-number (gnugo-get :white-captures)))
2119 (komi (gnugo--root-prop :KM)))
2120 (setq blurb (list "The game is over. Final score:\n")
2121 result (gnugo-query "final_score %d" seed))
2122 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2123 (dolist (group live)
2124 (incf (if (gnugo--blackp (caar group))
2127 (length (cdr group))))
2128 (dolist (group dead)
2129 (incf (if (gnugo--blackp (caar group))
2132 (length (cdr group))))
2133 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2134 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2135 w-terr terr komi 'komi (+ w-terr komi))
2138 (dolist (group dead)
2139 (incf (if (gnugo--blackp (caar group))
2142 (* 2 (length (cdr group)))))
2143 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2148 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2152 (+ w-terr w-capt komi))
2154 (push (if (string= "0" result)
2155 "The game is a draw.\n"
2156 (format "%s wins by %s.\n"
2157 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2158 (substring result 2)))
2160 (message "Computing final score ... done")))
2162 (let ((beg (gnugo-get :game-start-time))
2163 (end (gnugo-get :game-end-time)))
2167 ((yep (pretty moment)
2168 (push (format-time-string
2169 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2172 (yep "Game start" beg)
2174 (setq blurb (apply 'concat (nreverse blurb)))
2175 (gnugo--set-root-prop :RE result)
2177 (let ((node (car (aref (gnugo-get :monkey) 0))))
2179 (delq (assq :C node) node)
2180 (with-temp-buffer ; lame
2182 (when (search-backward "\n\nGame start:" nil t)
2183 (delete-region (point) (point-max)))
2184 (cl-flet ((rep (old new)
2185 (goto-char (point-min))
2186 (while (search-forward old nil t)
2187 (replace-match new))))
2188 (rep "The game is over. " "")
2189 (rep "territory" "T")
2190 (rep "captures" "C")
2192 `((:C . ,(buffer-string)))))))
2193 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2197 (defun gnugo-quit ()
2198 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2199 If the game is not over, ask for confirmation first."
2201 (if (or (gnugo-get :game-over)
2202 (y-or-n-p "Quit? "))
2204 (message "(not quitting)")))
2206 (defun gnugo-leave-me-alone ()
2207 "Kill the current buffer unconditionally."
2211 (defun gnugo-fancy-undo (count)
2212 "Rewind the game tree in various ways.
2213 Prefix arg COUNT means to undo that many moves.
2214 Otherwise, undo repeatedly up to and including the move
2215 which placed the stone at point."
2218 ;; TODO: Move this into `gnugo-magic-undo' proper.
2219 (cond ((numberp count) count)
2220 ((consp count) (car count))
2221 (t (gnugo-position)))))
2223 (defun gnugo-toggle-image-display-command () ; ugh
2224 "Toggle use of images to display the board, then refresh."
2226 (gnugo-toggle-image-display)
2227 (save-excursion (gnugo-refresh)))
2229 (defun gnugo--node-with-played-stone (pos)
2230 (let ((color (case (following-char)
2234 (loop with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
2235 for node in (aref (gnugo-get :monkey) 0)
2236 if (equal fruit (car node))
2238 finally return nil))))
2240 (defun gnugo-describe-position ()
2241 "Display the board position under cursor in the echo area.
2242 If there a stone at that position, also display its move number."
2244 (let* ((pos (gnugo-position)) ; do first (can throw)
2245 (node (gnugo--node-with-played-stone pos)))
2249 (let* ((tree (gnugo-get :sgf-gametree))
2250 (mnum (gnugo--tree-mnum tree))
2251 (move-num (gethash node mnum)))
2252 (format " (move %d)" move-num)))
2255 (defun gnugo-switch-to-another ()
2256 "Switch to another GNU Go game buffer (if any)."
2258 (loop for buf in (cdr (buffer-list))
2259 if (gnugo-board-buffer-p buf)
2262 (switch-to-buffer buf))
2263 finally do (message "(only one)")))
2265 (defun gnugo-comment (node comment)
2266 "Add to NODE a COMMENT (string) property.
2267 Called interactively, NODE is the one corresponding to the
2268 stone at point, and any previous comment is inserted as the
2269 initial-input (see `read-string').
2271 If COMMENT is nil or the empty string, remove the property entirely."
2273 (let* ((pos (gnugo-position))
2274 (node (or (gnugo--node-with-played-stone pos)
2275 (user-error "No stone at %s" pos))))
2277 (read-string (format "Comment for %s: "
2278 (gnugo-describe-position))
2279 (cdr (assq :C node))))))
2280 (setq node (delq (assq :C node) node))
2281 (unless (zerop (length comment))
2282 (gnugo--decorate node `((:C . ,comment)))))
2284 (defun gnugo-toggle-abdication ()
2285 "Toggle abdication, i.e., letting GNU Go play for you.
2286 When enabled, the mode line includes \"Abd\".
2287 Enabling signals error if the game is over.
2288 Disabling signals error if the color \"to play\" is the user color.
2289 This is to ensure that the user is the next to play after disabling."
2291 (let ((last-mover (gnugo-get :last-mover))
2292 (abd (gnugo-get :abd))
2296 (let ((gcolor (gnugo-get :gnugo-color)))
2297 (when (string= last-mover gcolor)
2298 (gnugo--ERR-wait gcolor "Sorry, too soon"))
2301 (gnugo--forget :abd)
2302 (unless (gnugo-get :waiting)
2303 (gnugo-get-move gcolor)))
2305 (gnugo--gate-game-over t)
2307 (gnugo-get-move (gnugo-other last-mover)))
2308 (message "Abdication %sabled%s"
2309 (if (gnugo-get :abd)
2314 ;;;---------------------------------------------------------------------------
2315 ;;; Command properties and gnugo-command
2317 ;; GTP commands entered by the user are never issued directly to GNU Go;
2318 ;; instead, their behavior and output are controlled by the property
2319 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2320 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2322 ;; :full -- completely interpret the command string; the value is a
2323 ;; func that takes the list of words derived from splitting the
2324 ;; command string (minus the command) and handles everything.
2326 ;; :output -- either a keyword specifying the preferred output method:
2327 ;; :message -- show output in minibuffer
2328 ;; :discard -- sometimes you just don't care;
2329 ;; or a function that takes one arg, the output string, and
2330 ;; handles it completely. default is to switch to buffer
2331 ;; "*gnugo command output*" if the output has a newline,
2332 ;; otherwise use `message'.
2334 ;; :post-thunk -- run after output processing (at the very end).
2336 (defun gnugo-command (command)
2337 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2338 Output and Emacs behavior depend on which command is given (some
2339 commands are handled completely by Emacs w/o using the subprocess;
2340 some commands have their output displayed in specially prepared
2341 buffers or in the echo area; some commands are instrumented to do
2342 gnugo.el-specific housekeeping).
2344 For example, for the command \"help\", Emacs visits the
2345 GTP command reference info page.
2347 NOTE: At this time, GTP command handling specification is still
2348 incomplete. Thus, some commands WILL confuse gnugo.el."
2349 (interactive "sCommand: ")
2350 (if (string= "" command)
2351 (message "(no command given)")
2352 (let* ((split (split-string command))
2353 (cmd (intern (car split)))
2354 (spec (get cmd :gnugo-gtp-command-spec))
2355 (full (plist-get spec :full)))
2357 (funcall full (cdr split))
2358 (message "Doing %s ..." command)
2359 (let* ((ans (gnugo--q command))
2360 (where (plist-get spec :output)))
2361 (if (string-match "unknown.command" ans)
2363 (cond ((functionp where) (funcall where ans))
2364 ((eq :discard where) (message ""))
2365 ((or (eq :message where)
2366 (not (string-match "\n" ans)))
2368 (t (switch-to-buffer "*gnugo command output*")
2371 (message "Doing %s ... done." command)))
2372 (let ((thunk (plist-get spec :post-thunk)))
2373 (when thunk (funcall thunk)))))))))
2375 ;;;---------------------------------------------------------------------------
2376 ;;; Major mode for interacting with a GNUGO subprocess
2378 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2379 "Major mode for playing GNU Go.
2380 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2381 In this mode, keys do not self insert.
2383 \\{gnugo-board-mode-map}"
2384 (buffer-disable-undo) ; todo: undo undo undoing
2385 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2387 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2388 (set (make-local-variable 'gnugo-state)
2389 (gnugo--mkht :size (1- 42)))
2390 (add-to-invisibility-spec :nogrid))
2392 ;;;---------------------------------------------------------------------------
2396 (defun gnugo (&optional new-game)
2397 "Run gnugo in a buffer, or resume a game in progress.
2398 Prefix arg means skip the game-in-progress check and start a new
2400 \\<gnugo-board-mode-map>
2401 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2403 You are queried for additional command-line options (Emacs supplies
2404 \"--mode gtp --quiet\" automatically). Here is a list of options
2405 that gnugo.el understands and handles specially:
2407 --boardsize num Set the board size to use (5--19)
2408 --color <color> Choose your color ('black' or 'white')
2409 --handicap <num> Set the number of handicap stones (0--9)
2411 If there is already a game in progress you may resume it instead of
2412 starting a new one. See `gnugo-board-mode' documentation for more info."
2414 (let* ((all (let (acc)
2415 (dolist (buf (buffer-list))
2416 (when (gnugo-board-buffer-p buf)
2417 (push (cons (buffer-name buf) buf) acc)))
2420 (if (and (not new-game)
2422 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2423 (if (= 1 n) "" "s"))))
2428 (let ((sel (completing-read "Which one? " all nil t)))
2429 (if (string= "" sel)
2431 (assoc sel all))))))
2433 (unless (executable-find gnugo-program)
2434 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2435 ;; set up a new board
2436 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2438 (let ((args (read-string "GNU Go options: "
2439 (car gnugo-option-history)
2440 'gnugo-option-history))
2442 board-size user-color handicap komi minus-l infile)
2443 (loop for (var default opt rx)
2444 in '((board-size 19 "--boardsize")
2445 (user-color "black" "--color" "\\(black\\|white\\)")
2446 (handicap 0 "--handicap")
2448 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
2449 (infile nil "--infile" "[ ]*[^ ]+"))
2451 (or (when (string-match opt args)
2452 (let ((start (match-end 0)) s)
2453 (string-match (or rx "[0-9.]+") args start)
2454 (setq s (match-string 0 args))
2455 (if rx s (string-to-number s))))
2457 (gnugo-put :user-color user-color)
2458 (let ((proc-args (split-string args)))
2459 (gnugo-put :proc-args proc-args)
2460 (gnugo-put :proc (setq proc (apply 'start-process "gnugo"
2463 "--mode" "gtp" "--quiet"
2465 (set-process-sentinel proc 'gnugo-sentinel)
2466 ;; Emacs is too protective sometimes, blech.
2467 (set-process-query-on-exit-flag proc nil)
2468 (when (or minus-l infile)
2470 in '((board-size "query_boardsize")
2472 (handicap "get_handicap"))
2473 do (set prop (string-to-number (gnugo-query q)))))
2474 (gnugo-put :diamond (substring (process-name proc) 5))
2475 (gnugo-put :gnugo-color (gnugo-other user-color))
2476 (gnugo-put :highlight-last-move-spec
2477 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2478 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2479 (let ((ov (make-overlay 1 1)))
2480 (overlay-put ov 'display ")")
2482 (gnugo--plant-and-climb
2483 (gnugo/sgf-create "(;FF[4]GM[1])" t))
2484 (gnugo--SZ! board-size)
2485 (let ((root (gnugo--root-node)))
2489 root (loop ; hmm, available elsewhere?
2491 collect (let* ((k (pop plist))
2495 :DT (format-time-string "%Y-%m-%d")
2496 :RU (if (string-match "--chinese-rules" args)
2499 :AP (cons "gnugo.el" gnugo-version)
2501 (let ((ub (gnugo--blackp user-color)))
2502 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2503 (if ub :PB :PW) (user-full-name)))
2504 (unless (zerop handicap)
2506 :AB (mapcar (gnugo--as-cc-func)
2507 (gnugo-lsquery "fixed_handicap %d"
2509 (gnugo-put :waiting-start (current-time))
2510 (gnugo-put :mul '(1 . 1))
2512 (let ((half (truncate (1+ (gnugo-get :SZ)) 2)))
2513 (gnugo-goto-pos (format "A%d" half))
2514 (forward-char (* 2 (1- half)))
2515 (gnugo-put :last-user-bpos
2516 (gnugo-put :center-position
2517 (get-text-property (point) 'gnugo-position))))
2519 (gnugo-put :game-start-time (current-time))
2520 (let ((g (gnugo-get :gnugo-color))
2521 (n (or (gnugo--root-prop :HA) 0))
2522 (u (gnugo-get :user-color)))
2523 (gnugo-put :last-mover
2524 (if (or (and (gnugo--blackp u) (< 1 n))
2525 (and (gnugo--blackp g) (< n 2)))
2528 (run-hooks 'gnugo-start-game-hook)
2529 (when (string= g (gnugo-current-player))
2531 (gnugo-get-move g))))))
2533 ;;;---------------------------------------------------------------------------
2534 ;;; Load-time actions
2536 (unless gnugo-frolic-mode-map
2537 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2538 (suppress-keymap gnugo-frolic-mode-map)
2539 (mapc (lambda (pair)
2540 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2541 '(("q" . gnugo-frolic-quit)
2542 ("Q" . gnugo-frolic-quit)
2543 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2544 ("\C-b" . gnugo-frolic-backward-branch)
2545 ("\C-f" . gnugo-frolic-forward-branch)
2546 ("\C-p" . gnugo-frolic-previous-move)
2547 ("\C-n" . gnugo-frolic-next-move)
2548 ("j" . gnugo-frolic-exchange-left)
2549 ("J" . gnugo-frolic-rotate-left)
2550 ("k" . gnugo-frolic-exchange-right)
2551 ("K" . gnugo-frolic-rotate-right)
2552 ("\C-m" . gnugo-frolic-set-as-main-line)
2553 ("\C-\M-p" . gnugo-frolic-prune-branch)
2554 ("o" . gnugo-frolic-return-to-origin))))
2556 (unless gnugo-board-mode-map
2557 (setq gnugo-board-mode-map (make-sparse-keymap))
2558 (suppress-keymap gnugo-board-mode-map)
2559 (mapc (lambda (pair)
2560 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2561 '(("?" . describe-mode)
2562 ("S" . gnugo-request-suggestion)
2563 ("\C-m" . gnugo-move)
2566 ("R" . gnugo-resign)
2568 ("Q" . gnugo-leave-me-alone)
2569 ("U" . gnugo-fancy-undo)
2570 ("\M-u" . gnugo-undo-one-move)
2571 ("u" . gnugo-undo-two-moves)
2572 ("\C-?" . gnugo-undo-two-moves)
2575 ("\C-l" . gnugo-refresh)
2576 ("\M-_" . gnugo-boss-is-near)
2577 ("_" . gnugo-boss-is-near)
2578 ("h" . gnugo-move-history)
2579 ("L" . gnugo-frolic-in-the-leaves)
2580 ("i" . gnugo-toggle-image-display-command)
2581 ("w" . gnugo-worm-stones)
2582 ("W" . gnugo-worm-data)
2583 ("d" . gnugo-dragon-stones)
2584 ("D" . gnugo-dragon-data)
2585 ("g" . gnugo-toggle-grid)
2586 ("!" . gnugo-estimate-score)
2587 (":" . gnugo-command)
2588 (";" . gnugo-command)
2589 ("=" . gnugo-describe-position)
2590 ("s" . gnugo-write-sgf-file)
2591 ("\C-x\C-s" . gnugo-write-sgf-file)
2592 ("\C-x\C-w" . gnugo-write-sgf-file)
2593 ("l" . gnugo-read-sgf-file)
2594 ("F" . gnugo-display-final-score)
2595 ("A" . gnugo-switch-to-another)
2596 ("C" . gnugo-comment)
2597 ("\C-c\C-a" . gnugo-toggle-abdication)
2599 ([(down-mouse-1)] . gnugo-mouse-move)
2600 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2601 ([(down-mouse-3)] . gnugo-mouse-pass)
2602 ;; delving into the curiosities
2603 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2605 (unless (get 'help :gnugo-gtp-command-spec)
2607 ((sget (x) (get x :gnugo-gtp-command-spec))
2608 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2609 (plist-put (sget cmd) prop val)))
2610 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2613 (jam cmd (car ls) (cadr ls))
2614 (setq ls (cddr ls)))))))
2615 (cl-macrolet ((deffull (who &body body)
2616 (declare (indent 1))
2617 `(defgtp ',who :full (lambda (sel)
2621 (info "(gnugo)GTP command reference")
2622 (when sel (setq sel (intern (car sel))))
2623 (let (buffer-read-only pad cur spec output found)
2625 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2626 (goto-char (point-min))
2628 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2631 (setq pad (make-string (- (match-beginning 1)
2632 (match-beginning 0))
2636 (get (setq cur (intern (match-string 1)))
2637 :gnugo-gtp-command-spec))
2639 (note "handles this command completely"))
2640 (when (setq output (plist-get spec :output))
2641 (if (functionp output)
2642 (note "handles the output specially")
2644 (:discard (note "discards the output"))
2645 (:message (note "displays the output in the echo area")))))
2647 (setq found (match-beginning 0))))))
2648 (cond (found (goto-char found))
2650 (t (message "(no such command: %s)" sel)))))
2652 (deffull final_score
2653 ;; Explicit ignorance avoids byte-compiler warning.
2655 (gnugo-display-final-score))
2661 :post-thunk (lambda ()
2662 (gnugo--unclose-game)
2663 (gnugo--forget :last-mover)
2665 (gnugo--SZ! (string-to-number
2667 "query_boardsize")))
2671 (gnugo-read-sgf-file (car sel)))
2673 (deffull (undo gg-undo)
2677 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2678 (t (car sel)))))))))
2683 ;;;---------------------------------------------------------------------------
2684 ;;; The remainder of this file defines a simplified SGF-handling library.
2685 ;;; When/if it should start to attain generality, it should be split off into
2686 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2687 ;;; "gnugo/" prefix.
2689 (defconst gnugo/sgf-*r4-properties*
2690 '((AB "Add Black" setup list stone)
2691 (AE "Add Empty" game list point)
2692 (AN "Annotation" game simpletext)
2693 (AP "Application" root (simpletext . simpletext))
2694 (AR "Arrow" - list (point . point))
2695 (AS "Who adds stones" - simpletext) ; (LOA)
2696 (AW "Add White" setup list stone)
2697 (B "Black" move move)
2698 (BL "Black time left" move real)
2699 (BM "Bad move" move double)
2700 (BR "Black rank" game simpletext)
2701 (BT "Black team" game simpletext)
2702 (C "Comment" - text)
2703 (CA "Charset" root simpletext)
2704 (CP "Copyright" game simpletext)
2705 (CR "Circle" - list point)
2706 (DD "Dim points" - elist point) ; (inherit)
2707 (DM "Even position" - double)
2708 (DO "Doubtful" move none)
2709 (DT "Date" game simpletext)
2710 (EV "Event" game simpletext)
2711 (FF "Fileformat" root [number (1 . 4)])
2712 (FG "Figure" - (or none (number . simpletext)))
2713 (GB "Good for Black" - double)
2714 (GC "Game comment" game text)
2715 (GM "Game" root [number (1 . 20)])
2716 (GN "Game name" game simpletext)
2717 (GW "Good for White" - double)
2718 (HA "Handicap" game number) ; (Go)
2719 (HO "Hotspot" - double)
2720 (IP "Initial pos." game simpletext) ; (LOA)
2721 (IT "Interesting" move none)
2722 (IY "Invert Y-axis" game simpletext) ; (LOA)
2723 (KM "Komi" game real) ; (Go)
2725 (LB "Label" - list (point . simpletext))
2726 (LN "Line" - list (point . point))
2727 (MA "Mark" - list point)
2728 (MN "set move number" move number)
2729 (N "Nodename" - simpletext)
2730 (OB "OtStones Black" move number)
2731 (ON "Opening" game text)
2732 (OT "Overtime" game simpletext)
2733 (OW "OtStones White" move number)
2734 (PB "Player Black" game simpletext)
2735 (PC "Place" game simpletext)
2736 (PL "Player to play" setup color)
2737 (PM "Print move mode" - number) ; (inherit)
2738 (PW "Player White" game simpletext)
2739 (RE "Result" game simpletext)
2740 (RO "Round" game simpletext)
2741 (RU "Rules" game simpletext)
2742 (SE "Markup" - point) ; (LOA)
2743 (SL "Selected" - list point)
2744 (SO "Source" game simpletext)
2745 (SQ "Square" - list point)
2746 (ST "Style" root [number (0 . 3)])
2747 (SU "Setup type" game simpletext) ; (LOA)
2748 (SZ "Size" root (or number (number . number)))
2749 (TB "Territory Black" - elist point) ; (Go)
2750 (TE "Tesuji" move double)
2751 (TM "Timelimit" game real)
2752 (TR "Triangle" - list point)
2753 (TW "Territory White" - elist point) ; (Go)
2754 (UC "Unclear pos" - double)
2755 (US "User" game simpletext)
2757 (VW "View" - elist point) ; (inherit)
2758 (W "White" move move)
2759 (WL "White time left" move real)
2760 (WR "White rank" game simpletext)
2761 (WT "White team" game simpletext)
2762 (LT "Lose on time" setup simpletext))
2763 ;; r4-specific notes
2764 ;; - changed: DT FG LB RE RU SZ
2765 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2766 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2768 (defun gnugo/sgf-create (file-or-data &optional data-p)
2769 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2770 FILE-OR-DATA is a file name or SGF[4] data.
2771 Optional arg DATA-P non-nil means FILE-OR-DATA is
2772 a string containing SGF[4] data.
2773 A collection is a list of gametrees, each a vector of four elements:
2775 ENDS -- a vector of node lists, with shared tails
2776 (last element of all the lists is the root node)
2778 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2779 have a move number of the previous \"move\" node (or zero)
2781 ROOT -- the root node"
2782 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2783 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2784 (put 'gnugo/sgf-*r4-properties* :keywords
2785 (mapcar (lambda (full)
2787 (intern (format ":%s" (car full)))))
2788 gnugo/sgf-*r4-properties*))))
2789 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2790 (put 'gnugo/sgf-*r4-properties* :specs
2791 (mapcar (lambda (full)
2792 (cons (car full) (cdddr full)))
2793 gnugo/sgf-*r4-properties*))))
2796 ((sw () (skip-chars-forward " \t\n"))
2797 (x (end preserve-whitespace)
2800 (:end (lambda (char) (= ?\] char)))
2801 (:mid (lambda (char) (= ?\: char)))
2802 (t (lambda (char) (or (= ?\: char)
2805 (while (not (funcall endp (setq c (following-char))))
2811 ((unless preserve-whitespace
2812 (looking-at "\\s-+"))
2813 (delete-region (point) (match-end 0))
2815 (t (forward-char 1))))
2816 (buffer-substring-no-properties beg (point))))
2817 (one (type end) (let ((s (progn
2819 (x end (eq 'text type)))))
2822 ;; blech, begone bu"tt"-ugly blatherings
2823 ;; (but bide brobdingnagian boards)...
2824 (if (and (string= "tt" s)
2829 ((simpletext color) s)
2830 ((number real double) (string-to-number s))
2833 (t (error "Unhandled type: %S" type)))))
2834 (val (spec) (cond ((symbolp spec)
2837 ;; todo: check range here.
2838 (one (aref spec 0) :end))
2839 ((eq 'or (car spec))
2840 (let ((v (one (cadr spec) t)))
2841 (if (= ?\] (following-char))
2844 ;; todo: this assumes `spec' has the form
2845 ;; (or foo (foo . bar))
2846 ;; i.e., foo is not rescanned. e.g., `SZ'.
2847 ;; probably this assumption is consistent
2848 ;; w/ the SGF authors' desire to make the
2849 ;; parsing easy, but you never know...
2850 (cons v (one (cdaddr spec) :end)))))
2851 (t (cons (one (car spec) :mid)
2852 (one (cdr spec) :end)))))
2853 (short (who) (when (eobp)
2854 (error "Unexpected EOF while reading %s" who)))
2855 (atvalp () (= ?\[ (following-char)))
2856 (PROP () (let (name spec ltype)
2857 (sw) (short 'property)
2858 (when (looking-at "[A-Z]")
2859 (setq name (read (current-buffer))
2860 spec (cdr (assq name specs)))
2863 (cdr (assq name keywords))
2864 (prog1 (if (= 1 (length spec))
2866 (unless (memq (setq ltype (car spec))
2868 (error "Bad spec: %S" spec))
2869 (if (and (eq 'elist ltype) (sw)
2872 (let ((type (cadr spec))
2874 (while (and (sw) (atvalp)
2875 (setq mo (val type)))
2880 (forward-char 1))))))
2881 (morep () (and (sw) (not (eobp))))
2882 (seek (c) (and (morep) (= c (following-char))))
2883 (seek-into (c) (when (seek c)
2886 (NODE () (when (seek-into ?\;)
2888 while (setq prop (PROP))
2890 (when (eq :SZ (car prop))
2891 (setq SZ (cdr prop)))
2900 (puthash node (+ (if (gnugo--move-prop node)
2903 (gethash prev mnum 0))
2908 (if (not (seek ?\())
2912 (loop while (seek ?\()
2913 append (TREE ls mnum)))
2917 (insert-file-contents file-or-data)
2918 (insert file-or-data)
2919 (goto-char (point-min)))
2921 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2922 (ends (TREE nil mnum))
2923 (root (car (last (car ends)))))
2924 (vector (apply 'vector ends)
2928 (defun gnugo/sgf-write-file (collection filename)
2929 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2930 (me (cons "gnugo.el" gnugo-version))
2931 (specs (mapcar (lambda (full)
2932 (cons (intern (format ":%s" (car full)))
2934 gnugo/sgf-*r4-properties*))
2937 ((esc (composed fmt arg)
2938 (mapconcat (lambda (c)
2940 ;; ‘?\[’ is not strictly required
2941 ;; but neither is it forbidden.
2942 ((?\[ ?\] ?\\) (format "\\%c" c))
2943 (?: (concat (if composed "\\" "") ":"))
2945 (string-to-list (format fmt arg))
2947 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2948 (>>two (v) (insert "["
2949 (esc t "%s" (car v))
2951 (esc t "%s" (cdr v))
2953 (>>nl () (cond ((memq name aft-newline-appreciated)
2955 ((< 60 (current-column))
2963 (insert (substring (symbol-name name) 1))
2966 (setq spec (cdr (assq name specs)))
2970 (let ((>> (if (consp (cadr spec))
2973 (dolist (little-v v)
2975 (funcall >> little-v)
2982 (loop initially (insert ";")
2986 (unless (zerop (current-column))
2990 (funcall (if (gnugo--nodep x)
2996 (dolist (tree collection)
2997 ;; take responsibility for our actions
2998 (gnugo--set-root-prop :AP me tree)
3000 (let ((ht (gnugo--mkht))
3001 (leaves (append (gnugo--tree-ends tree) nil)))
3005 with rh ; rectified history
3006 with bp ; branch point
3008 until (setq bp (gethash node ht))
3010 (push node rh) ; good for now: ½τ
3014 ;; first run: main line
3016 ;; subsequent runs: grafts (value discarded)
3018 ;; Maintain order of ‘leaves’.
3019 (let ((was (cdr bp)))
3020 (if (gnugo--nodep (car was))
3024 (setq tree (hang (pop leaves)))
3025 (mapc #'hang leaves)
3028 (write-file filename)))))
3030 ;;; gnugo.el ends here