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). Other keybindings are described in
43 ;; the `gnugo-board-mode' documentation, which you may view with the command
44 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
45 ;; the last move and who is currently to play. Capture counts and other info
46 ;; are shown on the mode line immediately following the major mode name.
48 ;; While GNU Go is pondering its next move, certain commands that rely on its
49 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
50 ;; is normal. When it is your turn again you may retry the command. In the
51 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
52 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
54 ;; If GNU Go should crash during a game the mode line will show "no process".
55 ;; Please report the event to the GNU Go maintainers so that they can improve
59 ;; Meta-Playing (aka Customizing)
60 ;; ------------------------------
62 ;; Customization is presently limited to
63 ;; vars: `gnugo-program'
64 ;; `gnugo-animation-string'
66 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
68 ;; normal hooks: `gnugo-board-mode-hook'
69 ;; `gnugo-post-move-hook'
70 ;; and the keymap: `gnugo-board-mode-map'
72 ;; The variable `gnugo-xpms' is a special case. To set it you need to load
73 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
78 (eval-when-compile (require 'cl)) ; use the source luke!
79 (require 'ascii-art-to-unicode) ; for `aa2u'
80 (require 'time-date) ; for `time-subtract'
82 ;;;---------------------------------------------------------------------------
85 (defconst gnugo-version "2.3.1"
86 "Version of gnugo.el currently loaded.
87 This follows a MAJOR.MINOR.PATCH scheme.")
89 ;;;---------------------------------------------------------------------------
90 ;;; Variables for the uninquisitive programmer
92 (defvar gnugo-program "gnugo"
93 "Command to start an external program that speaks GTP, such as \"gnugo\".
94 The value may also be in the form \"PROGRAM OPTIONS...\" in which case the
95 the command `gnugo' will prefix OPTIONS in its default offering when it
96 queries you for additional options. It is an error for \"--mode\" to appear
99 For more information on GTP and GNU Go, feel free to visit:
100 http://www.gnu.org/software/gnugo")
102 (defvar gnugo-board-mode-map nil
103 "Keymap for GNUGO Board mode.")
105 (defvar gnugo-frolic-mode-map nil
106 "Keymap for GNUGO Frolic mode.")
108 (defvar gnugo-board-mode-hook nil
109 "Hook run when entering GNUGO Board mode.")
111 (defvar gnugo-inhibit-refresh nil
112 "Used in `gnugo-post-move-hook'.")
114 (defvar gnugo-post-move-hook nil
115 "Normal hook run after a move and before the board is refreshed.
116 Hook functions can prevent the call to `gnugo-refresh' by evaluating:
117 (setq gnugo-inhibit-refresh t)
118 Initially, when `run-hooks' is called, the current buffer is the GNUGO
119 Board buffer of the game. Hook functions that switch buffers must take
120 care not to call (directly or indirectly through some other function)
121 `gnugo-put' or `gnugo-get' after the switch.")
123 (defvar gnugo-animation-string
124 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
125 (concat jam jam jam jam jam
126 ;; "SECRET MESSAGE HERE"
127 blink blink blink blink blink blink blink blink
128 ;; Playing go is like fighting ignorance: when you think you have
129 ;; surrounded something by knowing it very well it often turns
130 ;; out that in the time you spent deepening this understanding,
131 ;; other areas of ignorance have surrounded you.
132 spin spin spin spin spin spin spin spin spin
133 ;; Playing go is not like fighting ignorance: what one person
134 ;; knows many people may come to know; knowledge does not build
135 ;; solely move by move. Wisdom, on the other hand...
137 "String whose individual characters are used for animation.
138 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
139 render the stones in their respective result groups as the first character
140 in the string, then the next, and so on.")
142 (defvar gnugo-mode-line "~b ~w :~m :~u"
143 "A `mode-line-format'-compliant value for GNUGO Board mode.
144 If a single string, the following special escape sequences are
145 replaced with their associated information:
146 ~b,~w black,white captures (a number)
147 ~p current player (black or white)
149 ~t time waiting for the current move
150 ~u time taken for the Ultimate (most recent) move
151 The times are in seconds, or \"-\" if that information is not available.
152 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
154 (defvar gnugo-X-face 'font-lock-string-face
155 "Name of face to use for X (black) stones.")
157 (defvar gnugo-O-face 'font-lock-builtin-face
158 "Name of face to use for O (white) stones.")
160 (defvar gnugo-grid-face 'default
161 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
163 ;;;---------------------------------------------------------------------------
164 ;;; Variables for the inquisitive programmer
166 (defconst gnugo-font-lock-keywords
167 '(("X" . gnugo-X-face)
168 ("O" . gnugo-O-face))
169 "Font lock keywords for `gnugo-board-mode'.")
171 (defvar gnugo-option-history nil)
173 (defvar gnugo-state nil) ; hint: C-c C-p
176 (defvar gnugo-xpms nil))
178 (defvar gnugo-frolic-parent-buffer nil)
179 (defvar gnugo-frolic-origin nil)
181 ;;;---------------------------------------------------------------------------
182 ;;; Support functions
184 (defsubst gnugo--mkht (&rest etc)
185 (apply 'make-hash-table :test 'eq etc))
187 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
188 (compare-strings s1 beg1 nil s2 beg2 nil))
190 (defun gnugo-put (key value)
191 "Associate move/game/board-specific property KEY with VALUE.
193 There are many properties, each named by a keyword, that record and control
194 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
195 of properties, stored in the hash table `gnugo-state'. Here we document
196 some of the more stable properties. You may wish to use them as part of
197 a `gnugo-post-move-hook' function, for example. Be careful to preserve
198 the current buffer as `gnugo-state' is made into a buffer-local variable.
199 NOTE: In the following, \"see foo\" actually means \"see foo source or
200 you may never really understand to any degree of personal satisfaction\".
202 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
204 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
206 :game-over -- nil until game over at which time its value is set to
207 the alist `((live GROUP ...) (dead GROUP ...))'
209 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
210 a simple list of one or more gametrees, updated in
211 conjunction w/ :sgf-gametree and :monkey
213 :sgf-gametree -- one of the gametrees in :sgf-collection
215 :monkey -- vector of two elements:
216 MEM, a pointer to one of the branches in the gametree;
217 BIDX, the index of the \"current branch\"
219 :gnugo-color -- either \"black\" or \"white\"
223 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
226 :black-captures -- these are strings since gnugo.el doesn't do anything
227 :white-captures w/ the information besides display it in the mode line;
228 gory details in functions `gnugo-propertize-board-buffer'
229 and `gnugo-merge-showboard-results' (almost more effort
230 than they are worth!)
232 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
233 `gnugo-toggle-image-display' and `gnugo-refresh',
234 as well as gnugo-xpms.el (available elsewhere)
236 :all-yy -- list of 46 keywords used as the `category' text property
237 (so that their plists, typically w/ property `display' or
238 `do-not-display') are consulted by the Emacs display engine;
239 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
240 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
242 :lparen-ov -- overlays shuffled about to indicate the last move; only
243 :rparen-ov one is used when displaying using images
245 :last-user-bpos -- board position; keep the hapless human happy
247 As things stabilize probably more info will be added to this docstring."
249 (puthash key value gnugo-state))
251 (defun gnugo-get (key)
252 "Return the move/game/board-specific value for KEY.
254 (gethash key gnugo-state))
256 (defsubst gnugo--tree-mnum (tree)
259 (defsubst gnugo--tree-ends (tree)
262 (defsubst gnugo--set-tree-ends (tree ls)
263 (aset tree 0 (apply 'vector ls))
264 (gnugo--tree-ends tree))
266 (defun gnugo--root-node (&optional tree)
267 (aref (or tree (gnugo-get :sgf-gametree))
270 (defun gnugo-describe-internal-properties ()
271 "Pretty-print `gnugo-state' properties in another buffer.
272 Handle the big, slow-to-render, and/or uninteresting ones specially."
274 (let ((buf (current-buffer))
275 (d (gnugo-get :diamond))
277 (loop for key being the hash-keys of gnugo-state
278 using (hash-values val)
282 (format "hash: %X (%d images)"
288 (list (hash-table-count
289 (gnugo--tree-mnum val))
290 (gnugo--root-node val)
291 (gnugo--tree-ends val)))
293 (let ((mem (aref val 0)))
298 (switch-to-buffer (get-buffer-create
299 (format "%s*GNUGO Board Properties*"
300 (gnugo-get :diamond))))
303 (setq truncate-lines t)
307 (goto-char (point-min))
308 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
312 (while (re-search-forward rx (point-max) t)
313 (let ((pos (get-text-property (string-to-number (match-string 1))
314 'gnugo-position buf)))
315 (delete-region (+ 2 (match-beginning 0)) (point))
316 (insert (format " %S" pos))))))
317 (message "%d properties" (length acc))))
319 (defun gnugo-board-buffer-p (&optional buffer)
320 "Return non-nil if BUFFER is a GNUGO Board buffer."
321 (eq 'gnugo-board-mode
324 (or buffer (current-buffer)))))
326 (defun gnugo-board-user-play-ok-p (&optional buffer)
327 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
328 (with-current-buffer (or buffer (current-buffer))
329 (and gnugo-state (not (gnugo-get :waitingp)))))
331 (defsubst gnugo--blackp (string)
332 (string= "black" string))
334 (defun gnugo-other (color)
335 (if (gnugo--blackp color) "white" "black"))
337 (defun gnugo-gate (&optional in-progress-p)
338 (unless (gnugo-board-buffer-p)
339 (user-error "Wrong buffer -- try M-x gnugo"))
340 (unless (gnugo-get :proc)
341 (user-error "No \"gnugo\" process!"))
342 (when (gnugo-get :waitingp)
343 (user-error "Not your turn yet -- please wait for \"\(%s to play\)\""
344 (gnugo-get :user-color)))
345 (when (and in-progress-p (gnugo-get :game-over))
346 (user-error "Sorry, game over")))
348 (defun gnugo-sentinel (proc string)
349 (let ((status (process-status proc)))
350 (when (memq status '(exit signal))
351 (let ((buf (process-buffer proc)))
352 (when (buffer-live-p buf)
353 (with-current-buffer buf
354 (setq mode-line-process
356 (propertize (car (split-string string))
357 'face 'font-lock-warning-face)
359 (when (eq proc (gnugo-get :proc))
360 (gnugo-put :proc nil))))))))
362 (defun gnugo--begin-exchange (proc filter line)
363 (declare (indent 2)) ; good time, for a rime
364 ; nice style, for a wile...
365 (set-process-filter proc filter)
366 (process-send-string proc line)
367 (process-send-string proc "\n"))
369 (defun gnugo--q (fmt &rest args)
370 "Send formatted command \"FMT ARGS...\"; wait for / return response.
371 The response is a string whose first two characters indicate the
372 status of the command. See also `gnugo-query'."
373 (when (gnugo-get :waitingp)
374 (user-error "Sorry, still waiting for %s to play"
375 (gnugo-get :gnugo-color)))
376 (let ((proc (gnugo-get :proc)))
377 (process-put proc :incomplete t)
378 (process-put proc :srs "") ; synchronous return stash
379 (gnugo--begin-exchange
380 proc (lambda (proc string)
381 (let ((full (concat (process-get proc :srs)
383 (process-put proc :srs full)
384 (unless (numberp (gnugo--compare-strings
385 full (max 0 (- (length full)
388 (process-put proc :incomplete nil))))
391 (apply #'format fmt args)))
392 (while (process-get proc :incomplete)
393 (accept-process-output proc 30))
394 (prog1 (substring (process-get proc :srs) 0 -2)
395 (process-put proc :srs ""))))
397 (defun gnugo-query (message-format &rest args)
398 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
399 Return a string that omits the first two characters (corresponding
400 to the status indicator in the Go Text Protocol). Use this function
401 when you are sure the command cannot fail."
402 (substring (apply 'gnugo--q message-format args)
405 (defun gnugo-lsquery (message-format &rest args)
406 (split-string (apply 'gnugo-query message-format args)))
408 (defsubst gnugo--count-query (fmt &rest args)
409 (length (apply 'gnugo-lsquery fmt args)))
411 (defsubst gnugo--root-prop (prop &optional tree)
412 (cdr (assq prop (gnugo--root-node tree))))
414 (defun gnugo--set-root-prop (prop value &optional tree)
415 (let* ((root (gnugo--root-node tree))
416 (cur (assq prop root)))
419 (push (cons prop value)
420 (cdr (last root))))))
422 (defun gnugo--play-stone (color pos-or-PASS)
423 (let ((accept (gnugo--q (format "play %s %s" color pos-or-PASS))))
424 (unless (= ?= (aref accept 0))
425 (user-error "%s" accept))))
427 (defsubst gnugo--user-play-stone (pos-or-PASS)
428 (gnugo--play-stone (gnugo-get :user-color) pos-or-PASS))
430 (defun gnugo-goto-pos (pos)
431 "Move point to board position POS, a letter-number string."
432 (goto-char (point-min))
433 (forward-line (- (1+ (gnugo-get :SZ))
434 (string-to-number (substring pos 1))))
436 (forward-char (+ (if (= 32 (following-char)) 1 2)
437 (* 2 (- (let ((letter (aref pos 0)))
443 (defun gnugo-f (frag)
444 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
446 (defun gnugo-yang (c)
447 (cdr (assq c '((?+ . hoshi)
449 (?X . (bmoku . bpmoku))
450 (?O . (wmoku . wpmoku))))))
452 (defun gnugo-yy (yin yang &optional momentaryp)
453 (gnugo-f (format "%d-%s"
454 yin (cond ((and (consp yang) momentaryp) (cdr yang))
455 ((consp yang) (car yang))
458 (defun gnugo-toggle-image-display ()
459 (unless (and (fboundp 'display-images-p) (display-images-p))
460 (user-error "Display does not support images, sorry"))
461 (require 'gnugo-xpms)
462 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
463 (user-error "Could not load `gnugo-xpms', sorry"))
464 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
465 (unless (eq fresh (gnugo-get :xpms))
466 (gnugo-put :xpms fresh)
467 (gnugo-put :all-yy nil)))
468 (let* ((new (not (gnugo-get :display-using-images)))
469 (act (if new 'display 'do-not-display)))
471 (setcar (symbol-plist yy) act))
472 (or (gnugo-get :all-yy)
474 (prog1 (mapcar (lambda (ent)
476 (yy (gnugo-yy (cdr k) (car k))))
477 (setplist yy `(not-yet ,(cdr ent)))
480 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
482 (gnugo-put :w-imul (car imul))
483 (gnugo-put :h-imul (cdr imul)))))))
484 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
485 (gnugo-put :highlight-last-move-spec
488 (get (gnugo-yy (get-text-property p 'gnugo-yin)
489 (get-text-property p 'gnugo-yang)
493 (gnugo-get :default-highlight-last-move-spec)))
494 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
495 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
496 (mapc 'delete-overlay (cdar group))
497 (setcdr (car group) nil))
498 (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
499 (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
500 (gnugo-put :display-using-images new)))
502 (defun gnugo-toggle-grid ()
503 "Turn the grid around the board on or off."
505 (funcall (if (memq :nogrid buffer-invisibility-spec)
506 'remove-from-invisibility-spec
507 'add-to-invisibility-spec)
509 (save-excursion (gnugo-refresh)))
511 (defun gnugo-propertize-board-buffer ()
513 (insert (substring (gnugo--q "showboard") 3))
514 (let* ((grid-props (list 'invisible :nogrid
515 'font-lock-face gnugo-grid-face))
516 (%gpad (gnugo-f 'gpad))
517 (%gspc (gnugo-f 'gspc))
518 (%lpad (gnugo-f 'lpad))
519 (%rpad (gnugo-f 'rpad))
520 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
521 (size (gnugo-get :SZ))
522 (size-string (number-to-string size)))
523 (goto-char (point-min))
524 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
525 (skip-chars-forward " ")
526 (put-text-property (1- (point)) (point) 'category %gpad)
527 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
529 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
530 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
531 (let* ((row (match-string-no-properties 1))
533 (other-edge (+ edge (* 2 size) -1))
534 (right-empty (+ other-edge (length row) 1))
535 (top-p (string= size-string row))
536 (bot-p (string= "1" row)))
537 (let* ((nL (- edge 1 (length size-string)))
539 (ov (make-overlay nL nR (current-buffer) t)))
540 (add-text-properties nL nR grid-props)
541 ;; We redundantly set `invisible' in the overlay to workaround
542 ;; a display bug whereby text *following* the overlaid text is
543 ;; displayed with the face of the overlaid text, but only when
544 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
545 ;; This has something to do w/ the bletcherous `before-string'.
546 (overlay-put ov 'invisible :nogrid)
547 (overlay-put ov 'category %lpad))
548 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
550 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
551 (truncate (- p edge) 2))
553 (yin (let ((A-p (= edge p))
554 (Z-p (= (1- other-edge) p)))
555 (cond ((and top-p A-p) 1)
564 (yang (gnugo-yang (char-after p))))
565 (add-text-properties p (1+ p)
575 (gnugo-position gnugo-yin))))
576 (unless (= (1- other-edge) p)
577 (add-text-properties (1+ p) (+ 2 p) ispc-props)
578 (put-text-property p (+ 2 p) 'intangible ival)))
579 (add-text-properties (1+ other-edge) right-empty grid-props)
580 (goto-char right-empty)
581 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
582 (let ((prop (if (string= "WH" (match-string 1))
585 (beg (match-beginning 2))
587 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
588 (gnugo-put prop (match-string-no-properties 2))))
590 (put-text-property right-empty (point) 'category %rpad)
592 (add-text-properties (1- (point)) (point-max) grid-props)
593 (skip-chars-forward " ")
594 (put-text-property (1- (point)) (point) 'category %gpad)
595 (put-text-property (point) (progn (end-of-line) (point))
598 (defun gnugo-merge-showboard-results ()
599 (let ((aft (substring (gnugo--q "showboard") 3))
600 (adj 1) ; string to buffer position adjustment
602 (sync "[0-9]* stones$")
603 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
604 ;; restrictive a condition that fails in the case of:
607 ;; ... WHITE has captured 1 stones
610 ;; ... WHITE has captured 14 stones
613 ;; where the after count has more digits than the before count,
614 ;; but shares the same leading digits. In this case, the result
615 ;; of `compare-strings' points to the SPC following the before
616 ;; count (indicated by caret in this example).
618 (bef (buffer-substring-no-properties (point-min) (point-max)))
619 (bef-start 0) (bef-idx 0)
620 (aft-start 0) (aft-idx 0)
621 aft-sync-backtrack mis inc cut new very-strange)
622 (while (numberp (setq mis (gnugo--compare-strings
625 (setq aft-sync-backtrack nil
626 inc (if (cl-minusp mis)
629 bef-idx (+ bef-start inc)
630 aft-idx (+ aft-start inc)
631 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
634 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
635 (let ((peek (1- aft-idx)))
636 (while (not (= 32 (aref aft peek)))
637 (setq peek (1- peek)))
638 (setq aft-sync-backtrack (1+ peek))))
642 (if aft-sync-backtrack
643 (- aft-sync-backtrack aft-idx)
646 (if aft-sync-backtrack
647 (let* ((asb aft-sync-backtrack)
648 (l-p (get-text-property cut :gnugo-cf))
651 (keep (text-properties-at cut)))
652 (setq new (substring aft asb (string-match " " aft asb)))
653 (plist-put keep :gnugo-cf (cons (length new) capprop))
654 (gnugo-put capprop new)
655 (delete-char old-len)
656 (insert (apply 'propertize new keep))
657 (incf adj (- (length new) old-len)))
658 (setq new (aref aft aft-idx))
659 (insert-and-inherit (char-to-string new))
660 (let ((yin (get-text-property cut 'gnugo-yin))
661 (yang (gnugo-yang new)))
662 (add-text-properties cut (1+ cut)
666 ,(gnugo-yy yin yang))))
668 ;; do this last to avoid complications w/ font lock
669 ;; (this also means we cannot include `intangible' in `front-sticky')
670 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
671 (put-text-property cut (1+ cut) 'intangible very-strange))))))
673 (defsubst gnugo--move-prop (node)
677 (defun gnugo--as-pos-func ()
678 (lexical-let ((size (gnugo-get :SZ)))
683 (let ((col (aref cc 0)))
685 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
686 (- size (- (aref cc 1) ?a))))))))
688 (defun gnugo-move-history (&optional rsel)
689 "Determine and return the game's move history.
690 Optional arg RSEL controls side effects and return value.
691 If nil, display the history in the echo area as \"(N moves)\"
692 followed by the space-separated list of moves. When called
693 interactively with a prefix arg (i.e., RSEL is `(4)'), display
694 similarly, but suffix with the mover (either \":B\" or \":W\").
695 If RSEL is the symbol `car' return the most-recent move; if
696 `cadr', the next-to-most-recent move; if `count' the number of
697 moves thus far; if `two' the last two moves as a list, oldest last.
699 For all other values of RSEL, do nothing and return nil."
701 (let* ((monkey (gnugo-get :monkey))
702 (mem (aref monkey 0))
703 (as-pos (gnugo--as-pos-func))
706 ((as-pos-maybe (x) (if (string= "resign" x)
709 (next (byp) (when (setq node (pop mem)
710 mprop (gnugo--move-prop node))
711 (setq move (as-pos-maybe (cdr mprop)))
713 (format "%s%s" move (car mprop))
717 (tell () (message "(%d moves) %s"
719 (mapconcat 'identity (nreverse acc) " ")))
720 (finish (byp) (while mem (next byp)) (tell)))
725 (`cadr (nn) (car (nn)))
726 (`count (gethash (car mem) (gnugo--tree-mnum
727 (gnugo-get :sgf-gametree))))
731 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
732 "A special mode for manipulating a GNUGO gametree.
734 \\{gnugo-frolic-mode-map}"
735 (setq truncate-lines t)
736 (buffer-disable-undo))
738 (defun gnugo-frolic-quit ()
739 "Kill GNUGO Frolic buffer and switch to its parent buffer."
741 (let ((bye (current-buffer)))
742 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
743 gnugo-frolic-parent-buffer))
746 (defun gnugo-frolic-return-to-origin ()
747 "Move point to the board's current position."
749 (if (not gnugo-frolic-origin)
750 (message "No origin")
751 (goto-char gnugo-frolic-origin)
752 (recenter (- (count-lines (line-beginning-position)
755 (defun gnugo-frolic-in-the-leaves ()
756 "Display the game tree in a *GNUGO Frolic* buffer.
757 This looks something like:
760 2 W -- K10 K10 K10 K10
779 with 0, 1, ... N (in this case N is 3) in the header line
780 to indicate the branches. Branch 0 is the \"main line\".
781 Point (* in this example) indicates the current position,
782 and moves not actually on the game tree (e.g., E7, branch 3)
783 are dimmed. Type \\[describe-mode] in that buffer for details."
785 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
787 (from (or gnugo-frolic-parent-buffer
789 ;; todo: use defface once we finally succumb to ‘customize’
790 (dimmed-node-face (list :inherit 'default
791 :foreground "gray50"))
792 (tree (gnugo-get :sgf-gametree))
793 (ends (copy-sequence (gnugo--tree-ends tree)))
794 (mnum (gnugo--tree-mnum tree))
797 (width (length ends))
798 (lanes (number-sequence 0 (1- width)))
799 (monkey (gnugo-get :monkey))
800 (as-pos (gnugo--as-pos-func))
801 (at (car (aref monkey 0)))
802 (bidx (aref monkey 1))
803 (valid (map 'vector (lambda (end)
804 (gethash (car end) mnum))
806 (max-move-num (apply 'max (append valid nil)))
807 (inhibit-read-only t)
813 (propertize s 'face face))
814 (fsi (properties fmt &rest args)
815 (insert (apply 'propertize
816 (apply 'format fmt args)
823 for node in (aref ends bx)
824 do (if (setq fork (on node))
827 ;; todo: ignore non-"move" nodes
828 (eq node (car (aref ends bix))))
830 (pushnew other (gethash node soil))))
835 (puthash node bx seen))
838 (switch-to-buffer buf)
841 (setq header-line-format
842 (lexical-let ((full (concat
844 (mapconcat (lambda (n)
854 `(space :width ,w))))
856 (when (eq 'left scroll-bar-mode)
857 (let ((w (or scroll-bar-width
859 nil 'scroll-bar-width)))
860 (cw (frame-char-width)))
864 (let ((fc (fringe-columns 'left t)))
868 (substring full (window-hscroll))
870 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
871 (set (make-local-variable 'gnugo-state)
872 (buffer-local-value 'gnugo-state from))
876 from max-move-num downto 1
877 do (setq props (list 'n n))
882 (goto-char (point-min))
885 n (aref ["W" "B"] (logand 1 n))))
887 do (let* ((node (unless (< (aref valid bx) n)
888 ;; todo: ignore non-"move" nodes
889 (pop (aref ends bx))))
892 (s (cond ((not node) "")
893 ((not (setq move (gnugo--move-prop node))) "-")
894 (t (funcall as-pos (cdr move))))))
895 (when (and ok (setq br (gethash node soil)))
896 (push (cons bx (sort br '<))
898 (fsi (list* 'bx bx props)
900 (cond ((and (eq at node)
903 (setq finish (point-marker)))
904 (emph s (list :inherit 'default
905 :foreground (frame-parameter
906 nil 'cursor-color))))
908 (emph s dimmed-node-face))
911 (when (progn (fsi props "\n")
912 (setq forks (nreverse forks)))
913 (let* ((margin (make-string 11 ?\s))
914 (heads (mapcar #'car forks))
915 (tails (mapcar #'cdr forks)))
917 ((spaced (lanes func)
918 (mapconcat func lanes " "))
919 ;; live to play ~ ~ ()
920 ;; play to learn (+) (-) . o O
921 ;; learn to live --ttn .M. _____U
922 (dashed (lanes func) ;;; _____ ^^^^
923 (mapconcat func lanes "-----"))
925 (spaced lanes (lambda (bx)
929 (pad-unless (condition)
940 do (let* ((one (car ls))
943 (mapcar 'car (cdr ls))
945 (apply 'append (mapcar 'cdr bef))))
948 (end (car (last ord))))
950 ((also (b e) (cnxn (number-sequence b e)
955 (pad-unless (zerop beg))
956 (dashed (number-sequence beg end)
958 (cond ((memq bx ord) "+")
961 (pad-unless (>= end width))
962 (also (1+ end) (1- width))
965 (edge (apply 'append tails))
966 (aa2u (line-beginning-position
967 (- (1+ (length forks))))
970 (set (make-local-variable 'gnugo-frolic-origin) finish)
971 (gnugo-frolic-return-to-origin))))
973 (defun gnugo--awake (how)
974 ;; Valid HOW elements:
975 ;; require-valid-branch
977 ;; (line . move-string)
978 ;; Invalid elements blissfully ignored. :-D
979 (let* ((tree (gnugo-get :sgf-gametree))
980 (ends (gnugo--tree-ends tree))
981 (width (length ends))
982 (monkey (gnugo-get :monkey))
983 (line (case (cdr (assq 'line how))
985 (count-lines (point-min) (line-beginning-position)))
988 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
991 (col (current-column))
992 (a (unless (> 10 col)
993 (let ((try (/ (- col 10)
995 (unless (<= width try)
998 (when (memq 'require-valid-branch how)
1000 (user-error "No branch here")))
1001 (loop with omit = (cdr (assq 'omit how))
1002 for (name . value) in `((line . ,line)
1003 (bidx . ,(aref monkey 1))
1008 do (unless (memq name omit)
1012 (defmacro gnugo--awakened (how &rest body)
1013 (declare (indent 1))
1014 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1016 for name in '(line bidx monkey
1019 do (unless (memq name omit)
1022 (gnugo--awake ',how)
1025 (defsubst gnugo--move-to-bcol (bidx)
1026 (move-to-column (+ 10 (* 6 bidx))))
1028 (defun gnugo--swiz (direction &optional blunt)
1029 (gnugo--awakened (require-valid-branch
1032 (let* ((b (cond ((numberp blunt)
1033 (unless (and (< -1 blunt)
1035 (user-error "No such branch: %s" blunt))
1037 (t (mod (+ direction a) width))))
1038 (flit (if blunt (lambda (n)
1043 (mod (+ direction n) width))))
1044 (was (copy-sequence ends))
1045 (new-bidx (funcall flit bidx)))
1046 (loop for bx below width
1047 do (aset ends (funcall flit bx)
1049 (unless (= new-bidx bidx)
1050 (aset monkey 1 new-bidx))
1051 (gnugo-frolic-in-the-leaves)
1052 (goto-char (point-min))
1054 (gnugo--move-to-bcol b))))
1056 (defun gnugo-frolic-exchange-left ()
1057 "Exchange the current branch with the one to its left."
1061 (defun gnugo-frolic-rotate-left ()
1062 "Rotate all branches left."
1066 (defun gnugo-frolic-exchange-right ()
1067 "Exchange the current branch with the one to its right."
1071 (defun gnugo-frolic-rotate-right ()
1072 "Rotate all branches right."
1076 (defun gnugo-frolic-set-as-main-line ()
1077 "Make the current branch the main line."
1079 (gnugo--swiz nil 0))
1081 (defun gnugo-frolic-prune-branch ()
1082 "Remove the current branch from the gametree.
1083 This fails if there is only one branch in the tree.
1084 This fails if the monkey is on the current branch
1085 \(a restriction that will probably be lifted Real Soon Now\)."
1087 (gnugo--awakened (require-valid-branch
1088 (line . move-string))
1089 ;; todo: define meaningful eviction semantics; remove restriction
1091 (user-error "Cannot prune with monkey on branch"))
1093 (user-error "Cannot prune last remaining branch"))
1094 (let ((new (append ends nil)))
1095 ;; Explicit ignorance avoids byte-compiler warning.
1096 (ignore (pop (nthcdr a new)))
1097 (gnugo--set-tree-ends tree new))
1099 (aset monkey 1 (decf bidx)))
1100 (gnugo-frolic-in-the-leaves)
1102 (goto-char (point-min))
1103 (search-forward line)
1104 (gnugo--move-to-bcol (min a (- width 2))))))
1106 (defun gnugo--sideways (backwards n)
1107 (gnugo--awakened ((omit tree ends monkey bidx line))
1108 (gnugo--move-to-bcol (mod (if backwards
1113 (defun gnugo-frolic-backward-branch (&optional n)
1114 "Move backward N (default 1) branches."
1116 (gnugo--sideways t n))
1118 (defun gnugo-frolic-forward-branch (&optional n)
1119 "Move forward N (default 1) branches."
1121 (gnugo--sideways nil n))
1123 (defun gnugo--vertical (n direction)
1126 direction (- direction)))
1127 (gnugo--awakened ((line . numeric)
1128 (omit tree ends width monkey bidx))
1129 (let ((stop (if (> 0 direction)
1131 (max 0 (1- (count-lines (point-min)
1135 (loop while (not (= line stop))
1137 (forward-line direction)
1138 (incf line direction))
1139 until (get-text-property (point) 'n))
1140 until (zerop (decf n)))
1142 (gnugo--move-to-bcol a)
1143 (move-to-column col)))))
1145 (defun gnugo-frolic-previous-move (&optional n)
1146 "Move to the Nth (default 1) previous move."
1148 (gnugo--vertical n -1))
1150 (defun gnugo-frolic-next-move (&optional n)
1151 "Move to the Nth (default 1) next move."
1153 (gnugo--vertical n 1))
1155 (defun gnugo-boss-is-near ()
1156 "Do `bury-buffer' until the current one is not a GNU Board."
1158 (while (gnugo-board-buffer-p)
1161 (defsubst gnugo--passp (string)
1162 (string= "PASS" string))
1164 (defsubst gnugo--no-regrets (monkey ends)
1165 (eq (aref ends (aref monkey 1))
1168 (defun gnugo--as-cc-func ()
1169 (lexical-let ((size (gnugo-get :SZ)))
1171 (let* ((col (aref pos 0))
1172 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1173 (two (+ ?a (- size (string-to-number
1174 (substring pos 1))))))
1175 (format "%c%c" one two)))))
1177 (defsubst gnugo--decorate (node alist)
1178 ;; NB: ALIST should not have :B or :W keys.
1179 (setcdr (last node) alist))
1181 (defun gnugo-note (property value &optional mogrifyp)
1183 (let ((as-cc (gnugo--as-cc-func)))
1185 ((mog (pos) (if (gnugo--passp pos)
1187 (funcall as-cc pos))))
1188 (setq value (if (consp value)
1189 (mapcar #'mog value)
1191 (let* ((pair (cons property value))
1193 (monkey (gnugo-get :monkey))
1194 (mem (aref monkey 0))
1196 (if (memq property '(:B :W))
1197 (let* ((tree (gnugo-get :sgf-gametree))
1198 (ends (gnugo--tree-ends tree))
1199 (mnum (gnugo--tree-mnum tree))
1200 (count (length ends))
1201 (tip-move-num (gethash tip mnum))
1202 (bidx (aref monkey 1)))
1203 ;; Detect déjà-vu. That is, when placing "A", avoid:
1209 ;; (such "variations" do not actually vary!) in favor of:
1215 ;; This linear search loses for multiple ‘old’ w/ "A",
1216 ;; a very unusual (but not invalid, sigh) situation.
1220 ;; Start with latest / highest likelihood for hit.
1221 ;; (See "to the right" comment, below.)
1222 from (if (gnugo--no-regrets monkey ends)
1226 if (setq bx (mod (+ bidx i) count)
1229 for m on (aref ends bx)
1230 while (< tip-move-num
1231 (gethash (setq node (car m))
1235 (when (equal pair (assoc property node))
1243 (rotatef (aref ends bidx)
1245 (setq mem previous))
1249 (unless (gnugo--no-regrets monkey ends)
1250 (setq ends (gnugo--set-tree-ends
1251 tree (let ((ls (append ends nil)))
1252 ;; copy old to the right of new
1253 (push mem (nthcdr bidx ls))
1255 (puthash fruit (1+ (gethash tip mnum)) mnum)
1257 (aset ends bidx mem)))
1258 (setf (aref monkey 0) mem))
1259 (gnugo--decorate tip fruit))))
1261 (defun gnugo-close-game (end-time resign)
1262 (gnugo-put :game-end-time end-time)
1263 (let ((now (or end-time (current-time))))
1264 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1266 (gnugo-put :game-over
1267 (if (or (eq t resign)
1268 (and (stringp resign)
1269 (string-match "[BW][+][Rr]esign" resign)))
1271 ((ls (color) (mapcar
1276 (gnugo-query "worm_stones %s" color)
1278 (let ((live (append (ls "black") (ls "white"))))
1281 (let ((dd (gnugo-query "dragon_data"))
1282 (start 0) mem color ent live dead)
1283 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1285 (setq mem (match-string 1 dd)
1286 color (match-string 2 dd)
1288 ent (cons (list color)
1289 (sort (gnugo-lsquery "dragon_stones %s" mem)
1291 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1293 (if (match-string 2 dd)
1296 (setq start (match-end 0)))
1300 (defun gnugo--unclose-game ()
1301 (dolist (prop '(:game-over ; all those in -close-game
1304 (gnugo-put prop nil))
1305 (let* ((root (gnugo--root-node))
1306 (cur (assq :RE root)))
1308 (assert (not (eq cur (car root))) nil
1309 ":RE at head of root node: %S"
1313 (defun gnugo-push-move (userp move)
1314 (let* ((color (gnugo-get (if userp :user-color :gnugo-color)))
1315 (start (gnugo-get :waiting-start))
1316 (now (current-time))
1317 (resignp (string= "resign" move))
1318 (passp (gnugo--passp move))
1319 (head (gnugo-move-history 'car))
1320 (onep (and head (gnugo--passp head)))
1321 (donep (or resignp (and onep passp))))
1323 (gnugo-merge-showboard-results))
1324 (gnugo-put :last-mover color)
1326 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1327 (gnugo-note (if (gnugo--blackp color) :B :W) move (not resignp))
1329 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1331 (gnugo-close-game now resignp))
1332 (gnugo-put :waiting-start (and (not donep) now))
1335 (defun gnugo-venerate (yin yang)
1336 (let* ((fg-yy (gnugo-yy yin yang))
1337 (fg-disp (or (get fg-yy 'display)
1338 (get fg-yy 'do-not-display)))
1339 (fg-data (plist-get (cdr fg-disp) :data))
1340 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1341 (bg-disp (or (get bg-yy 'display)
1342 (get bg-yy 'do-not-display)))
1343 (bg-data (plist-get (cdr bg-disp) :data))
1347 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1348 (setq start (match-end 0))
1349 (string-to-number (match-string 1 s)))))
1350 (while (and (not (cl-minusp ncolors))
1351 (string-match ",\n" s start))
1352 (setq start (match-end 0)
1353 ncolors (1- ncolors)))
1354 (string-match "\"" s start)
1356 (new (copy-sequence fg-data))
1357 (lx (length fg-data))
1358 (sx (funcall bop fg-data))
1359 (sb (funcall bop bg-data))
1360 (color-key (aref new sx))) ; blech, heuristic
1362 (when (and (not (= color-key (aref new sx)))
1363 (cl-plusp (random 4)))
1364 (aset new sx (aref bg-data sb)))
1367 (create-image new 'xpm t :ascent 'center)))
1369 (defun gnugo-refresh (&optional nocache)
1370 "Update GNUGO Board buffer display.
1371 While a game is in progress, parenthesize the last-played stone (no parens
1372 for pass). If the buffer is currently displayed in the selected window,
1373 recenter the board (presuming there is extra space in the window). Update
1374 the mode line. Lastly, move point to the last position played by the user,
1375 if that move was not a pass.
1377 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1378 be slow. (This should normally be unnecessary; specify it only if the display
1379 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1382 (when (and nocache (not (gnugo-get :waitingp)))
1383 (gnugo-propertize-board-buffer))
1384 (let* ((last-mover (gnugo-get :last-mover))
1385 (other (gnugo-other last-mover))
1386 (move (gnugo-move-history 'car))
1387 (game-over (gnugo-get :game-over))
1391 (let ((l-ov (gnugo-get :lparen-ov))
1392 (r-ov (gnugo-get :rparen-ov)))
1393 (if (member move '("PASS" "resign"))
1394 (mapc 'delete-overlay (list l-ov r-ov))
1395 (gnugo-goto-pos move)
1397 (hspec (gnugo-get :highlight-last-move-spec))
1398 (display-value (nth 0 hspec))
1399 (l-offset (nth 1 hspec))
1400 (l-new-pos (+ p l-offset))
1401 (r-action (nth 2 hspec)))
1402 (overlay-put l-ov 'display
1403 (if (functionp display-value)
1404 (funcall display-value p)
1406 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1408 (funcall r-action r-ov)
1409 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1411 (rename-buffer (concat (gnugo-get :diamond)
1413 (format "%s(game over)"
1414 (if (string= move "resign")
1415 (concat move "ation ")
1417 (format "%s(%s to play)"
1418 (if move (concat move " ") "")
1422 (let ((live (cdr (assq 'live game-over)))
1423 (dead (cdr (assq 'dead game-over)))
1425 (unless (eq game-over (get-text-property 1 'game-over))
1426 (dolist (group (append live dead))
1427 (dolist (pos (cdr group))
1428 (gnugo-goto-pos pos)
1430 (put-text-property p (1+ p) 'group group)))
1431 (put-text-property 1 2 'game-over game-over))
1432 (dolist (group live)
1433 (when (setq pall (cdar group))
1434 (mapc 'delete-overlay pall)
1435 (setcdr (car group) nil)))
1436 (dolist (group dead)
1437 (unless (cdar group)
1438 (let (ov pall c (color (caar group)))
1439 (setq c (if (gnugo--blackp color) "x" "o"))
1440 (dolist (pos (cdr group))
1441 (gnugo-goto-pos pos)
1442 (setq p (point) ov (make-overlay p (1+ p)))
1445 (if (gnugo-get :display-using-images)
1446 ;; respect the dead individually; it takes more time
1447 ;; but that's not a problem (for them)
1448 (gnugo-venerate (get-text-property p 'gnugo-yin)
1449 (gnugo-yang (aref (upcase c) 0)))
1450 (propertize c 'face 'font-lock-warning-face)))
1452 (setcdr (car group) pall))))))
1454 (when (setq window (get-buffer-window (current-buffer)))
1455 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1456 (size (gnugo-get :SZ))
1457 (under10p (< size 10))
1458 (h (- (truncate (- (window-height window)
1459 (* size (gnugo-get :hmul))
1463 (edges (window-edges window))
1464 (right-w-edge (nth 2 edges))
1465 (avail-width (- right-w-edge (nth 0 edges)))
1466 (wmul (gnugo-get :wmul))
1467 (imagesp (symbol-plist (gnugo-f 'ispc)))
1468 (w (/ (- avail-width
1473 2 ; between board and grid
1478 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1479 `(display ,(make-string h 10))
1480 '(invisible :nogrid)))
1485 (cond (imagesp (+ (* 0.5 wmul)
1491 (gspc . ,(when imagesp
1495 ;; DWR: image width alone => OBOE!
1497 ;; NB: ‘(* wmul cw)’ is the same
1498 ;; as ‘(car (image-size ... t))’.
1499 (let ((cw (frame-char-width)))
1500 (/ (+ 1.0 (* wmul cw))
1503 (lpad . ,(let ((d `(display (space :align-to ,w))))
1504 ;; We distinguish between these cases to
1505 ;; workaround a display bug whereby the
1506 ;; `before-string' is omitted entirely (not
1507 ;; rendered) when interacting w/ the text
1508 ;; mode last-move left-paren for moves in
1512 ,(apply 'propertize " " d))
1515 (space :align-to ,(1- avail-width))))))
1516 (setplist (gnugo-f (car pair)) (cdr pair)))))
1518 (let ((cur (gnugo-get :mode-line)))
1519 (unless (equal cur gnugo-mode-line)
1520 (setq cur gnugo-mode-line)
1521 (gnugo-put :mode-line cur)
1522 (gnugo-put :mode-line-form
1523 (cond ((stringp cur)
1524 (setq cur (copy-sequence cur))
1526 (while (setq cut (string-match "~[bwpmtu]" cur))
1528 (setq c (aref cur (incf cut)))
1531 `(,(intern (format "squig-%c" c))
1533 (?b '(or (gnugo-get :black-captures) 0))
1534 (?w '(or (gnugo-get :white-captures) 0))
1535 (?p '(gnugo-other (gnugo-get :last-mover)))
1536 (?t '(let ((ws (gnugo-get :waiting-start)))
1538 (cadr (time-since ws))
1540 (?u '(or (gnugo-get :last-waiting) "-"))
1541 (?m '(gnugo-move-history 'count))))
1543 `(let ,(delete-dups (copy-sequence acc))
1544 (format ,cur ,@(reverse (mapcar 'car acc))))))
1546 (let ((form (gnugo-get :mode-line-form)))
1547 (setq mode-line-process
1549 ;; this dynamicism is nice but excessive in its wantonness
1550 ;;- `(" [" (:eval ,form) "]")
1551 ;; this dynamicism is ok because the user triggers it
1552 (list (format " [%s]" (eval form))))))
1553 (force-mode-line-update))
1555 (when (setq last (gnugo-get :last-user-bpos))
1556 (gnugo-goto-pos last))))
1558 ;;;---------------------------------------------------------------------------
1559 ;;; Game play actions
1561 (defun gnugo-get-move-insertion-filter (proc string)
1562 (with-current-buffer (process-buffer proc)
1563 (let* ((so-far (gnugo-get :get-move-string))
1564 (full (gnugo-put :get-move-string (concat so-far string))))
1565 (when (string-match "^= \\(.+\\)\n\n" full)
1566 (let ((pos-or-pass (match-string 1 full)))
1567 (gnugo-put :get-move-string nil)
1568 (gnugo-put :waitingp nil)
1569 (gnugo-push-move nil pos-or-pass)
1570 (let ((buf (current-buffer)))
1571 (let (gnugo-inhibit-refresh)
1572 (run-hooks 'gnugo-post-move-hook)
1573 (unless gnugo-inhibit-refresh
1574 (with-current-buffer buf
1575 (gnugo-refresh))))))))))
1577 (defun gnugo-get-move (color)
1578 (gnugo-put :waitingp t)
1579 (gnugo--begin-exchange
1580 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1581 (concat "genmove " color))
1582 (accept-process-output))
1584 (defun gnugo-cleanup ()
1585 (when (gnugo-board-buffer-p)
1586 (unless (zerop (buffer-size))
1587 (message "Thank you for playing GNU Go."))
1589 (setplist sym nil) ; "...is next to fordliness." --Huxley
1590 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1591 ;; No worries, things will be Much Better w/ structs, RSN...
1593 (append (gnugo-get :all-yy)
1602 (setq gnugo-state nil)))
1604 (defun gnugo-position ()
1605 (or (get-text-property (point) 'gnugo-position)
1606 (user-error "Not a proper position point")))
1608 (defun gnugo-move ()
1609 "Make a move on the GNUGO Board buffer.
1610 The position is computed from current point.
1611 Signal error if done out-of-turn or if game-over.
1612 To start a game try M-x gnugo."
1615 (let* ((buf (current-buffer))
1616 (pos (gnugo-position)))
1617 (gnugo--user-play-stone pos)
1618 (gnugo-push-move t pos) ; value always nil for non-pass move
1619 (let (gnugo-inhibit-refresh)
1620 (run-hooks 'gnugo-post-move-hook)
1621 (unless gnugo-inhibit-refresh
1622 (with-current-buffer buf
1624 (with-current-buffer buf
1625 (gnugo-get-move (gnugo-get :gnugo-color)))))
1627 (defun gnugo-mouse-move (e)
1628 "Do `gnugo-move' at mouse location."
1631 (when (looking-at "[.+]")
1634 (defun gnugo-pass ()
1635 "Make a pass on the GNUGO Board buffer.
1636 Signal error if done out-of-turn or if game-over.
1637 To start a game try M-x gnugo."
1640 (gnugo--user-play-stone "PASS")
1641 (let ((donep (gnugo-push-move t "PASS"))
1642 (buf (current-buffer)))
1643 (let (gnugo-inhibit-refresh)
1644 (run-hooks 'gnugo-post-move-hook)
1645 (unless gnugo-inhibit-refresh
1646 (with-current-buffer buf
1649 (with-current-buffer buf
1650 (gnugo-get-move (gnugo-get :gnugo-color))))))
1652 (defun gnugo-mouse-pass (e)
1653 "Do `gnugo-pass' at mouse location."
1658 (defun gnugo-resign ()
1661 (if (not (y-or-n-p "Resign? "))
1662 (message "(not resigning)")
1663 (gnugo-push-move t "resign")
1666 (defun gnugo-animate-group (w/d)
1667 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1668 (let* ((pos (gnugo-position))
1669 (orig-b-m-p (buffer-modified-p))
1671 (unless (memq (following-char) '(?X ?O))
1672 (user-error "No stone at %s" pos))
1673 (setq blurb (message "Computing %s stones ..." w/d)
1674 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1675 (message "%s %s in group." blurb (length stones))
1676 (setplist (gnugo-f 'anim) nil)
1677 (let* ((spec (if (gnugo-get :display-using-images)
1678 (loop with yin = (get-text-property (point) 'gnugo-yin)
1679 with yang = (gnugo-yang (following-char))
1680 with up = (get (gnugo-yy yin yang t) 'display)
1681 with dn = (get (gnugo-yy yin yang) 'display)
1682 for n below (length gnugo-animation-string)
1683 collect (if (zerop (logand 1 n))
1685 (split-string gnugo-animation-string "" t)))
1687 (ovs (save-excursion
1688 (mapcar (lambda (pos)
1689 (gnugo-goto-pos pos)
1691 (ov (make-overlay p (1+ p))))
1692 (overlay-put ov 'category (gnugo-f 'anim))
1693 (overlay-put ov 'priority most-positive-fixnum)
1696 (setplist (gnugo-f 'anim) (cons 'display cell))
1697 (while (and (cdr spec) ; let last linger lest levity lost
1698 (sit-for 0.08675309)) ; jenny jenny i got your number...
1699 (setcar cell (setq spec (cdr spec)))
1700 ;; Force redisplay of overlays.
1701 (set-buffer-modified-p orig-b-m-p))
1703 (mapc 'delete-overlay ovs)
1706 (defun gnugo-display-group-data (command buffer-name)
1707 (message "Computing %s ..." command)
1708 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1709 (switch-to-buffer buffer-name)
1712 (message "Computing %s ... done." command))
1714 (defun gnugo-worm-stones ()
1715 "In the GNUGO Board buffer, animate \"worm\" at current position.
1716 Signal error if done out-of-turn or if game-over.
1717 See variable `gnugo-animation-string' for customization."
1720 (gnugo-animate-group 'worm))
1722 (defun gnugo-worm-data ()
1723 "Display in another buffer data from \"worm\" at current position.
1724 Signal error if done out-of-turn or if game-over."
1727 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1729 (defun gnugo-dragon-stones ()
1730 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1731 Signal error if done out-of-turn or if game-over.
1732 See variable `gnugo-animation-string' for customization."
1735 (gnugo-animate-group 'dragon))
1737 (defun gnugo-dragon-data ()
1738 "Display in another buffer data from \"dragon\" at current position.
1739 Signal error if done out-of-turn or if game-over."
1742 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1744 (defun gnugo-toggle-dead-group ()
1745 "In a GNUGO Board buffer, during game-over, toggle a group as dead.
1746 The group is selected from current position (point). Signal error if
1747 not in game-over or if there is no group at that position.
1749 In the context of GNU Go, a group is called a \"dragon\" and may be
1750 composed of more than one \"worm\" (set of directly-connected stones).
1751 It is unclear to the gnugo.el author whether or not GNU Go supports
1752 - considering worms as groups in their own right; and
1753 - toggling group aliveness via GTP.
1754 Due to these uncertainties, this command is only half complete; the
1755 changes you may see in Emacs are not propagated to the gnugo subprocess.
1756 Thus, GTP commands like `final_score' may give unexpected results.
1758 If you are able to expose via GTP `change_dragon_status' in utils.c,
1759 you may consider modifying the `gnugo-toggle-dead-group' source code
1760 to enable full functionality."
1762 (let ((game-over (or (gnugo-get :game-over)
1763 (user-error "Sorry, game still in play")))
1764 (group (or (get-text-property (point) 'group)
1765 (user-error "No stone at that position")))
1766 (now (current-time)))
1767 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1769 (let ((live (assq 'live game-over))
1770 (dead (assq 'dead game-over))
1772 (if (memq group live)
1773 (setq bef live now dead)
1774 (setq bef dead now live))
1775 (setcdr bef (delq group (cdr bef)))
1776 (setcdr now (cons group (cdr now)))
1777 ;; disabled permanently -- too wrong
1781 (let ((color (caar group)))
1782 (dolist (stone (cdr group))
1783 (gnugo--play-stone color stone)))))
1786 ;; drastic (and wrong -- clobbers capture info, etc)
1787 (gnugo-query "clear_board")
1788 (mapc #'populate (cdr live)))))
1789 ;; here is the desired interface (to be enabled Some Day)
1791 (gnugo-query "change_dragon_status %s %s"
1792 (cadr group) (if (eq now live)
1798 (defun gnugo-estimate-score ()
1799 "Display estimated score of a game of GNU Go.
1800 Output includes number of stones on the board and number of stones
1801 captured by each player, and the estimate of who has the advantage (and
1802 by how many stones)."
1804 (message "Est.score ...")
1805 (let ((black (gnugo--count-query "list_stones black"))
1806 (white (gnugo--count-query "list_stones white"))
1807 (black-captures (gnugo-query "captures black"))
1808 (white-captures (gnugo-query "captures white"))
1809 (est (gnugo-query "estimate_score")))
1810 ;; might as well update this
1811 (gnugo-put :black-captures black-captures)
1812 (gnugo-put :white-captures white-captures)
1813 (message "Est.score ... B %s %s | W %s %s | %s"
1814 black black-captures white white-captures est)))
1816 (defun gnugo-write-sgf-file (filename)
1817 "Save the game history to FILENAME (even if unfinished).
1818 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1819 (interactive "FWrite game as SGF file: ")
1820 (when (and (file-exists-p filename)
1821 (not (y-or-n-p "File exists. Continue? ")))
1822 (user-error "Not writing %s" filename))
1823 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1824 (set-buffer-modified-p nil))
1826 (defun gnugo--who-is-who (wait play samep)
1827 (message "GNU Go %splays as %s, you as %s (%s)"
1828 (if samep "" "now ")
1831 "NOTE: this is a switch!")))
1833 (defsubst gnugo--nodep (x)
1834 (keywordp (caar x)))
1836 (defsubst gnugo--SZ! (size)
1837 (gnugo-put :SZ size))
1839 (defun gnugo-read-sgf-file (filename)
1840 "Load the first game tree from FILENAME, a file in SGF format."
1841 (interactive "fSGF file to load: ")
1842 (when (file-directory-p filename)
1843 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1844 (let (ans play wait samep coll tree)
1845 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1846 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1847 (unless (= ?= (aref (setq ans (gnugo--q "loadsgf %s"
1848 (expand-file-name filename)))
1850 (user-error "%s" ans))
1851 (setq play (substring ans 2)
1852 wait (gnugo-other play)
1853 samep (string= (gnugo-get :user-color) play))
1854 (gnugo-put :last-mover wait)
1856 (gnugo-put :gnugo-color wait)
1857 (gnugo-put :user-color play))
1858 (setq coll (gnugo/sgf-create filename)
1859 tree (nth (let ((n (length coll)))
1863 ;; (let* ((q (format "Which game? (1-%d)" n))
1864 ;; (choice (1- (read-number q 1))))
1865 ;; (if (and (< -1 choice) (< choice n))
1867 ;; (message "(Selecting the first game)")
1869 ;; but this is what we use (for now) to accomodate
1870 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1872 (message "(Selecting the first game)"))
1875 (gnugo-put :sgf-collection coll)
1876 (gnugo-put :sgf-gametree tree)
1877 (gnugo-put :monkey (vector (aref (gnugo--tree-ends tree) 0) 0))
1878 ;; This is deliberately undocumented for now.
1879 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1881 (gnugo-put :game-over
1883 (or (gnugo--root-prop :RE tree)
1884 (and (equal '("PASS" "PASS") (gnugo-move-history 'two))
1886 (when (and game-over
1887 ;; (maybe) todo: user var to inhibit (can be slow)
1889 (gnugo-close-game nil game-over)))
1891 (set-buffer-modified-p nil)
1892 (gnugo--who-is-who wait play samep)))
1894 (defun gnugo-magic-undo (spec &optional noalt keep)
1895 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1896 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1897 check that the position is occupied by a stone of the user's color,
1898 and if so, remove moves from the history until that position is clear.
1899 If SPEC is a positive number, remove exactly that many moves from the
1900 history, signaling an error if the history is exhausted before finishing.
1901 If SPEC Is 0 (zero), remove either one or two moves,
1902 so that you are to play next.
1903 If SPEC is not recognized, signal \"bad spec\" error.
1905 Refresh the board for each move undone. If (in the case where SPEC is
1906 a number) after finishing, the color to play is not the user's color,
1907 schedule a move by GNU Go.
1909 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1910 turn to play. Optional second arg NOALT non-nil inhibits this.
1912 Optional third arg KEEP non-nil means do not prune the undone moves
1913 from the gametree, such that they become a sub-gametree (variation)
1917 (user-color (gnugo-get :user-color))
1918 (monkey (gnugo-get :monkey))
1919 (tree (gnugo-get :sgf-gametree))
1920 (ends (gnugo--tree-ends tree))
1921 (remorseful (not (gnugo--no-regrets monkey ends)))
1923 (cond ((numberp spec)
1924 (setq n (if (zerop spec)
1925 (if (string= user-color (gnugo-get :last-mover))
1929 done (lambda () (zerop n))))
1930 ((string-match "^[a-z]" spec)
1931 (let ((pos (upcase spec)))
1932 (setq done `(lambda ()
1933 (gnugo-goto-pos ,pos)
1934 (memq (following-char) '(?. ?+))))
1935 (when (funcall done)
1936 (user-error "%s already clear" pos))
1937 (when (= (save-excursion
1938 (gnugo-goto-pos pos)
1940 (if (gnugo--blackp user-color)
1943 (user-error "%s not occupied by %s" pos user-color))))
1944 (t (user-error "Bad spec: %S" spec)))
1945 (when (gnugo-get :game-over)
1946 (gnugo--unclose-game))
1947 (while (not (funcall done))
1948 (setq ans (gnugo--q "undo"))
1949 (unless (= ?= (aref ans 0))
1950 (user-error "%s" ans))
1951 (pop (aref monkey 0))
1952 (gnugo-put :last-mover (gnugo-other (gnugo-get :last-mover)))
1953 (gnugo-merge-showboard-results) ; all
1954 (gnugo-refresh) ; this
1956 (redisplay)) ; eye candy
1957 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1959 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1960 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1962 (gnugo-get :center-position)))
1964 (unless (or keep remorseful)
1965 (aset ends (aref monkey 1) (aref monkey 0)))
1966 (when (and ulastp (not noalt))
1967 (gnugo-get-move (gnugo-get :gnugo-color))))))
1969 (defun gnugo-undo-one-move (&optional me-next)
1970 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1971 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1972 Prefix arg ME-NEXT means to arrange for you to play
1973 the color of the next move (and GNU Go the opposite).
1974 This is useful after loading an SGF file whose last
1975 move was done by the color you prefer to play:
1976 \\[gnugo-read-sgf-file] FILENAME RET
1977 C-u \\[gnugo-undo-one-move]
1979 See also `gnugo-undo-two-moves'."
1982 (gnugo-magic-undo 1 t)
1984 (let* ((wait (gnugo-get :last-mover))
1985 (play (gnugo-other wait)))
1986 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
1987 (gnugo-put :user-color play)
1988 (gnugo-put :gnugo-color wait))))
1990 (defun gnugo-undo-two-moves ()
1991 "Undo a pair of moves (GNU Go's and yours).
1992 However, if you are the last mover, undo only one move.
1993 Regardless, after undoing, it is your turn to play again."
1996 (gnugo-magic-undo 0))
1998 (defun gnugo-oops (&optional position)
1999 "Like `gnugo-undo-two-moves', but keep the undone moves.
2000 The kept moves become a sub-gametree (variation) when play resumes.
2001 Prefix arg means, instead, undo repeatedly up to and including
2002 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2005 (gnugo-magic-undo (if position
2010 (defun gnugo-okay (&optional full)
2011 "Redo a pair of undone moves.
2012 Prefix arg means to redo all the undone moves."
2015 (let* ((tree (gnugo-get :sgf-gametree))
2016 (ends (gnugo--tree-ends tree))
2017 (monkey (gnugo-get :monkey)))
2018 (if (gnugo--no-regrets monkey ends)
2019 (message "Oop ack!")
2020 (let* ((as-pos (gnugo--as-pos-func))
2021 (mnum (gnugo--tree-mnum tree))
2022 (mem (aref monkey 0))
2023 (bidx (aref monkey 1))
2024 (end (aref ends bidx))
2025 (ucolor (gnugo-get :user-color))
2026 (gcolor (gnugo-other ucolor))
2027 (uprop (if (gnugo--blackp ucolor)
2029 (cl-flet ((mvno (node) (gethash node mnum)))
2033 (+ 2 (mvno (car mem))))
2034 with (node move todo)
2038 move (gnugo--move-prop node))
2039 (when (and move (>= ok (mvno node)))
2040 (let ((userp (eq uprop (car move))))
2041 (push (list (if userp ucolor gcolor)
2043 (funcall as-pos (cdr move)))
2045 until (eq mem (cdr ls))
2048 for (color userp pos) in todo
2050 (gnugo--play-stone color pos)
2051 (gnugo-push-move userp pos)
2055 (defun gnugo-display-final-score ()
2056 "Display final score and other info in another buffer (when game over).
2057 If the game is still ongoing, Emacs asks if you wish to stop play (by
2058 making sure two \"pass\" moves are played consecutively, if necessary).
2059 Also, add the `:RE' SGF property to the root node of the game tree."
2061 (let ((game-over (gnugo-get :game-over)))
2062 (unless (or game-over
2063 (and (not (gnugo-get :waitingp))
2064 (y-or-n-p "Game still in play. Stop play now? ")))
2065 (user-error "Sorry, game still in play"))
2069 (message "Playing PASS for %s ..."
2070 (gnugo-get (if userp :user-color :gnugo-color)))
2072 (gnugo-push-move userp "PASS")))
2077 (let ((b= " Black = ")
2079 (res (when (string= "resign" (gnugo-move-history 'car))
2080 (gnugo-get :last-mover)))
2084 (format "%s wins.\n"
2085 (substring (if (= ?b (aref res 0)) w= b=)
2087 "The game is over.\n"
2088 (format "Resignation by %s.\n" res))
2089 result (concat (upcase (substring (gnugo-other res) 0 1))
2091 (message "Computing final score ...")
2092 (let* ((g-over (gnugo-get :game-over))
2093 (live (cdr (assq 'live g-over)))
2094 (dead (cdr (assq 'dead g-over)))
2095 (seed (gnugo-get :scoring-seed))
2096 (terr-q (format "final_status_list %%s_territory %d" seed))
2099 (b-terr (gnugo--count-query terr-q "black"))
2100 (w-terr (gnugo--count-query terr-q "white"))
2101 (b-capt (string-to-number (gnugo-get :black-captures)))
2102 (w-capt (string-to-number (gnugo-get :white-captures)))
2103 (komi (gnugo--root-prop :KM)))
2104 (setq blurb (list "The game is over. Final score:\n")
2105 result (gnugo-query "final_score %d" seed))
2106 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2107 (dolist (group live)
2108 (incf (if (gnugo--blackp (caar group))
2111 (length (cdr group))))
2112 (dolist (group dead)
2113 (incf (if (gnugo--blackp (caar group))
2116 (length (cdr group))))
2117 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2118 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2119 w-terr terr komi 'komi (+ w-terr komi))
2122 (dolist (group dead)
2123 (incf (if (gnugo--blackp (caar group))
2126 (* 2 (length (cdr group)))))
2127 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2132 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2136 (+ w-terr w-capt komi))
2138 (push (if (string= "0" result)
2139 "The game is a draw.\n"
2140 (format "%s wins by %s.\n"
2141 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2142 (substring result 2)))
2144 (message "Computing final score ... done")))
2146 (let ((beg (gnugo-get :game-start-time))
2147 (end (gnugo-get :game-end-time)))
2151 ((yep (pretty moment)
2152 (push (format-time-string
2153 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2156 (yep "Game start" beg)
2158 (setq blurb (apply 'concat (nreverse blurb)))
2159 (gnugo--set-root-prop :RE result)
2160 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2164 (defun gnugo-quit ()
2165 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2166 If the game is not over, ask for confirmation first."
2168 (if (or (gnugo-get :game-over)
2169 (y-or-n-p "Quit? "))
2171 (message "(not quitting)")))
2173 (defun gnugo-leave-me-alone ()
2174 "Kill the current buffer unconditionally."
2178 (defun gnugo-fancy-undo (count)
2179 "Rewind the game tree in various ways.
2180 Prefix arg COUNT means to undo that many moves.
2181 Otherwise, undo repeatedly up to and including the move
2182 which placed the stone at point."
2185 ;; TODO: Move this into `gnugo-magic-undo' proper.
2186 (cond ((numberp count) count)
2187 ((consp count) (car count))
2188 (t (gnugo-position)))))
2190 (defun gnugo-toggle-image-display-command () ; ugh
2191 "Toggle use of images to display the board, then refresh."
2193 (gnugo-toggle-image-display)
2194 (save-excursion (gnugo-refresh)))
2196 (defun gnugo-describe-position ()
2197 "Display the board position under cursor in the echo area.
2198 If there a stone at that position, also display its move number."
2200 (let ((pos (gnugo-position)) ; do first (can throw)
2201 (color (case (following-char)
2208 with monkey = (gnugo-get :monkey)
2209 with tree = (gnugo-get :sgf-gametree)
2210 with mnum = (gnugo--tree-mnum tree)
2211 with as-cc = (gnugo--as-cc-func)
2212 with fruit = (cons color (funcall as-cc pos))
2213 for node in (aref monkey 0)
2214 if (member fruit node)
2216 (format " (move %d)"
2217 (gethash node mnum))
2222 (defun gnugo-switch-to-another ()
2223 "Switch to another GNU Go game buffer (if any)."
2225 (loop for buf in (cdr (buffer-list))
2226 if (gnugo-board-buffer-p buf)
2229 (switch-to-buffer buf))
2230 finally do (message "(only one)")))
2232 ;;;---------------------------------------------------------------------------
2233 ;;; Command properties and gnugo-command
2235 ;; GTP commands entered by the user are never issued directly to GNU Go;
2236 ;; instead, their behavior and output are controlled by the property
2237 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2238 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2240 ;; :full -- completely interpret the command string; the value is a
2241 ;; func that takes the list of words derived from splitting the
2242 ;; command string (minus the command) and handles everything.
2244 ;; :output -- either a keyword specifying the preferred output method:
2245 ;; :message -- show output in minibuffer
2246 ;; :discard -- sometimes you just don't care;
2247 ;; or a function that takes one arg, the output string, and
2248 ;; handles it completely. default is to switch to buffer
2249 ;; "*gnugo command output*" if the output has a newline,
2250 ;; otherwise use `message'.
2252 ;; :post-thunk -- run after output processing (at the very end).
2254 (defun gnugo-command (command)
2255 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2256 Output and Emacs behavior depend on which command is given (some
2257 commands are handled completely by Emacs w/o using the subprocess;
2258 some commands have their output displayed in specially prepared
2259 buffers or in the echo area; some commands are instrumented to do
2260 gnugo.el-specific housekeeping).
2262 For example, for the command \"help\", Emacs visits the
2263 GTP command reference info page.
2265 NOTE: At this time, GTP command handling specification is still
2266 incomplete. Thus, some commands WILL confuse gnugo.el."
2267 (interactive "sCommand: ")
2268 (if (string= "" command)
2269 (message "(no command given)")
2270 (let* ((split (split-string command))
2271 (cmd (intern (car split)))
2272 (spec (get cmd :gnugo-gtp-command-spec))
2273 (full (plist-get spec :full)))
2275 (funcall full (cdr split))
2276 (message "Doing %s ..." command)
2277 (let* ((ans (gnugo--q command))
2278 (where (plist-get spec :output)))
2279 (if (string-match "unknown.command" ans)
2281 (cond ((functionp where) (funcall where ans))
2282 ((eq :discard where) (message ""))
2283 ((or (eq :message where)
2284 (not (string-match "\n" ans)))
2286 (t (switch-to-buffer "*gnugo command output*")
2289 (message "Doing %s ... done." command)))
2290 (let ((thunk (plist-get spec :post-thunk)))
2291 (when thunk (funcall thunk)))))))))
2293 ;;;---------------------------------------------------------------------------
2294 ;;; Major mode for interacting with a GNUGO subprocess
2296 (put 'gnugo-board-mode 'mode-class 'special)
2297 (defun gnugo-board-mode ()
2298 "Major mode for playing GNU Go.
2299 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2300 In this mode, keys do not self insert.
2302 \\{gnugo-board-mode-map}"
2303 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2304 (buffer-disable-undo) ; todo: undo undo undoing
2305 (kill-all-local-variables)
2306 (use-local-map gnugo-board-mode-map)
2307 (set (make-local-variable 'font-lock-defaults)
2308 '(gnugo-font-lock-keywords t))
2309 (setq major-mode 'gnugo-board-mode
2310 mode-name "GNUGO Board"
2312 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2313 (set (make-local-variable 'gnugo-state)
2314 (gnugo--mkht :size (1- 42)))
2315 (add-to-invisibility-spec :nogrid)
2316 (mapc (lambda (prop)
2317 (gnugo-put prop nil)) ; todo: separate display/game aspects;
2318 '(:game-over ; move latter to func `gnugo'
2325 :display-using-images
2329 (let ((name (if (string-match "[ ]" gnugo-program)
2330 (let ((p (substring gnugo-program 0 (match-beginning 0)))
2331 (o (substring gnugo-program (match-end 0)))
2332 (h (or (car gnugo-option-history) "")))
2333 (when (string-match "--mode" o)
2334 (user-error "Found \"--mode\" in `gnugo-program'"))
2335 (when (and o (cl-plusp (length o))
2336 h (cl-plusp (length o))
2337 (or (< (length h) (length o))
2338 (not (string= (substring h 0 (length o))
2340 (push (concat o " " h) gnugo-option-history))
2343 (args (read-string "GNU Go options: "
2344 (car gnugo-option-history)
2345 'gnugo-option-history))
2347 board-size user-color handicap komi minus-l infile)
2348 (loop for (var default opt rx)
2349 in '((board-size 19 "--boardsize")
2350 (user-color "black" "--color" "\\(black\\|white\\)")
2351 (handicap 0 "--handicap")
2353 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
2354 (infile nil "--infile" "[ ]*[^ ]+"))
2356 (or (when (string-match opt args)
2357 (let ((start (match-end 0)) s)
2358 (string-match (or rx "[0-9.]+") args start)
2359 (setq s (match-string 0 args))
2360 (if rx s (string-to-number s))))
2362 (gnugo-put :user-color user-color)
2363 (let ((proc-args (split-string args)))
2364 (gnugo-put :proc-args proc-args)
2365 (gnugo-put :proc (setq proc (apply 'start-process "gnugo"
2366 (current-buffer) name
2367 "--mode" "gtp" "--quiet"
2369 (set-process-sentinel proc 'gnugo-sentinel)
2370 ;; Emacs is too protective sometimes, blech.
2371 (set-process-query-on-exit-flag proc nil)
2372 (when (or minus-l infile)
2374 in '((board-size "query_boardsize")
2376 (handicap "get_handicap"))
2377 do (set prop (string-to-number (gnugo-query q)))))
2378 (gnugo-put :diamond (substring (process-name proc) 5))
2379 (gnugo-put :gnugo-color (gnugo-other user-color))
2380 (gnugo-put :highlight-last-move-spec
2381 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2382 (gnugo-put :lparen-ov (make-overlay 1 1))
2383 (gnugo-put :rparen-ov (let ((ov (make-overlay 1 1)))
2384 (overlay-put ov 'display ")")
2386 (let* ((coll (gnugo/sgf-create "(;FF[4]GM[1])" t))
2388 (gnugo-put :sgf-gametree tree)
2389 (gnugo-put :sgf-collection coll)
2390 (gnugo-put :monkey (vector (aref (gnugo--tree-ends tree) 0) 0)))
2391 (gnugo--SZ! board-size)
2392 (loop with gb = (gnugo--blackp (gnugo-other user-color))
2393 for (property value mogrifyp) in
2395 (:DT ,(format-time-string "%Y-%m-%d"))
2396 (:RU ,(if (string-match "--chinese-rules" args)
2399 (:AP ("gnugo.el" . ,gnugo-version))
2401 (,(if gb :PW :PB) ,(user-full-name))
2402 (,(if gb :PB :PW) ,(concat "GNU Go " (gnugo-query "version")))
2403 ,@(when (not (zerop handicap))
2405 (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
2407 do (gnugo-note property value mogrifyp)))
2408 (gnugo-put :waiting-start (current-time))
2411 (run-hooks 'gnugo-board-mode-hook)
2414 ;;;---------------------------------------------------------------------------
2418 (defun gnugo (&optional new-game)
2419 "Run gnugo in a buffer, or resume a game in progress.
2420 Prefix arg means skip the game-in-progress check and start a new
2422 \\<gnugo-board-mode-map>
2423 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2425 You are queried for additional command-line options (Emacs supplies
2426 \"--mode gtp --quiet\" automatically). Here is a list of options
2427 that gnugo.el understands and handles specially:
2429 --boardsize num Set the board size to use (5--19)
2430 --color <color> Choose your color ('black' or 'white')
2431 --handicap <num> Set the number of handicap stones (0--9)
2433 If there is already a game in progress you may resume it instead of
2434 starting a new one. See `gnugo-board-mode' documentation for more info."
2436 (let* ((all (let (acc)
2437 (dolist (buf (buffer-list))
2438 (when (gnugo-board-buffer-p buf)
2439 (push (cons (buffer-name buf) buf) acc)))
2442 (if (and (not new-game)
2444 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2445 (if (= 1 n) "" "s"))))
2450 (let ((sel (completing-read "Which one? " all nil t)))
2451 (if (string= "" sel)
2453 (assoc sel all))))))
2454 ;; set up a new board
2456 (let ((half (truncate (1+ (gnugo-get :SZ)) 2)))
2457 (gnugo-goto-pos (format "A%d" half))
2458 (forward-char (* 2 (1- half)))
2459 (gnugo-put :last-user-bpos
2460 (gnugo-put :center-position
2461 (get-text-property (point) 'gnugo-position))))
2463 (gnugo-put :game-start-time (current-time))
2464 (let ((g (gnugo-get :gnugo-color))
2465 (n (or (gnugo--root-prop :HA) 0))
2466 (u (gnugo-get :user-color)))
2467 (gnugo-put :last-mover g)
2468 (when (or (and (gnugo--blackp u) (< 1 n))
2469 (and (gnugo--blackp g) (< n 2)))
2470 (gnugo-put :last-mover u)
2472 (gnugo-get-move g))))))
2474 ;;;---------------------------------------------------------------------------
2475 ;;; Load-time actions
2477 (unless gnugo-frolic-mode-map
2478 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2479 (suppress-keymap gnugo-frolic-mode-map)
2480 (mapc (lambda (pair)
2481 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2482 '(("q" . gnugo-frolic-quit)
2483 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2484 ("\C-b" . gnugo-frolic-backward-branch)
2485 ("\C-f" . gnugo-frolic-forward-branch)
2486 ("\C-p" . gnugo-frolic-previous-move)
2487 ("\C-n" . gnugo-frolic-next-move)
2488 ("j" . gnugo-frolic-exchange-left)
2489 ("J" . gnugo-frolic-rotate-left)
2490 ("k" . gnugo-frolic-exchange-right)
2491 ("K" . gnugo-frolic-rotate-right)
2492 ("\C-m" . gnugo-frolic-set-as-main-line)
2493 ("\C-\M-p" . gnugo-frolic-prune-branch)
2494 ("o" . gnugo-frolic-return-to-origin))))
2496 (unless gnugo-board-mode-map
2497 (setq gnugo-board-mode-map (make-sparse-keymap))
2498 (suppress-keymap gnugo-board-mode-map)
2499 (mapc (lambda (pair)
2500 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2501 '(("?" . describe-mode)
2502 ("\C-m" . gnugo-move)
2505 ("R" . gnugo-resign)
2507 ("Q" . gnugo-leave-me-alone)
2508 ("U" . gnugo-fancy-undo)
2509 ("\M-u" . gnugo-undo-one-move)
2510 ("u" . gnugo-undo-two-moves)
2511 ("\C-?" . gnugo-undo-two-moves)
2514 ("\C-l" . gnugo-refresh)
2515 ("\M-_" . gnugo-boss-is-near)
2516 ("_" . gnugo-boss-is-near)
2517 ("h" . gnugo-move-history)
2518 ("L" . gnugo-frolic-in-the-leaves)
2519 ("i" . gnugo-toggle-image-display-command)
2520 ("w" . gnugo-worm-stones)
2521 ("W" . gnugo-worm-data)
2522 ("d" . gnugo-dragon-stones)
2523 ("D" . gnugo-dragon-data)
2524 ("t" . gnugo-toggle-dead-group)
2525 ("g" . gnugo-toggle-grid)
2526 ("!" . gnugo-estimate-score)
2527 (":" . gnugo-command)
2528 (";" . gnugo-command)
2529 ("=" . gnugo-describe-position)
2530 ("s" . gnugo-write-sgf-file)
2531 ("\C-x\C-s" . gnugo-write-sgf-file)
2532 ("\C-x\C-w" . gnugo-write-sgf-file)
2533 ("l" . gnugo-read-sgf-file)
2534 ("F" . gnugo-display-final-score)
2535 ("A" . gnugo-switch-to-another)
2537 ([(down-mouse-1)] . gnugo-mouse-move)
2538 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2539 ([(down-mouse-3)] . gnugo-mouse-pass)
2540 ;; delving into the curiosities
2541 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2543 (unless (get 'help :gnugo-gtp-command-spec)
2545 ((sget (x) (get x :gnugo-gtp-command-spec))
2546 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2547 (plist-put (sget cmd) prop val)))
2548 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2551 (jam cmd (car ls) (cadr ls))
2552 (setq ls (cddr ls)))))))
2553 (cl-macrolet ((deffull (who &body body)
2554 (declare (indent 1))
2555 `(defgtp ',who :full (lambda (sel)
2559 (info "(gnugo)GTP command reference")
2560 (when sel (setq sel (intern (car sel))))
2561 (let (buffer-read-only pad cur spec output found)
2563 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2564 (goto-char (point-min))
2566 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2569 (setq pad (make-string (- (match-beginning 1)
2570 (match-beginning 0))
2574 (get (setq cur (intern (match-string 1)))
2575 :gnugo-gtp-command-spec))
2577 (note "handles this command completely"))
2578 (when (setq output (plist-get spec :output))
2579 (if (functionp output)
2580 (note "handles the output specially")
2582 (:discard (note "discards the output"))
2583 (:message (note "displays the output in the echo area")))))
2585 (setq found (match-beginning 0))))))
2586 (cond (found (goto-char found))
2588 (t (message "(no such command: %s)" sel)))))
2590 (deffull final_score
2591 ;; Explicit ignorance avoids byte-compiler warning.
2593 (gnugo-display-final-score))
2599 :post-thunk (lambda ()
2600 (gnugo--unclose-game)
2601 (gnugo-put :last-mover nil)
2603 (gnugo--SZ! (string-to-number
2605 "query_boardsize")))
2609 (gnugo-read-sgf-file (car sel)))
2611 (deffull (undo gg-undo)
2615 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2616 (t (car sel)))))))))
2621 ;;;---------------------------------------------------------------------------
2622 ;;; The remainder of this file defines a simplified SGF-handling library.
2623 ;;; When/if it should start to attain generality, it should be split off into
2624 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2625 ;;; "gnugo/" prefix.
2627 (defconst gnugo/sgf-*r4-properties*
2628 '((AB "Add Black" setup list stone)
2629 (AE "Add Empty" game list point)
2630 (AN "Annotation" game simpletext)
2631 (AP "Application" root (simpletext . simpletext))
2632 (AR "Arrow" - list (point . point))
2633 (AS "Who adds stones" - simpletext) ; (LOA)
2634 (AW "Add White" setup list stone)
2635 (B "Black" move move)
2636 (BL "Black time left" move real)
2637 (BM "Bad move" move double)
2638 (BR "Black rank" game simpletext)
2639 (BT "Black team" game simpletext)
2640 (C "Comment" - text)
2641 (CA "Charset" root simpletext)
2642 (CP "Copyright" game simpletext)
2643 (CR "Circle" - list point)
2644 (DD "Dim points" - elist point) ; (inherit)
2645 (DM "Even position" - double)
2646 (DO "Doubtful" move none)
2647 (DT "Date" game simpletext)
2648 (EV "Event" game simpletext)
2649 (FF "Fileformat" root [number (1 . 4)])
2650 (FG "Figure" - (or none (number . simpletext)))
2651 (GB "Good for Black" - double)
2652 (GC "Game comment" game text)
2653 (GM "Game" root [number (1 . 20)])
2654 (GN "Game name" game simpletext)
2655 (GW "Good for White" - double)
2656 (HA "Handicap" game number) ; (Go)
2657 (HO "Hotspot" - double)
2658 (IP "Initial pos." game simpletext) ; (LOA)
2659 (IT "Interesting" move none)
2660 (IY "Invert Y-axis" game simpletext) ; (LOA)
2661 (KM "Komi" game real) ; (Go)
2663 (LB "Label" - list (point . simpletext))
2664 (LN "Line" - list (point . point))
2665 (MA "Mark" - list point)
2666 (MN "set move number" move number)
2667 (N "Nodename" - simpletext)
2668 (OB "OtStones Black" move number)
2669 (ON "Opening" game text)
2670 (OT "Overtime" game simpletext)
2671 (OW "OtStones White" move number)
2672 (PB "Player Black" game simpletext)
2673 (PC "Place" game simpletext)
2674 (PL "Player to play" setup color)
2675 (PM "Print move mode" - number) ; (inherit)
2676 (PW "Player White" game simpletext)
2677 (RE "Result" game simpletext)
2678 (RO "Round" game simpletext)
2679 (RU "Rules" game simpletext)
2680 (SE "Markup" - point) ; (LOA)
2681 (SL "Selected" - list point)
2682 (SO "Source" game simpletext)
2683 (SQ "Square" - list point)
2684 (ST "Style" root [number (0 . 3)])
2685 (SU "Setup type" game simpletext) ; (LOA)
2686 (SZ "Size" root (or number (number . number)))
2687 (TB "Territory Black" - elist point) ; (Go)
2688 (TE "Tesuji" move double)
2689 (TM "Timelimit" game real)
2690 (TR "Triangle" - list point)
2691 (TW "Territory White" - elist point) ; (Go)
2692 (UC "Unclear pos" - double)
2693 (US "User" game simpletext)
2695 (VW "View" - elist point) ; (inherit)
2696 (W "White" move move)
2697 (WL "White time left" move real)
2698 (WR "White rank" game simpletext)
2699 (WT "White team" game simpletext)
2700 (LT "Lose on time" setup simpletext))
2701 ;; r4-specific notes
2702 ;; - changed: DT FG LB RE RU SZ
2703 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2704 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2706 (defun gnugo/sgf-create (file-or-data &optional data-p)
2707 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2708 FILE-OR-DATA is a file name or SGF[4] data.
2709 Optional arg DATA-P non-nil means FILE-OR-DATA is
2710 a string containing SGF[4] data.
2711 A collection is a list of gametrees, each a vector of four elements:
2713 ENDS -- a vector of node lists, with shared tails
2714 (last element of all the lists is the root node)
2716 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2717 have a move number of the previous \"move\" node (or zero)
2719 ROOT -- the root node"
2720 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2721 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2722 (put 'gnugo/sgf-*r4-properties* :keywords
2723 (mapcar (lambda (full)
2725 (intern (format ":%s" (car full)))))
2726 gnugo/sgf-*r4-properties*))))
2727 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2728 (put 'gnugo/sgf-*r4-properties* :specs
2729 (mapcar (lambda (full)
2730 (cons (car full) (cdddr full)))
2731 gnugo/sgf-*r4-properties*))))
2734 ((sw () (skip-chars-forward " \t\n"))
2735 (x (end preserve-whitespace)
2738 (:end (lambda (char) (= ?\] char)))
2739 (:mid (lambda (char) (= ?\: char)))
2740 (t (lambda (char) (or (= ?\: char)
2743 (while (not (funcall endp (setq c (following-char))))
2749 ((unless preserve-whitespace
2750 (looking-at "\\s-+"))
2751 (delete-region (point) (match-end 0))
2753 (t (forward-char 1))))
2754 (buffer-substring-no-properties beg (point))))
2755 (one (type end) (let ((s (progn
2757 (x end (eq 'text type)))))
2760 ;; blech, begone bu"tt"-ugly blatherings
2761 ;; (but bide brobdingnagian boards)...
2762 (if (and (string= "tt" s)
2767 ((simpletext color) s)
2768 ((number real double) (string-to-number s))
2771 (t (error "Unhandled type: %S" type)))))
2772 (val (spec) (cond ((symbolp spec)
2775 ;; todo: check range here.
2776 (one (aref spec 0) :end))
2777 ((eq 'or (car spec))
2778 (let ((v (one (cadr spec) t)))
2779 (if (= ?\] (following-char))
2782 ;; todo: this assumes `spec' has the form
2783 ;; (or foo (foo . bar))
2784 ;; i.e., foo is not rescanned. e.g., `SZ'.
2785 ;; probably this assumption is consistent
2786 ;; w/ the SGF authors' desire to make the
2787 ;; parsing easy, but you never know...
2788 (cons v (one (cdaddr spec) :end)))))
2789 (t (cons (one (car spec) :mid)
2790 (one (cdr spec) :end)))))
2791 (short (who) (when (eobp)
2792 (error "Unexpected EOF while reading %s" who)))
2793 (atvalp () (= ?\[ (following-char)))
2794 (PROP () (let (name spec ltype)
2795 (sw) (short 'property)
2796 (when (looking-at "[A-Z]")
2797 (setq name (read (current-buffer))
2798 spec (cdr (assq name specs)))
2801 (cdr (assq name keywords))
2802 (prog1 (if (= 1 (length spec))
2804 (unless (memq (setq ltype (car spec))
2806 (error "Bad spec: %S" spec))
2807 (if (and (eq 'elist ltype) (sw)
2810 (let ((type (cadr spec))
2812 (while (and (sw) (atvalp)
2813 (setq mo (val type)))
2818 (forward-char 1))))))
2819 (morep () (and (sw) (not (eobp))))
2820 (seek (c) (and (morep) (= c (following-char))))
2821 (seek-into (c) (when (seek c)
2824 (NODE () (when (seek-into ?\;)
2826 while (setq prop (PROP))
2828 (when (eq :SZ (car prop))
2829 (setq SZ (cdr prop)))
2838 (puthash node (+ (if (gnugo--move-prop node)
2841 (gethash prev mnum 0))
2846 (if (not (seek ?\())
2850 (loop while (seek ?\()
2851 append (TREE ls mnum)))
2855 (insert-file-contents file-or-data)
2856 (insert file-or-data)
2857 (goto-char (point-min)))
2859 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2860 (ends (TREE nil mnum))
2861 (root (car (last (car ends)))))
2862 (vector (apply 'vector ends)
2866 (defun gnugo/sgf-write-file (collection filename)
2867 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2868 (me (cons "gnugo.el" gnugo-version))
2869 (specs (mapcar (lambda (full)
2870 (cons (intern (format ":%s" (car full)))
2872 gnugo/sgf-*r4-properties*))
2875 ((esc (composed fmt arg)
2876 (mapconcat (lambda (c)
2878 ;; ‘?\[’ is not strictly required
2879 ;; but neither is it forbidden.
2880 ((?\[ ?\] ?\\) (format "\\%c" c))
2881 (?: (concat (if composed "\\" "") ":"))
2883 (string-to-list (format fmt arg))
2885 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2886 (>>two (v) (insert "["
2887 (esc t "%s" (car v))
2889 (esc t "%s" (cdr v))
2891 (>>nl () (cond ((memq name aft-newline-appreciated)
2893 ((< 60 (current-column))
2901 (insert (substring (symbol-name name) 1))
2904 (setq spec (cdr (assq name specs)))
2908 (let ((>> (if (consp (cadr spec))
2911 (dolist (little-v v)
2913 (funcall >> little-v)
2920 (loop initially (insert ";")
2924 (unless (zerop (current-column))
2928 (funcall (if (gnugo--nodep x)
2934 (dolist (tree collection)
2935 ;; take responsibility for our actions
2936 (gnugo--set-root-prop :AP me tree)
2938 (let ((ht (gnugo--mkht))
2939 (leaves (append (gnugo--tree-ends tree) nil)))
2943 with rh ; rectified history
2944 with bp ; branch point
2946 until (setq bp (gethash node ht))
2948 (push node rh) ; good for now: ½τ
2952 ;; first run: main line
2954 ;; subsequent runs: grafts (value discarded)
2956 ;; Maintain order of ‘leaves’.
2957 (let ((was (cdr bp)))
2958 (if (gnugo--nodep (car was))
2962 (setq tree (hang (pop leaves)))
2963 (mapc #'hang leaves)
2966 (write-file filename)))))
2968 ;;; gnugo.el ends here