1 ;;; gnugo.el --- play GNU Go in a buffer -*- lexical-binding: t -*-
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--prop<-color (color)
348 (if (gnugo--blackp color) :B :W))
350 (defsubst gnugo--gate-game-over (enable)
351 (when (and enable (gnugo-get :game-over))
352 (user-error "Sorry, game over")))
354 (defun gnugo--ERR-wait (color why)
355 (user-error "%s -- please wait for \"(%s to play)\""
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)))
365 (gnugo--ERR-wait (gnugo-get :user-color)
368 "Not your turn yet"))))
369 (gnugo--gate-game-over in-progress-p))
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
379 (propertize (car (split-string string))
380 'face 'font-lock-warning-face)
382 (when (eq proc (gnugo-get :proc))
383 (gnugo--forget :proc))))))))
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"))
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)))
399 (user-error "Sorry, still waiting for %s to %s"
400 (car slow) (if (cdr slow)
401 "receive a suggestion"
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)
409 (process-put proc :srs full)
410 (unless (numberp (gnugo--compare-strings
411 full (max 0 (- (length full)
414 (process-put proc :incomplete nil))))
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 ""))))
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))
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)
437 (defun gnugo--nquery (cmd)
438 (string-to-number (gnugo-query cmd)))
440 (defun gnugo-lsquery (message-format &rest args)
441 (split-string (apply 'gnugo-query message-format args)))
443 (defsubst gnugo--count-query (fmt &rest args)
444 (length (apply 'gnugo-lsquery fmt args)))
446 (defsubst gnugo--root-prop (prop &optional tree)
447 (cdr (assq prop (gnugo--root-node tree))))
449 (defun gnugo--set-root-prop (prop value &optional tree)
450 (let* ((root (gnugo--root-node tree))
451 (cur (assq prop root)))
454 (push (cons prop value)
455 (cdr (last root))))))
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))))
463 (forward-char (+ (if (= 32 (following-char)) 1 2)
464 (* 2 (- (let ((letter (aref pos 0)))
470 (defun gnugo-f (frag)
471 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
473 (defun gnugo-yang (c)
474 (cdr (assq c '((?+ . hoshi)
476 (?X . (bmoku . bpmoku))
477 (?O . (wmoku . wpmoku))))))
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))
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)))
498 (setcar (symbol-plist yy) act))
499 (or (gnugo-get :all-yy)
501 (prog1 (mapcar (lambda (ent)
503 (yy (gnugo-yy (cdr k) (car k))))
504 (setplist yy `(not-yet ,(cdr ent)))
508 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
510 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
511 (gnugo-put :highlight-last-move-spec
514 (get (gnugo-yy (get-text-property p 'gnugo-yin)
515 (get-text-property p 'gnugo-yang)
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
527 (gnugo-put :display-using-images new)))
529 (defun gnugo-toggle-grid ()
530 "Turn the grid around the board on or off."
532 (funcall (if (memq :nogrid buffer-invisibility-spec)
533 'remove-from-invisibility-spec
534 'add-to-invisibility-spec)
536 (save-excursion (gnugo-refresh)))
538 (defun gnugo-propertize-board-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)
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))
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)))
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)))
577 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
578 (truncate (- p edge) 2))
580 (yin (let ((A-p (= edge p))
581 (Z-p (= (1- other-edge) p)))
582 (cond ((and top-p A-p) 1)
591 (yang (gnugo-yang (char-after p))))
592 (add-text-properties p (1+ p)
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))
612 (beg (match-beginning 2))
614 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
615 (gnugo-put prop (match-string-no-properties 2))))
617 (put-text-property right-empty (point) 'category %rpad)
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))
625 (defun gnugo-merge-showboard-results ()
626 (let ((aft (substring (gnugo--q "showboard") 3))
627 (adj 1) ; string to buffer position adjustment
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:
634 ;; ... WHITE has captured 1 stones
637 ;; ... WHITE has captured 14 stones
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).
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
650 (inhibit-read-only t))
651 (while (numberp (setq mis (gnugo--compare-strings
654 (setq aft-sync-backtrack nil
655 inc (if (cl-minusp mis)
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))
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))))
671 (if aft-sync-backtrack
672 (- aft-sync-backtrack aft-idx)
675 (if aft-sync-backtrack
676 (let* ((asb aft-sync-backtrack)
677 (l-p (get-text-property cut :gnugo-cf))
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)
695 ,(gnugo-yy yin yang))))
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))))))
702 (defsubst gnugo--move-prop (node)
706 (defun gnugo--as-pos-func ()
707 (lexical-let ((size (gnugo-get :SZ)))
712 (let ((col (aref cc 0)))
714 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
715 (- size (- (aref cc 1) ?a))))))))
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."
731 (let* ((monkey (gnugo-get :monkey))
732 (mem (aref monkey 0))
733 (as-pos (gnugo--as-pos-func))
736 ((as-pos-maybe (x) (if (string= "resign" 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)
745 (format "%s%s" move (car mprop))
749 (tell () (message "(%d moves) %s"
751 (mapconcat 'identity (nreverse acc) " ")))
752 (finish (byp) (while mem (next byp)) (tell)))
757 (`cadr (nn) (car (nn)))
759 (`bpos (loop with prop = (gnugo--prop<-color color)
761 (eq prop (car mprop))
763 (not (string= "resign" move))
764 (not (gnugo--passp move)))
768 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
769 "A special mode for manipulating a GNUGO gametree.
771 \\{gnugo-frolic-mode-map}"
772 (setq truncate-lines t)
773 (buffer-disable-undo))
775 (defun gnugo-frolic-quit ()
776 "Kill GNUGO Frolic buffer and switch to its parent buffer."
778 (let ((bye (current-buffer)))
779 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
780 gnugo-frolic-parent-buffer))
783 (defun gnugo-frolic-return-to-origin ()
784 "Move point to the board's current position."
786 (if (not gnugo-frolic-origin)
787 (message "No origin")
788 (goto-char gnugo-frolic-origin)
789 (recenter (- (count-lines (line-beginning-position)
792 (defun gnugo-frolic-in-the-leaves ()
793 "Display the game tree in a *GNUGO Frolic* buffer.
794 This looks something like:
797 2 W -- K10 K10 K10 K10
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."
823 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
825 (from (or gnugo-frolic-parent-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))
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))
844 (max-move-num (apply 'max (append valid nil)))
845 (inhibit-read-only t)
851 (propertize s 'face face))
852 (fsi (properties fmt &rest args)
853 (insert (apply 'propertize
854 (apply 'format fmt args)
861 for node in (aref ends bx)
862 do (if (setq fork (on node))
865 ;; todo: ignore non-"move" nodes
866 (eq node (car (aref ends bix))))
868 (pushnew other (gethash node soil))))
873 (puthash node bx seen))
876 (switch-to-buffer buf)
879 (setq header-line-format
880 (lexical-let ((full (concat
882 (mapconcat (lambda (n)
892 `(space :width ,w))))
894 (when (eq 'left scroll-bar-mode)
895 (let ((w (or scroll-bar-width
897 nil 'scroll-bar-width)))
898 (cw (frame-char-width)))
902 (let ((fc (fringe-columns 'left t)))
906 (substring full (window-hscroll))
908 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
909 (set (make-local-variable 'gnugo-state)
910 (buffer-local-value 'gnugo-state from))
914 from max-move-num downto 1
915 do (setq props (list 'n n))
920 (goto-char (point-min))
923 n (aref ["W" "B"] (logand 1 n))))
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))
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))))))
938 (push 'help-echo zow))
939 (when (and ok (setq br (gethash node soil)))
940 (push (cons bx (sort br '<))
945 (cond ((and (eq at node)
948 (setq finish (point-marker)))
949 (emph s (list :inherit 'default
950 :foreground (frame-parameter
951 nil 'cursor-color))))
953 (emph s dimmed-node-face))
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)))
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 "-----"))
970 (spaced lanes (lambda (bx)
974 (pad-unless (condition)
985 do (let* ((one (car ls))
988 (mapcar 'car (cdr ls))
990 (apply 'append (mapcar 'cdr bef))))
993 (end (car (last ord))))
995 ((also (b e) (cnxn (number-sequence b e)
1000 (pad-unless (zerop beg))
1001 (dashed (number-sequence beg end)
1003 (cond ((memq bx ord) "+")
1006 (pad-unless (>= end width))
1007 (also (1+ end) (1- width))
1010 (edge (apply 'append tails))
1011 (aa2u (line-beginning-position
1012 (- (1+ (length forks))))
1015 (set (make-local-variable 'gnugo-frolic-origin) finish)
1016 (gnugo-frolic-return-to-origin))))
1018 (defun gnugo--awake (how)
1019 ;; Valid HOW elements:
1020 ;; require-valid-branch
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))
1030 (count-lines (point-min) (line-beginning-position)))
1033 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1036 (col (current-column))
1037 (a (unless (> 10 col)
1038 (let ((try (/ (- col 10)
1040 (unless (<= width try)
1043 (when (memq 'require-valid-branch how)
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))
1053 do (unless (memq name omit)
1057 (defmacro gnugo--awakened (how &rest body)
1058 (declare (indent 1))
1059 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1061 for name in '(line bidx monkey
1064 do (unless (memq name omit)
1067 (gnugo--awake ',how)
1070 (defsubst gnugo--move-to-bcol (bidx)
1071 (move-to-column (+ 10 (* 6 bidx))))
1073 (defun gnugo--swiz (direction &optional blunt)
1074 (gnugo--awakened (require-valid-branch
1077 (let* ((b (cond ((numberp blunt)
1078 (unless (and (< -1 blunt)
1080 (user-error "No such branch: %s" blunt))
1082 (t (mod (+ direction a) width))))
1083 (flit (if blunt (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)
1094 (unless (= new-bidx bidx)
1095 (aset monkey 1 new-bidx))
1096 (gnugo-frolic-in-the-leaves)
1097 (goto-char (point-min))
1099 (gnugo--move-to-bcol b))))
1101 (defun gnugo-frolic-exchange-left ()
1102 "Exchange the current branch with the one to its left."
1106 (defun gnugo-frolic-rotate-left ()
1107 "Rotate all branches left."
1111 (defun gnugo-frolic-exchange-right ()
1112 "Exchange the current branch with the one to its right."
1116 (defun gnugo-frolic-rotate-right ()
1117 "Rotate all branches right."
1121 (defun gnugo-frolic-set-as-main-line ()
1122 "Make the current branch the main line."
1124 (gnugo--swiz nil 0))
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\)."
1132 (gnugo--awakened (require-valid-branch
1133 (line . move-string))
1134 ;; todo: define meaningful eviction semantics; remove restriction
1136 (user-error "Cannot prune with monkey on branch"))
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))
1144 (aset monkey 1 (decf bidx)))
1145 (gnugo-frolic-in-the-leaves)
1147 (goto-char (point-min))
1148 (search-forward line)
1149 (gnugo--move-to-bcol (min a (- width 2))))))
1151 (defun gnugo--sideways (backwards n)
1152 (gnugo--awakened ((omit tree ends monkey bidx line))
1153 (gnugo--move-to-bcol (mod (if backwards
1158 (defun gnugo-frolic-backward-branch (&optional n)
1159 "Move backward N (default 1) branches."
1161 (gnugo--sideways t n))
1163 (defun gnugo-frolic-forward-branch (&optional n)
1164 "Move forward N (default 1) branches."
1166 (gnugo--sideways nil n))
1168 (defun gnugo--vertical (n direction)
1171 direction (- direction)))
1172 (gnugo--awakened ((line . numeric)
1173 (omit tree ends width monkey bidx))
1174 (let ((stop (if (> 0 direction)
1176 (max 0 (1- (count-lines (point-min)
1180 (loop while (not (= line stop))
1182 (forward-line direction)
1183 (incf line direction))
1184 until (get-text-property (point) 'n))
1185 until (zerop (decf n)))
1187 (gnugo--move-to-bcol a)
1188 (move-to-column col)))))
1190 (defun gnugo-frolic-previous-move (&optional n)
1191 "Move to the Nth (default 1) previous move."
1193 (gnugo--vertical n -1))
1195 (defun gnugo-frolic-next-move (&optional n)
1196 "Move to the Nth (default 1) next move."
1198 (gnugo--vertical n 1))
1200 (defun gnugo-boss-is-near ()
1201 "Do `bury-buffer' until the current one is not a GNU Board."
1203 (while (gnugo-board-buffer-p)
1206 (defsubst gnugo--passp (string)
1207 (string= "PASS" string))
1209 (defsubst gnugo--no-regrets (monkey ends)
1210 (eq (aref ends (aref monkey 1))
1213 (defun gnugo--as-cc-func ()
1214 (lexical-let ((size (gnugo-get :SZ)))
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)))))
1222 (defsubst gnugo--decorate (node alist)
1223 ;; NB: ALIST should not have :B or :W keys.
1224 (setcdr (last node) alist))
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)
1231 (gnugo-put :game-over
1232 (if (or (eq t resign)
1233 (and (stringp resign)
1234 (string-match "[BW][+][Rr]esign" resign)))
1236 ((ls (color) (mapcar
1241 (gnugo-query "worm_stones %s" color)
1243 (let ((live (append (ls "black") (ls "white"))))
1246 (let ((dd (gnugo-query "dragon_data"))
1247 (start 0) mem color ent live dead)
1248 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1250 (setq mem (match-string 1 dd)
1251 color (match-string 2 dd)
1253 ent (cons (list color)
1254 (sort (gnugo-lsquery "dragon_stones %s" mem)
1256 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1258 (if (match-string 2 dd)
1261 (setq start (match-end 0)))
1265 (defun gnugo--unclose-game ()
1266 (gnugo--forget :game-over ; all those in -close-game
1269 (let* ((root (gnugo--root-node))
1270 (cur (assq :RE root)))
1272 (assert (not (eq cur (car root))) nil
1273 ":RE at head of root node: %S"
1277 (defun gnugo-push-move (who move)
1278 (let* ((simple (booleanp who))
1279 (ucolor (gnugo-get :user-color))
1283 (gnugo-get :gnugo-color))
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))))
1293 (gnugo--q/ue "play %s %s" color move))
1295 (gnugo-merge-showboard-results))
1296 (gnugo-put :last-mover color)
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)
1305 (t (funcall (gnugo--as-cc-func)
1308 (monkey (gnugo-get :monkey))
1309 (mem (aref monkey 0))
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:
1323 ;; (such "variations" do not actually vary!) in favor of:
1329 ;; This linear search loses for multiple ‘old’ w/ "A",
1330 ;; a very unusual (but not invalid, sigh) situation.
1334 ;; Start with latest / highest likelihood for hit.
1335 ;; (See "to the right" comment, below.)
1336 from (if (gnugo--no-regrets monkey ends)
1340 if (setq bx (mod (+ bidx i) count)
1343 for m on (aref ends bx)
1344 while (< tip-move-num
1345 (gethash (setq node (car m))
1349 (when (equal pair (assq property node))
1357 (rotatef (aref ends bidx)
1359 (setq mem previous))
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))
1369 (puthash fruit (1+ (gethash tip mnum)) mnum)
1371 (aset ends bidx mem)))
1372 (setf (aref monkey 0) mem))
1374 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1376 (gnugo-close-game now resignp))
1377 (gnugo-put :waiting-start (and (not donep) now))
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))
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)
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
1407 (when (and (not (= color-key (aref new sx)))
1408 (cl-plusp (random 4)))
1409 (aset new sx (aref bg-data sb)))
1412 (create-image new 'xpm t :ascent 'center)))
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.
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
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)
1433 (when (and nocache (not (gnugo-get :waiting)))
1434 (gnugo-propertize-board-buffer))
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)
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)
1451 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1453 (funcall r-action r-ov)
1454 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1456 (rename-buffer (concat (gnugo-get :diamond)
1458 (format "%s(game over)"
1459 (if (string= move "resign")
1460 (concat move "ation ")
1462 (format "%s(%s to play)"
1463 (if move (concat move " ") "")
1467 (let ((live (cdr (assq 'live game-over)))
1468 (dead (cdr (assq 'dead game-over)))
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)
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)))
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)))
1497 (setcdr (car group) pall))))))
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)
1509 (edges (window-edges window))
1510 (right-w-edge (nth 2 edges))
1511 (avail-width (- right-w-edge (nth 0 edges)))
1513 (imagesp (symbol-plist (gnugo-f 'ispc)))
1514 (w (/ (- avail-width
1519 2 ; between board and grid
1524 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1525 `(display ,(make-string h 10))
1526 '(invisible :nogrid)))
1531 (cond (imagesp (+ (* 0.5 wmul)
1537 (gspc . ,(when imagesp
1541 ;; DWR: image width alone => OBOE!
1543 ;; NB: ‘(* wmul cw)’ is the same
1544 ;; as ‘(car (image-size ... t))’.
1545 (let ((cw (frame-char-width)))
1546 (/ (+ 1.0 (* wmul cw))
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
1558 ,(apply 'propertize " " d))
1561 (space :align-to ,(1- avail-width))))))
1562 (setplist (gnugo-f (car pair)) (cdr pair)))))
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))
1572 (while (setq cut (string-match "~[bwpmtu]" cur))
1574 (setq c (aref cur (incf cut)))
1577 `(,(intern (format "squig-%c" 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)))
1584 (cadr (time-since ws))
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
1594 `(let ,(delete-dups (copy-sequence acc))
1595 (format ,cur ,@(reverse (mapcar 'car acc))))))
1597 (let ((form (gnugo-get :mode-line-form)))
1598 (setq mode-line-process
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)
1607 (force-mode-line-update))
1609 (when (setq last (gnugo-get :last-user-bpos))
1610 (gnugo-goto-pos last))))
1612 (defun gnugo--finish-move (buf)
1613 (run-hooks 'gnugo-post-move-hook)
1614 (with-current-buffer buf
1617 ;;;---------------------------------------------------------------------------
1618 ;;; Game play actions
1620 (defun gnugo--rename-buffer-portion (&optional back)
1621 (let ((old "to play")
1622 (new "waiting for suggestion"))
1625 (let ((name (buffer-name)))
1626 (when (string-match old name)
1627 (rename-buffer (replace-match new t t name))))))
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
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)
1648 (let* ((donep (gnugo-push-move color pos-or-pass))
1649 (buf (current-buffer)))
1650 (gnugo--finish-move buf)
1651 (when (gnugo-get :abd)
1655 2 ;;; sec (frettoloso? dubioso!)
1656 nil (lambda (buf color)
1657 (with-current-buffer buf
1658 (gnugo-get-move color)))
1660 (gnugo-other color))))))))))))
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))
1671 (defun gnugo-cleanup ()
1672 (when (gnugo-board-buffer-p)
1673 (unless (zerop (buffer-size))
1674 (message "Thank you for playing GNU Go."))
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...
1680 (append (gnugo-get :all-yy)
1689 (setq gnugo-state nil)))
1691 (defun gnugo-position ()
1692 (or (get-text-property (point) 'gnugo-position)
1693 (user-error "Not a proper position point")))
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."
1702 (gnugo--rename-buffer-portion)
1703 (gnugo-get-move (gnugo-get :user-color)
1708 (defun gnugo--user-play (pos-or-pass)
1710 (let ((donep (gnugo-push-move t pos-or-pass))
1711 (buf (current-buffer)))
1712 (gnugo--finish-move buf)
1714 (with-current-buffer buf
1715 (gnugo-get-move (gnugo-get :gnugo-color))))))
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."
1723 (gnugo--user-play (gnugo-position)))
1725 (defun gnugo-mouse-move (e)
1726 "Do `gnugo-move' at mouse location."
1729 (when (memq (following-char) '(?. ?+))
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."
1737 (gnugo--user-play "PASS"))
1739 (defun gnugo-mouse-pass (e)
1740 "Do `gnugo-pass' at mouse location."
1745 (defun gnugo-resign ()
1748 (if (not (y-or-n-p "Resign? "))
1749 (message "(not resigning)")
1750 (gnugo-push-move t "resign")
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))
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))
1772 (split-string gnugo-animation-string "" t)))
1774 (ovs (save-excursion
1775 (mapcar (lambda (pos)
1776 (gnugo-goto-pos pos)
1778 (ov (make-overlay p (1+ p))))
1779 (overlay-put ov 'category (gnugo-f 'anim))
1780 (overlay-put ov 'priority most-positive-fixnum)
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))
1790 (mapc 'delete-overlay ovs)
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)
1799 (message "Computing %s ... done." command))
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."
1807 (gnugo-animate-group 'worm))
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."
1814 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
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."
1822 (gnugo-animate-group 'dragon))
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."
1829 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
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)."
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)))
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))
1859 (defun gnugo--who-is-who (wait play samep)
1860 (message "GNU Go %splays as %s, you as %s (%s)"
1861 (if samep "" "now ")
1864 "NOTE: this is a switch!")))
1866 (defsubst gnugo--nodep (x)
1867 (keywordp (caar x)))
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))))
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
1882 (aref (gnugo--tree-ends tree) 0)
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)
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)))
1908 ;; (let* ((q (format "Which game? (1-%d)" n))
1909 ;; (choice (1- (read-number q 1))))
1910 ;; (if (and (< -1 choice) (< choice n))
1912 ;; (message "(Selecting the first game)")
1914 ;; but this is what we use (for now) to accomodate
1915 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1917 (message "(Selecting the first game)"))
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))
1925 (gnugo-close-game nil game-over))
1926 (gnugo-put :last-user-bpos
1927 (gnugo-move-history 'bpos (gnugo-get :user-color)))
1929 (set-buffer-modified-p nil)
1930 (gnugo--who-is-who wait play samep)))
1932 (defun gnugo--mem-with-played-stone (pos)
1933 (let ((color (case (following-char)
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))
1941 finally return nil))))
1943 (defun gnugo--climb-towards-root (spec &optional noalt keep)
1945 (let* ((user-color (gnugo-get :user-color))
1946 (monkey (gnugo-get :monkey))
1947 (tree (gnugo-get :sgf-gametree))
1948 (ends (gnugo--tree-ends tree))
1949 (remorseful (not (gnugo--no-regrets monkey ends)))
1950 (stop (if (numberp spec)
1951 (nthcdr (if (zerop spec)
1952 (if (string= (gnugo-get :last-mover)
1959 (hmm (or (gnugo--mem-with-played-stone pos)
1960 (user-error "%s already clear" pos))))
1961 ;; todo: relax ‘gnugo--user-play’ then lift restriction
1962 (unless (eq (gnugo--prop<-color user-color)
1963 (car (gnugo--move-prop (car hmm))))
1964 (user-error "%s not occupied by %s"
1967 (when (gnugo-get :game-over)
1968 (gnugo--unclose-game))
1969 (while (not (eq stop (aref monkey 0)))
1970 (gnugo--q/ue "undo")
1971 (pop (aref monkey 0))
1972 (gnugo-put :last-mover (gnugo-current-player))
1973 (gnugo-merge-showboard-results) ; all
1974 (gnugo-refresh) ; this
1975 (redisplay)) ; eye candy
1976 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1978 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1979 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1981 (gnugo-get :center-position)))
1983 (unless (or keep remorseful)
1984 (aset ends (aref monkey 1) (aref monkey 0)))
1985 (when (and ulastp (not noalt))
1986 (gnugo-get-move (gnugo-get :gnugo-color))))))
1988 (defun gnugo-undo-one-move (&optional me-next)
1989 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1990 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1991 Prefix arg ME-NEXT means to arrange for you to play
1992 the color of the next move (and GNU Go the opposite).
1993 This is useful after loading an SGF file whose last
1994 move was done by the color you prefer to play:
1995 \\[gnugo-read-sgf-file] FILENAME RET
1996 C-u \\[gnugo-undo-one-move]
1998 See also `gnugo-undo-two-moves'."
2002 (let* ((play (gnugo-get :last-mover))
2003 (wait (gnugo-other play)))
2004 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
2005 (gnugo-put :user-color play)
2006 (gnugo-put :gnugo-color wait)))
2007 (gnugo--climb-towards-root 1 t))
2009 (defun gnugo-undo-two-moves ()
2010 "Undo a pair of moves (GNU Go's and yours).
2011 However, if you are the last mover, undo only one move.
2012 Regardless, after undoing, it is your turn to play again."
2015 (gnugo--climb-towards-root 0))
2017 (defun gnugo-oops (&optional position)
2018 "Like `gnugo-undo-two-moves', but keep the undone moves.
2019 The kept moves become a sub-gametree (variation) when play resumes.
2020 Prefix arg means, instead, undo repeatedly up to and including
2021 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2024 (gnugo--climb-towards-root (if position
2029 (defun gnugo-okay (&optional full)
2030 "Redo a pair of undone moves.
2031 Prefix arg means to redo all the undone moves."
2034 (let* ((tree (gnugo-get :sgf-gametree))
2035 (ends (gnugo--tree-ends tree))
2036 (monkey (gnugo-get :monkey)))
2037 (if (gnugo--no-regrets monkey ends)
2038 (message "Oop ack!")
2039 (let* ((as-pos (gnugo--as-pos-func))
2040 (mnum (gnugo--tree-mnum tree))
2041 (mem (aref monkey 0))
2042 (bidx (aref monkey 1))
2043 (end (aref ends bidx))
2044 (ucolor (gnugo-get :user-color))
2045 (uprop (gnugo--prop<-color ucolor)))
2046 (cl-flet ((mvno (node) (gethash node mnum)))
2050 (+ 2 (mvno (car mem))))
2051 with (node move todo)
2055 move (gnugo--move-prop node))
2056 (when (and move (>= ok (mvno node)))
2057 (let ((userp (eq uprop (car move))))
2059 (funcall as-pos (cdr move)))
2061 until (eq mem (cdr ls))
2064 for (userp pos) in todo
2066 (gnugo-push-move userp pos)
2070 (defun gnugo-display-final-score (&optional comment)
2071 "Display final score and other info in another buffer (when game over).
2072 If the game is still ongoing, Emacs asks if you wish to stop play (by
2073 making sure two \"pass\" moves are played consecutively, if necessary).
2074 Also, add the `:RE' SGF property to the root node of the game tree.
2075 Prefix arg COMMENT means to also attach the text (slightly compacted)
2076 to the last move, as a comment."
2078 (let ((game-over (gnugo-get :game-over)))
2079 (unless (or game-over
2080 (and (not (gnugo-get :waiting))
2081 (y-or-n-p "Game still in play. Stop play now? ")))
2082 (user-error "Sorry, game still in play"))
2086 (message "Playing PASS for %s ..."
2087 (gnugo-get (if userp :user-color :gnugo-color)))
2089 (gnugo-push-move userp "PASS")))
2094 (let ((b= " Black = ")
2096 (res (when (string= "resign" (gnugo-move-history 'car))
2097 (gnugo-get :last-mover)))
2101 (format "%s wins.\n"
2102 (substring (if (= ?b (aref res 0)) w= b=)
2104 "The game is over.\n"
2105 (format "Resignation by %s.\n" res))
2106 result (concat (upcase (substring (gnugo-other res) 0 1))
2108 (message "Computing final score ...")
2109 (let* ((g-over (gnugo-get :game-over))
2110 (live (cdr (assq 'live g-over)))
2111 (dead (cdr (assq 'dead g-over)))
2112 (seed (gnugo-get :scoring-seed))
2113 (terr-q (format "final_status_list %%s_territory %d" seed))
2116 (b-terr (gnugo--count-query terr-q "black"))
2117 (w-terr (gnugo--count-query terr-q "white"))
2118 (b-capt (string-to-number (gnugo-get :black-captures)))
2119 (w-capt (string-to-number (gnugo-get :white-captures)))
2120 (komi (gnugo--root-prop :KM)))
2121 (setq blurb (list "The game is over. Final score:\n")
2122 result (gnugo-query "final_score %d" seed))
2123 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2124 (dolist (group live)
2125 (incf (if (gnugo--blackp (caar group))
2128 (length (cdr group))))
2129 (dolist (group dead)
2130 (incf (if (gnugo--blackp (caar group))
2133 (length (cdr group))))
2134 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2135 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2136 w-terr terr komi 'komi (+ w-terr komi))
2139 (dolist (group dead)
2140 (incf (if (gnugo--blackp (caar group))
2143 (* 2 (length (cdr group)))))
2144 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2149 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2153 (+ w-terr w-capt komi))
2155 (push (if (string= "0" result)
2156 "The game is a draw.\n"
2157 (format "%s wins by %s.\n"
2158 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2159 (substring result 2)))
2161 (message "Computing final score ... done")))
2163 (let ((beg (gnugo-get :game-start-time))
2164 (end (gnugo-get :game-end-time)))
2168 ((yep (pretty moment)
2169 (push (format-time-string
2170 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2173 (yep "Game start" beg)
2175 (setq blurb (apply 'concat (nreverse blurb)))
2176 (gnugo--set-root-prop :RE result)
2178 (let ((node (car (aref (gnugo-get :monkey) 0))))
2180 (delq (assq :C node) node)
2181 (with-temp-buffer ; lame
2183 (when (search-backward "\n\nGame start:" nil t)
2184 (delete-region (point) (point-max)))
2185 (cl-flet ((rep (old new)
2186 (goto-char (point-min))
2187 (while (search-forward old nil t)
2188 (replace-match new))))
2189 (rep "The game is over. " "")
2190 (rep "territory" "T")
2191 (rep "captures" "C")
2193 `((:C . ,(buffer-string)))))))
2194 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2198 (defun gnugo-quit ()
2199 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2200 If the game is not over, ask for confirmation first."
2202 (if (or (gnugo-get :game-over)
2203 (y-or-n-p "Quit? "))
2205 (message "(not quitting)")))
2207 (defun gnugo-leave-me-alone ()
2208 "Kill the current buffer unconditionally."
2212 (defun gnugo-fancy-undo (count)
2213 "Rewind the game tree in various ways.
2214 Prefix arg COUNT means to undo that many moves.
2215 Otherwise, undo repeatedly up to and including the move
2216 which placed the stone at point."
2218 (gnugo--climb-towards-root
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 (defsubst gnugo--node-with-played-stone (pos)
2230 (car (gnugo--mem-with-played-stone pos)))
2232 (defun gnugo-describe-position ()
2233 "Display the board position under cursor in the echo area.
2234 If there a stone at that position, also display its move number."
2236 (let* ((pos (gnugo-position)) ; do first (can throw)
2237 (node (gnugo--node-with-played-stone pos)))
2241 (let* ((tree (gnugo-get :sgf-gametree))
2242 (mnum (gnugo--tree-mnum tree))
2243 (move-num (gethash node mnum)))
2244 (format " (move %d)" move-num)))
2247 (defun gnugo-switch-to-another ()
2248 "Switch to another GNU Go game buffer (if any)."
2250 (loop for buf in (cdr (buffer-list))
2251 if (gnugo-board-buffer-p buf)
2254 (switch-to-buffer buf))
2255 finally do (message "(only one)")))
2257 (defun gnugo-comment (node comment)
2258 "Add to NODE a COMMENT (string) property.
2259 Called interactively, NODE is the one corresponding to the
2260 stone at point, and any previous comment is inserted as the
2261 initial-input (see `read-string').
2263 If COMMENT is nil or the empty string, remove the property entirely."
2265 (let* ((pos (gnugo-position))
2266 (node (or (gnugo--node-with-played-stone pos)
2267 (user-error "No stone at %s" pos))))
2269 (read-string (format "Comment for %s: "
2270 (gnugo-describe-position))
2271 (cdr (assq :C node))))))
2272 (setq node (delq (assq :C node) node))
2273 (unless (zerop (length comment))
2274 (gnugo--decorate node `((:C . ,comment)))))
2276 (defun gnugo-toggle-abdication ()
2277 "Toggle abdication, i.e., letting GNU Go play for you.
2278 When enabled, the mode line includes \"Abd\".
2279 Enabling signals error if the game is over.
2280 Disabling signals error if the color \"to play\" is the user color.
2281 This is to ensure that the user is the next to play after disabling."
2283 (let ((last-mover (gnugo-get :last-mover))
2284 (abd (gnugo-get :abd))
2288 (let ((gcolor (gnugo-get :gnugo-color)))
2289 (when (string= last-mover gcolor)
2290 (gnugo--ERR-wait gcolor "Sorry, too soon"))
2293 (gnugo--forget :abd)
2294 (unless (gnugo-get :waiting)
2295 (gnugo-get-move gcolor)))
2297 (gnugo--gate-game-over t)
2299 (gnugo-get-move (gnugo-other last-mover)))
2300 (message "Abdication %sabled%s"
2301 (if (gnugo-get :abd)
2306 ;;;---------------------------------------------------------------------------
2307 ;;; Command properties and gnugo-command
2309 ;; GTP commands entered by the user are never issued directly to GNU Go;
2310 ;; instead, their behavior and output are controlled by the property
2311 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2312 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2314 ;; :full -- completely interpret the command string; the value is a
2315 ;; func that takes the list of words derived from splitting the
2316 ;; command string (minus the command) and handles everything.
2318 ;; :output -- either a keyword specifying the preferred output method:
2319 ;; :message -- show output in minibuffer
2320 ;; :discard -- sometimes you just don't care;
2321 ;; or a function that takes one arg, the output string, and
2322 ;; handles it completely. default is to switch to buffer
2323 ;; "*gnugo command output*" if the output has a newline,
2324 ;; otherwise use `message'.
2326 ;; :post-thunk -- run after output processing (at the very end).
2328 (defun gnugo-command (command)
2329 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2330 Output and Emacs behavior depend on which command is given (some
2331 commands are handled completely by Emacs w/o using the subprocess;
2332 some commands have their output displayed in specially prepared
2333 buffers or in the echo area; some commands are instrumented to do
2334 gnugo.el-specific housekeeping).
2336 For example, for the command \"help\", Emacs visits the
2337 GTP command reference info page.
2339 NOTE: At this time, GTP command handling specification is still
2340 incomplete. Thus, some commands WILL confuse gnugo.el."
2341 (interactive "sCommand: ")
2342 (if (string= "" command)
2343 (message "(no command given)")
2344 (let* ((split (split-string command))
2345 (cmd (intern (car split)))
2346 (spec (get cmd :gnugo-gtp-command-spec))
2347 (full (plist-get spec :full)))
2349 (funcall full (cdr split))
2350 (message "Doing %s ..." command)
2351 (let* ((ans (gnugo--q command))
2352 (where (plist-get spec :output)))
2353 (if (string-match "unknown.command" ans)
2355 (cond ((functionp where) (funcall where ans))
2356 ((eq :discard where) (message ""))
2357 ((or (eq :message where)
2358 (not (string-match "\n" ans)))
2360 (t (switch-to-buffer "*gnugo command output*")
2363 (message "Doing %s ... done." command)))
2364 (let ((thunk (plist-get spec :post-thunk)))
2365 (when thunk (funcall thunk)))))))))
2367 ;;;---------------------------------------------------------------------------
2368 ;;; Major mode for interacting with a GNUGO subprocess
2370 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2371 "Major mode for playing GNU Go.
2372 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2373 In this mode, keys do not self insert.
2375 \\{gnugo-board-mode-map}"
2376 (buffer-disable-undo) ; todo: undo undo undoing
2377 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2379 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2380 (set (make-local-variable 'gnugo-state)
2381 (gnugo--mkht :size (1- 42)))
2382 (gnugo-put :highlight-last-move-spec
2383 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2384 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2385 (let ((ov (make-overlay 1 1)))
2386 (overlay-put ov 'display ")")
2388 (gnugo-put :mul '(1 . 1))
2389 (add-to-invisibility-spec :nogrid))
2391 ;;;---------------------------------------------------------------------------
2395 (defun gnugo (&optional new-game)
2396 "Run gnugo in a buffer, or resume a game in progress.
2397 If there is already a game in progress you may resume it instead
2398 of starting a new one. Prefix arg means skip the game-in-progress
2399 check and start a new game straight away.
2401 Before starting, Emacs queries you for additional command-line
2402 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2404 Note that specifying \"--infile FILENAME\" (or, \"-l FILENAME\")
2405 silently clobbers certain other options, such as \"--color\".
2406 For details, see info node `(gnugo) Invoking GNU Go'.
2408 \\<gnugo-board-mode-map>
2409 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2410 See `gnugo-board-mode' for a full list of commands."
2412 (let* ((all (let (acc)
2413 (dolist (buf (buffer-list))
2414 (when (gnugo-board-buffer-p buf)
2415 (push (cons (buffer-name buf) buf) acc)))
2418 (if (and (not new-game)
2420 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2421 (if (= 1 n) "" "s"))))
2426 (let ((sel (completing-read "Which one? " all nil t)))
2427 (if (string= "" sel)
2429 (assoc sel all))))))
2431 (unless (executable-find gnugo-program)
2432 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2433 ;; set up a new board
2434 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2436 (let* ((filename nil)
2437 (user-color "black")
2439 with ls = (split-string
2440 ;; todo: grok ‘gnugo --help’; completion
2443 (car gnugo-option-history)
2444 'gnugo-option-history))
2447 (let ((arg (pop ls)))
2451 (warn "%s %s ignored" opt fn)
2452 (setq filename fn))))
2454 ((string= "--color" arg)
2457 ;; Unfortunately, GTP does not provide
2458 ;; a way to query the user color, so
2459 ;; we must resort to this weirdness.
2463 ((string= "--infile" arg)
2464 (ex "--infile" (pop ls)))
2465 ((string-match "^-l" arg)
2466 (ex "-l" (if (< 2 (length arg))
2469 (t (push arg ok)))))
2470 finally return (nreverse ok)))
2471 (proc (apply 'start-process "gnugo"
2474 "--mode" "gtp" "--quiet"
2476 root board-size handicap komi)
2477 (gnugo-put :user-color user-color)
2478 (gnugo-put :proc proc)
2479 (set-process-sentinel proc 'gnugo-sentinel)
2480 ;; Emacs is too protective sometimes, blech.
2481 (set-process-query-on-exit-flag proc nil)
2482 (gnugo-put :diamond (substring (process-name proc) 5))
2483 (gnugo-put :gnugo-color (gnugo-other user-color))
2485 (gnugo-read-sgf-file (expand-file-name filename))
2489 root (loop ; hmm, available elsewhere?
2491 collect (let* ((k (pop plist))
2495 (setq root (gnugo--root-node
2496 (gnugo--plant-and-climb
2497 (gnugo/sgf-create "(;FF[4]GM[1])" t)))
2498 komi (gnugo--nquery "get_komi")
2499 handicap (gnugo--nquery "get_handicap")
2500 board-size (gnugo--nquery "query_boardsize")))
2502 :DT (format-time-string "%Y-%m-%d")
2503 :RU (if (member "--chinese-rules" args)
2506 :AP (cons "gnugo.el" gnugo-version)
2508 (let ((ub (gnugo--blackp user-color)))
2509 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2510 (if ub :PB :PW) (user-full-name)))
2511 (unless (zerop handicap)
2513 :AB (mapcar (gnugo--as-cc-func)
2514 (gnugo-lsquery "fixed_handicap %d"
2516 (gnugo-put :waiting-start (current-time))
2518 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2519 (gnugo-get :center-position)))
2521 (gnugo-put :game-start-time (current-time))
2522 (let ((g (gnugo-get :gnugo-color))
2523 (n (or (gnugo--root-prop :HA) 0))
2524 (u (gnugo-get :user-color)))
2525 (unless (gnugo-get :last-mover)
2526 (gnugo-put :last-mover
2527 (if (or (and (gnugo--blackp u) (< 1 n))
2528 (and (gnugo--blackp g) (< n 2)))
2531 (run-hooks 'gnugo-start-game-hook)
2532 (when (and (not (gnugo-get :game-over))
2533 (string= g (gnugo-current-player)))
2535 (gnugo-get-move g))))))
2537 ;;;---------------------------------------------------------------------------
2538 ;;; Load-time actions
2540 (unless gnugo-frolic-mode-map
2541 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2542 (suppress-keymap gnugo-frolic-mode-map)
2543 (mapc (lambda (pair)
2544 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2545 '(("q" . gnugo-frolic-quit)
2546 ("Q" . gnugo-frolic-quit)
2547 ("\C-q" . gnugo-frolic-quit)
2548 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2549 ("\C-b" . gnugo-frolic-backward-branch)
2550 ("\C-f" . gnugo-frolic-forward-branch)
2551 ("\C-p" . gnugo-frolic-previous-move)
2552 ("\C-n" . gnugo-frolic-next-move)
2553 ("j" . gnugo-frolic-exchange-left)
2554 ("J" . gnugo-frolic-rotate-left)
2555 ("k" . gnugo-frolic-exchange-right)
2556 ("K" . gnugo-frolic-rotate-right)
2557 ("\C-m" . gnugo-frolic-set-as-main-line)
2558 ("\C-\M-p" . gnugo-frolic-prune-branch)
2559 ("o" . gnugo-frolic-return-to-origin))))
2561 (unless gnugo-board-mode-map
2562 (setq gnugo-board-mode-map (make-sparse-keymap))
2563 (suppress-keymap gnugo-board-mode-map)
2564 (mapc (lambda (pair)
2565 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2566 '(("?" . describe-mode)
2567 ("S" . gnugo-request-suggestion)
2568 ("\C-m" . gnugo-move)
2571 ("R" . gnugo-resign)
2573 ("Q" . gnugo-leave-me-alone)
2574 ("U" . gnugo-fancy-undo)
2575 ("\M-u" . gnugo-undo-one-move)
2576 ("u" . gnugo-undo-two-moves)
2577 ("\C-?" . gnugo-undo-two-moves)
2580 ("\C-l" . gnugo-refresh)
2581 ("\M-_" . gnugo-boss-is-near)
2582 ("_" . gnugo-boss-is-near)
2583 ("h" . gnugo-move-history)
2584 ("L" . gnugo-frolic-in-the-leaves)
2585 ("\C-c\C-l" . gnugo-frolic-in-the-leaves)
2586 ("i" . gnugo-toggle-image-display-command)
2587 ("w" . gnugo-worm-stones)
2588 ("W" . gnugo-worm-data)
2589 ("d" . gnugo-dragon-stones)
2590 ("D" . gnugo-dragon-data)
2591 ("g" . gnugo-toggle-grid)
2592 ("!" . gnugo-estimate-score)
2593 (":" . gnugo-command)
2594 (";" . gnugo-command)
2595 ("=" . gnugo-describe-position)
2596 ("s" . gnugo-write-sgf-file)
2597 ("\C-x\C-s" . gnugo-write-sgf-file)
2598 ("\C-x\C-w" . gnugo-write-sgf-file)
2599 ("l" . gnugo-read-sgf-file)
2600 ("F" . gnugo-display-final-score)
2601 ("A" . gnugo-switch-to-another)
2602 ("C" . gnugo-comment)
2603 ("\C-c\C-a" . gnugo-toggle-abdication)
2605 ([(down-mouse-1)] . gnugo-mouse-move)
2606 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2607 ([(down-mouse-3)] . gnugo-mouse-pass)
2608 ;; delving into the curiosities
2609 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2611 (unless (get 'help :gnugo-gtp-command-spec)
2613 ((sget (x) (get x :gnugo-gtp-command-spec))
2614 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2615 (plist-put (sget cmd) prop val)))
2616 (validpos (s &optional go)
2617 (let ((pos (upcase s)))
2618 (loop with size = (gnugo-get :SZ)
2619 for c across (funcall (gnugo--as-cc-func)
2621 do (let ((norm (- c ?a)))
2622 (unless (and (< -1 norm)
2624 (user-error "Invalid position: %s"
2627 (gnugo-goto-pos pos))
2629 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2632 (jam cmd (car ls) (cadr ls))
2633 (setq ls (cddr ls)))))))
2634 (cl-macrolet ((deffull (who &body body)
2635 (declare (indent 1))
2636 `(defgtp ',who :full (lambda (sel)
2640 (info "(gnugo)GTP command reference")
2641 (when sel (setq sel (intern (car sel))))
2642 (let (buffer-read-only pad cur spec output found)
2644 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2645 (goto-char (point-min))
2647 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2650 (setq pad (make-string (- (match-beginning 1)
2651 (match-beginning 0))
2655 (get (setq cur (intern (match-string 1)))
2656 :gnugo-gtp-command-spec))
2658 (note "handles this command completely"))
2659 (when (setq output (plist-get spec :output))
2660 (if (functionp output)
2661 (note "handles the output specially")
2663 (:discard (note "discards the output"))
2664 (:message (note "displays the output in the echo area")))))
2666 (setq found (match-beginning 0))))))
2667 (cond (found (goto-char found))
2669 (t (message "(no such command: %s)" sel)))))
2671 (deffull final_score
2672 ;; Explicit ignorance avoids byte-compiler warning.
2674 (gnugo-display-final-score))
2680 :post-thunk (lambda ()
2681 (gnugo--unclose-game)
2682 (gnugo--forget :last-mover)
2684 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2688 (gnugo-read-sgf-file (car sel)))
2690 (deffull (undo gg-undo)
2691 (gnugo--climb-towards-root
2694 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2695 (t (validpos (car sel) t)))))))))
2700 ;;;---------------------------------------------------------------------------
2701 ;;; The remainder of this file defines a simplified SGF-handling library.
2702 ;;; When/if it should start to attain generality, it should be split off into
2703 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2704 ;;; "gnugo/" prefix.
2706 (defconst gnugo/sgf-*r4-properties*
2707 '((AB "Add Black" setup list stone)
2708 (AE "Add Empty" game list point)
2709 (AN "Annotation" game simpletext)
2710 (AP "Application" root (simpletext . simpletext))
2711 (AR "Arrow" - list (point . point))
2712 (AS "Who adds stones" - simpletext) ; (LOA)
2713 (AW "Add White" setup list stone)
2714 (B "Black" move move)
2715 (BL "Black time left" move real)
2716 (BM "Bad move" move double)
2717 (BR "Black rank" game simpletext)
2718 (BT "Black team" game simpletext)
2719 (C "Comment" - text)
2720 (CA "Charset" root simpletext)
2721 (CP "Copyright" game simpletext)
2722 (CR "Circle" - list point)
2723 (DD "Dim points" - elist point) ; (inherit)
2724 (DM "Even position" - double)
2725 (DO "Doubtful" move none)
2726 (DT "Date" game simpletext)
2727 (EV "Event" game simpletext)
2728 (FF "Fileformat" root [number (1 . 4)])
2729 (FG "Figure" - (or none (number . simpletext)))
2730 (GB "Good for Black" - double)
2731 (GC "Game comment" game text)
2732 (GM "Game" root [number (1 . 20)])
2733 (GN "Game name" game simpletext)
2734 (GW "Good for White" - double)
2735 (HA "Handicap" game number) ; (Go)
2736 (HO "Hotspot" - double)
2737 (IP "Initial pos." game simpletext) ; (LOA)
2738 (IT "Interesting" move none)
2739 (IY "Invert Y-axis" game simpletext) ; (LOA)
2740 (KM "Komi" game real) ; (Go)
2742 (LB "Label" - list (point . simpletext))
2743 (LN "Line" - list (point . point))
2744 (MA "Mark" - list point)
2745 (MN "set move number" move number)
2746 (N "Nodename" - simpletext)
2747 (OB "OtStones Black" move number)
2748 (ON "Opening" game text)
2749 (OT "Overtime" game simpletext)
2750 (OW "OtStones White" move number)
2751 (PB "Player Black" game simpletext)
2752 (PC "Place" game simpletext)
2753 (PL "Player to play" setup color)
2754 (PM "Print move mode" - number) ; (inherit)
2755 (PW "Player White" game simpletext)
2756 (RE "Result" game simpletext)
2757 (RO "Round" game simpletext)
2758 (RU "Rules" game simpletext)
2759 (SE "Markup" - point) ; (LOA)
2760 (SL "Selected" - list point)
2761 (SO "Source" game simpletext)
2762 (SQ "Square" - list point)
2763 (ST "Style" root [number (0 . 3)])
2764 (SU "Setup type" game simpletext) ; (LOA)
2765 (SZ "Size" root (or number (number . number)))
2766 (TB "Territory Black" - elist point) ; (Go)
2767 (TE "Tesuji" move double)
2768 (TM "Timelimit" game real)
2769 (TR "Triangle" - list point)
2770 (TW "Territory White" - elist point) ; (Go)
2771 (UC "Unclear pos" - double)
2772 (US "User" game simpletext)
2774 (VW "View" - elist point) ; (inherit)
2775 (W "White" move move)
2776 (WL "White time left" move real)
2777 (WR "White rank" game simpletext)
2778 (WT "White team" game simpletext)
2779 (LT "Lose on time" setup simpletext))
2780 ;; r4-specific notes
2781 ;; - changed: DT FG LB RE RU SZ
2782 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2783 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2785 (defun gnugo/sgf-create (file-or-data &optional data-p)
2786 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2787 FILE-OR-DATA is a file name or SGF[4] data.
2788 Optional arg DATA-P non-nil means FILE-OR-DATA is
2789 a string containing SGF[4] data.
2790 A collection is a list of gametrees, each a vector of four elements:
2792 ENDS -- a vector of node lists, with shared tails
2793 (last element of all the lists is the root node)
2795 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2796 have a move number of the previous \"move\" node (or zero)
2798 ROOT -- the root node"
2799 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2800 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2801 (put 'gnugo/sgf-*r4-properties* :keywords
2802 (mapcar (lambda (full)
2804 (intern (format ":%s" (car full)))))
2805 gnugo/sgf-*r4-properties*))))
2806 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2807 (put 'gnugo/sgf-*r4-properties* :specs
2808 (mapcar (lambda (full)
2809 (cons (car full) (cdddr full)))
2810 gnugo/sgf-*r4-properties*))))
2813 ((sw () (skip-chars-forward " \t\n"))
2814 (x (end preserve-whitespace)
2817 (:end (lambda (char) (= ?\] char)))
2818 (:mid (lambda (char) (= ?\: char)))
2819 (t (lambda (char) (or (= ?\: char)
2822 (while (not (funcall endp (setq c (following-char))))
2828 ((unless preserve-whitespace
2829 (looking-at "\\s-+"))
2830 (delete-region (point) (match-end 0))
2832 (t (forward-char 1))))
2833 (buffer-substring-no-properties beg (point))))
2834 (one (type end) (let ((s (progn
2836 (x end (eq 'text type)))))
2839 ;; blech, begone bu"tt"-ugly blatherings
2840 ;; (but bide brobdingnagian boards)...
2841 (if (and (string= "tt" s)
2846 ((simpletext color) s)
2847 ((number real double) (string-to-number s))
2850 (t (error "Unhandled type: %S" type)))))
2851 (val (spec) (cond ((symbolp spec)
2854 ;; todo: check range here.
2855 (one (aref spec 0) :end))
2856 ((eq 'or (car spec))
2857 (let ((v (one (cadr spec) t)))
2858 (if (= ?\] (following-char))
2861 ;; todo: this assumes `spec' has the form
2862 ;; (or foo (foo . bar))
2863 ;; i.e., foo is not rescanned. e.g., `SZ'.
2864 ;; probably this assumption is consistent
2865 ;; w/ the SGF authors' desire to make the
2866 ;; parsing easy, but you never know...
2867 (cons v (one (cdaddr spec) :end)))))
2868 (t (cons (one (car spec) :mid)
2869 (one (cdr spec) :end)))))
2870 (short (who) (when (eobp)
2871 (error "Unexpected EOF while reading %s" who)))
2872 (atvalp () (= ?\[ (following-char)))
2873 (PROP () (let (name spec ltype)
2874 (sw) (short 'property)
2875 (when (looking-at "[A-Z]")
2876 (setq name (read (current-buffer))
2877 spec (cdr (assq name specs)))
2880 (cdr (assq name keywords))
2881 (prog1 (if (= 1 (length spec))
2883 (unless (memq (setq ltype (car spec))
2885 (error "Bad spec: %S" spec))
2886 (if (and (eq 'elist ltype) (sw)
2889 (let ((type (cadr spec))
2891 (while (and (sw) (atvalp)
2892 (setq mo (val type)))
2897 (forward-char 1))))))
2898 (morep () (and (sw) (not (eobp))))
2899 (seek (c) (and (morep) (= c (following-char))))
2900 (seek-into (c) (when (seek c)
2903 (NODE () (when (seek-into ?\;)
2905 while (setq prop (PROP))
2907 (when (eq :SZ (car prop))
2908 (setq SZ (cdr prop)))
2917 (puthash node (+ (if (gnugo--move-prop node)
2920 (gethash prev mnum 0))
2925 (if (not (seek ?\())
2929 (loop while (seek ?\()
2930 append (TREE ls mnum)))
2934 (insert-file-contents file-or-data)
2935 (insert file-or-data)
2936 (goto-char (point-min)))
2938 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2939 (ends (TREE nil mnum))
2940 (root (car (last (car ends)))))
2941 (vector (apply 'vector ends)
2945 (defun gnugo/sgf-write-file (collection filename)
2946 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2947 (me (cons "gnugo.el" gnugo-version))
2948 (specs (mapcar (lambda (full)
2949 (cons (intern (format ":%s" (car full)))
2951 gnugo/sgf-*r4-properties*))
2954 ((esc (composed fmt arg)
2955 (mapconcat (lambda (c)
2957 ;; ‘?\[’ is not strictly required
2958 ;; but neither is it forbidden.
2959 ((?\[ ?\] ?\\) (format "\\%c" c))
2960 (?: (concat (if composed "\\" "") ":"))
2962 (string-to-list (format fmt arg))
2964 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2965 (>>two (v) (insert "["
2966 (esc t "%s" (car v))
2968 (esc t "%s" (cdr v))
2970 (>>nl () (cond ((memq name aft-newline-appreciated)
2972 ((< 60 (current-column))
2980 (insert (substring (symbol-name name) 1))
2983 (setq spec (cdr (assq name specs)))
2987 (let ((>> (if (consp (cadr spec))
2990 (dolist (little-v v)
2992 (funcall >> little-v)
2999 (loop initially (insert ";")
3003 (unless (zerop (current-column))
3007 (funcall (if (gnugo--nodep x)
3013 (dolist (tree collection)
3014 ;; take responsibility for our actions
3015 (gnugo--set-root-prop :AP me tree)
3017 (let ((ht (gnugo--mkht))
3018 (leaves (append (gnugo--tree-ends tree) nil)))
3022 with rh ; rectified history
3023 with bp ; branch point
3025 until (setq bp (gethash node ht))
3027 (push node rh) ; good for now: ½τ
3031 ;; first run: main line
3033 ;; subsequent runs: grafts (value discarded)
3035 ;; Maintain order of ‘leaves’.
3036 (let ((was (cdr bp)))
3037 (if (gnugo--nodep (car was))
3041 (setq tree (hang (pop leaves)))
3042 (mapc #'hang leaves)
3045 (write-file filename)))))
3047 ;;; gnugo.el ends here