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 (destructuring-bind (&optional color . suggestion)
369 "Not your turn yet"))))
370 (gnugo--gate-game-over in-progress-p))
372 (defun gnugo-sentinel (proc string)
373 (let ((status (process-status proc)))
374 (when (memq status '(exit signal))
375 (let ((buf (process-buffer proc)))
376 (when (buffer-live-p buf)
377 (with-current-buffer buf
378 (setq mode-line-process
380 (propertize (car (split-string string))
381 'face 'font-lock-warning-face)
383 (when (eq proc (gnugo-get :proc))
384 (gnugo--forget :proc))))))))
386 (defun gnugo--begin-exchange (proc filter line)
387 (declare (indent 2)) ; good time, for a rime
388 ; nice style, for a wile...
389 (set-process-filter proc filter)
390 (process-send-string proc line)
391 (process-send-string proc "\n"))
393 (defun gnugo--q (fmt &rest args)
394 "Send formatted command \"FMT ARGS...\"; wait for / return response.
395 The response is a string whose first two characters indicate the
396 status of the command. See also `gnugo-query'."
397 (let ((slow (gnugo-get :waiting))
398 (proc (gnugo-get :proc)))
400 (user-error "Sorry, still waiting for %s to %s"
401 (car slow) (if (cdr slow)
402 "receive a suggestion"
404 (process-put proc :incomplete t)
405 (process-put proc :srs "") ; synchronous return stash
406 (gnugo--begin-exchange
407 proc (lambda (proc string)
408 (let ((full (concat (process-get proc :srs)
410 (process-put proc :srs full)
411 (unless (numberp (gnugo--compare-strings
412 full (max 0 (- (length full)
415 (process-put proc :incomplete nil))))
418 (apply #'format fmt args)))
419 (while (process-get proc :incomplete)
420 (accept-process-output proc 30))
421 (prog1 (substring (process-get proc :srs) 0 -2)
422 (process-put proc :srs ""))))
424 (defun gnugo--q/ue (fmt &rest args)
425 (let ((ans (apply 'gnugo--q fmt args)))
426 (unless (= ?= (aref ans 0))
427 (user-error "%s" ans))
430 (defun gnugo-query (message-format &rest args)
431 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
432 Return a string that omits the first two characters (corresponding
433 to the status indicator in the Go Text Protocol). Use this function
434 when you are sure the command cannot fail."
435 (substring (apply 'gnugo--q message-format args)
438 (defun gnugo--nquery (cmd)
439 (string-to-number (gnugo-query cmd)))
441 (defun gnugo-lsquery (message-format &rest args)
442 (split-string (apply 'gnugo-query message-format args)))
444 (defsubst gnugo--count-query (fmt &rest args)
445 (length (apply 'gnugo-lsquery fmt args)))
447 (defsubst gnugo--root-prop (prop &optional tree)
448 (cdr (assq prop (gnugo--root-node tree))))
450 (defun gnugo--set-root-prop (prop value &optional tree)
451 (let* ((root (gnugo--root-node tree))
452 (cur (assq prop root)))
455 (push (cons prop value)
456 (cdr (last root))))))
458 (defun gnugo-goto-pos (pos)
459 "Move point to board position POS, a letter-number string."
460 (goto-char (point-min))
461 (forward-line (- (1+ (gnugo-get :SZ))
462 (string-to-number (substring pos 1))))
464 (forward-char (+ (if (= 32 (following-char)) 1 2)
465 (* 2 (- (let ((letter (aref pos 0)))
471 (defun gnugo-f (frag)
472 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
474 (defun gnugo-yang (c)
475 (cdr (assq c '((?+ . hoshi)
477 (?X . (bmoku . bpmoku))
478 (?O . (wmoku . wpmoku))))))
480 (defun gnugo-yy (yin yang &optional momentaryp)
481 (gnugo-f (format "%d-%s"
482 yin (cond ((and (consp yang) momentaryp) (cdr yang))
483 ((consp yang) (car yang))
486 (defun gnugo-toggle-image-display ()
487 (unless (and (fboundp 'display-images-p) (display-images-p))
488 (user-error "Display does not support images, sorry"))
489 (require 'gnugo-xpms)
490 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
491 (user-error "Could not load `gnugo-xpms', sorry"))
492 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
493 (unless (eq fresh (gnugo-get :xpms))
494 (gnugo-put :xpms fresh)
495 (gnugo--forget :all-yy)))
496 (let* ((new (not (gnugo-get :display-using-images)))
497 (act (if new 'display 'do-not-display)))
499 (setcar (symbol-plist yy) act))
500 (or (gnugo-get :all-yy)
502 (prog1 (mapcar (lambda (ent)
504 (yy (gnugo-yy (cdr k) (car k))))
505 (setplist yy `(not-yet ,(cdr ent)))
509 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
511 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
512 (gnugo-put :highlight-last-move-spec
515 (get (gnugo-yy (get-text-property p 'gnugo-yin)
516 (get-text-property p 'gnugo-yang)
520 (gnugo-get :default-highlight-last-move-spec)))
521 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
522 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
523 (mapc 'delete-overlay (cdar group))
524 (setcdr (car group) nil))
525 (gnugo-put :mul (if new
528 (gnugo-put :display-using-images new)))
530 (defun gnugo-toggle-grid ()
531 "Turn the grid around the board on or off."
533 (funcall (if (memq :nogrid buffer-invisibility-spec)
534 'remove-from-invisibility-spec
535 'add-to-invisibility-spec)
537 (save-excursion (gnugo-refresh)))
539 (defun gnugo-propertize-board-buffer ()
541 (insert (substring (gnugo--q "showboard") 3))
542 (let* ((grid-props (list 'invisible :nogrid
543 'font-lock-face gnugo-grid-face))
544 (%gpad (gnugo-f 'gpad))
545 (%gspc (gnugo-f 'gspc))
546 (%lpad (gnugo-f 'lpad))
547 (%rpad (gnugo-f 'rpad))
548 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
549 (size (gnugo-get :SZ))
550 (size-string (number-to-string size)))
551 (goto-char (point-min))
552 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
553 (skip-chars-forward " ")
554 (put-text-property (1- (point)) (point) 'category %gpad)
555 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
557 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
558 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
559 (let* ((row (match-string-no-properties 1))
561 (other-edge (+ edge (* 2 size) -1))
562 (right-empty (+ other-edge (length row) 1))
563 (top-p (string= size-string row))
564 (bot-p (string= "1" row)))
565 (let* ((nL (- edge 1 (length size-string)))
567 (ov (make-overlay nL nR (current-buffer) t)))
568 (add-text-properties nL nR grid-props)
569 ;; We redundantly set `invisible' in the overlay to workaround
570 ;; a display bug whereby text *following* the overlaid text is
571 ;; displayed with the face of the overlaid text, but only when
572 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
573 ;; This has something to do w/ the bletcherous `before-string'.
574 (overlay-put ov 'invisible :nogrid)
575 (overlay-put ov 'category %lpad))
576 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
578 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
579 (truncate (- p edge) 2))
581 (yin (let ((A-p (= edge p))
582 (Z-p (= (1- other-edge) p)))
583 (cond ((and top-p A-p) 1)
592 (yang (gnugo-yang (char-after p))))
593 (add-text-properties p (1+ p)
603 (gnugo-position gnugo-yin))))
604 (unless (= (1- other-edge) p)
605 (add-text-properties (1+ p) (+ 2 p) ispc-props)
606 (put-text-property p (+ 2 p) 'intangible ival)))
607 (add-text-properties (1+ other-edge) right-empty grid-props)
608 (goto-char right-empty)
609 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
610 (let ((prop (if (string= "WH" (match-string 1))
613 (beg (match-beginning 2))
615 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
616 (gnugo-put prop (match-string-no-properties 2))))
618 (put-text-property right-empty (point) 'category %rpad)
620 (add-text-properties (1- (point)) (point-max) grid-props)
621 (skip-chars-forward " ")
622 (put-text-property (1- (point)) (point) 'category %gpad)
623 (put-text-property (point) (progn (end-of-line) (point))
626 (defun gnugo-merge-showboard-results ()
627 (let ((aft (substring (gnugo--q "showboard") 3))
628 (adj 1) ; string to buffer position adjustment
630 (sync "[0-9]* stones$")
631 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
632 ;; restrictive a condition that fails in the case of:
635 ;; ... WHITE has captured 1 stones
638 ;; ... WHITE has captured 14 stones
641 ;; where the after count has more digits than the before count,
642 ;; but shares the same leading digits. In this case, the result
643 ;; of `compare-strings' points to the SPC following the before
644 ;; count (indicated by caret in this example).
646 (bef (buffer-substring-no-properties (point-min) (point-max)))
647 (bef-start 0) (bef-idx 0)
648 (aft-start 0) (aft-idx 0)
649 aft-sync-backtrack mis inc cut new very-strange
651 (inhibit-read-only t))
652 (while (numberp (setq mis (gnugo--compare-strings
655 (setq aft-sync-backtrack nil
656 inc (if (cl-minusp mis)
659 bef-idx (+ bef-start inc)
660 aft-idx (+ aft-start inc)
661 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
664 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
665 (let ((peek (1- aft-idx)))
666 (while (not (= 32 (aref aft peek)))
667 (setq peek (1- peek)))
668 (setq aft-sync-backtrack (1+ peek))))
672 (if aft-sync-backtrack
673 (- aft-sync-backtrack aft-idx)
676 (if aft-sync-backtrack
677 (let* ((asb aft-sync-backtrack)
678 (l-p (get-text-property cut :gnugo-cf))
681 (keep (text-properties-at cut)))
682 (setq new (substring aft asb (string-match " " aft asb)))
683 (plist-put keep :gnugo-cf (cons (length new) capprop))
684 (gnugo-put capprop new)
685 (delete-char old-len)
686 (insert (apply 'propertize new keep))
687 (incf adj (- (length new) old-len)))
688 (setq new (aref aft aft-idx))
689 (insert-and-inherit (char-to-string new))
690 (let ((yin (get-text-property cut 'gnugo-yin))
691 (yang (gnugo-yang new)))
692 (add-text-properties cut (1+ cut)
696 ,(gnugo-yy yin yang))))
698 ;; do this last to avoid complications w/ font lock
699 ;; (this also means we cannot include `intangible' in `front-sticky')
700 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
701 (put-text-property cut (1+ cut) 'intangible very-strange))))))
703 (defsubst gnugo--move-prop (node)
707 (defun gnugo--as-pos-func ()
708 (lexical-let ((size (gnugo-get :SZ)))
713 (let ((col (aref cc 0)))
715 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
716 (- size (- (aref cc 1) ?a))))))))
718 (defun gnugo-move-history (&optional rsel color)
719 "Determine and return the game's move history.
720 Optional arg RSEL controls side effects and return value.
721 If nil, display the history in the echo area as \"(N moves)\"
722 followed by the space-separated list of moves. When called
723 interactively with a prefix arg (i.e., RSEL is `(4)'), display
724 similarly, but suffix with the mover (either \":B\" or \":W\").
725 RSEL may also be a symbol that selects what to return:
726 car -- the most-recent move
727 cadr -- the next-to-most-recent move
728 two -- the last two moves as a list, oldest last
729 bpos -- the last stone on the board placed by COLOR
730 For all other values of RSEL, do nothing and return nil."
732 (let* ((monkey (gnugo-get :monkey))
733 (mem (aref monkey 0))
734 (as-pos (gnugo--as-pos-func))
737 ((as-pos-maybe (x) (if (string= "resign" x)
740 (remem () (setq node (pop mem)
741 mprop (gnugo--move-prop node)))
742 (pretty () (setq move (as-pos-maybe (cdr mprop))))
743 (next (byp) (when (remem)
746 (format "%s%s" move (car mprop))
750 (tell () (message "(%d moves) %s"
752 (mapconcat 'identity (nreverse acc) " ")))
753 (finish (byp) (while mem (next byp)) (tell)))
758 (`cadr (nn) (car (nn)))
760 (`bpos (loop with prop = (gnugo--prop<-color color)
762 (eq prop (car mprop))
764 (not (string= "resign" move))
765 (not (gnugo--passp move)))
769 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
770 "A special mode for manipulating a GNUGO gametree.
772 \\{gnugo-frolic-mode-map}"
773 (setq truncate-lines t)
774 (buffer-disable-undo))
776 (defun gnugo-frolic-quit ()
777 "Kill GNUGO Frolic buffer and switch to its parent buffer."
779 (let ((bye (current-buffer)))
780 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
781 gnugo-frolic-parent-buffer))
784 (defun gnugo-frolic-return-to-origin ()
785 "Move point to the board's current position."
787 (if (not gnugo-frolic-origin)
788 (message "No origin")
789 (goto-char gnugo-frolic-origin)
790 (recenter (- (count-lines (line-beginning-position)
793 (defun gnugo-frolic-in-the-leaves ()
794 "Display the game tree in a *GNUGO Frolic* buffer.
795 This looks something like:
798 2 W -- K10 K10 K10 K10
817 with 0, 1, ... N (in this case N is 3) in the header line
818 to indicate the branches. Branch 0 is the \"main line\".
819 Point (* in this example) indicates the current position,
820 \"!\" indicates comment properties (e.g., B8, branch 1),
821 and moves not actually on the game tree (e.g., E7, branch 3)
822 are dimmed. Type \\[describe-mode] in that buffer for details."
824 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
826 (from (or gnugo-frolic-parent-buffer
828 ;; todo: use defface once we finally succumb to ‘customize’
829 (dimmed-node-face (list :inherit 'default
830 :foreground "gray50"))
831 (tree (gnugo-get :sgf-gametree))
832 (ends (copy-sequence (gnugo--tree-ends tree)))
833 (mnum (gnugo--tree-mnum tree))
836 (width (length ends))
837 (lanes (number-sequence 0 (1- width)))
838 (monkey (gnugo-get :monkey))
839 (as-pos (gnugo--as-pos-func))
840 (at (car (aref monkey 0)))
841 (bidx (aref monkey 1))
842 (valid (map 'vector (lambda (end)
843 (gethash (car end) mnum))
845 (max-move-num (apply 'max (append valid nil)))
846 (inhibit-read-only t)
852 (propertize s 'face face))
853 (fsi (properties fmt &rest args)
854 (insert (apply 'propertize
855 (apply 'format fmt args)
862 for node in (aref ends bx)
863 do (if (setq fork (on node))
866 ;; todo: ignore non-"move" nodes
867 (eq node (car (aref ends bix))))
869 (pushnew other (gethash node soil))))
874 (puthash node bx seen))
877 (switch-to-buffer buf)
880 (setq header-line-format
881 (lexical-let ((full (concat
883 (mapconcat (lambda (n)
893 `(space :width ,w))))
895 (when (eq 'left scroll-bar-mode)
896 (let ((w (or scroll-bar-width
898 nil 'scroll-bar-width)))
899 (cw (frame-char-width)))
903 (let ((fc (fringe-columns 'left t)))
907 (substring full (window-hscroll))
909 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
910 (set (make-local-variable 'gnugo-state)
911 (buffer-local-value 'gnugo-state from))
915 from max-move-num downto 1
916 do (setq props (list 'n n))
921 (goto-char (point-min))
924 n (aref ["W" "B"] (logand 1 n))))
926 do (let* ((node (unless (< (aref valid bx) n)
927 ;; todo: ignore non-"move" nodes
928 (pop (aref ends bx))))
929 (zow (list* 'bx bx props))
933 (cdr (assq :C node))))
934 (s (cond ((not node) "")
935 ((not (setq move (gnugo--move-prop node))) "-")
936 (t (funcall as-pos (cdr move))))))
939 (push 'help-echo zow))
940 (when (and ok (setq br (gethash node soil)))
941 (push (cons bx (sort br '<))
946 (cond ((and (eq at node)
949 (setq finish (point-marker)))
950 (emph s (list :inherit 'default
951 :foreground (frame-parameter
952 nil 'cursor-color))))
954 (emph s dimmed-node-face))
957 (when (progn (fsi props "\n")
958 (setq forks (nreverse forks)))
959 (let* ((margin (make-string 11 ?\s))
960 (heads (mapcar #'car forks))
961 (tails (mapcar #'cdr forks)))
963 ((spaced (lanes func)
964 (mapconcat func lanes " "))
965 ;; live to play ~ ~ ()
966 ;; play to learn (+) (-) . o O
967 ;; learn to live --ttn .M. _____U
968 (dashed (lanes func) ;;; _____ ^^^^
969 (mapconcat func lanes "-----"))
971 (spaced lanes (lambda (bx)
975 (pad-unless (condition)
986 do (let* ((one (car ls))
989 (mapcar 'car (cdr ls))
991 (apply 'append (mapcar 'cdr bef))))
994 (end (car (last ord))))
996 ((also (b e) (cnxn (number-sequence b e)
1001 (pad-unless (zerop beg))
1002 (dashed (number-sequence beg end)
1004 (cond ((memq bx ord) "+")
1007 (pad-unless (>= end width))
1008 (also (1+ end) (1- width))
1011 (edge (apply 'append tails))
1012 (aa2u (line-beginning-position
1013 (- (1+ (length forks))))
1016 (set (make-local-variable 'gnugo-frolic-origin) finish)
1017 (gnugo-frolic-return-to-origin))))
1019 (defun gnugo--awake (how)
1020 ;; Valid HOW elements:
1021 ;; require-valid-branch
1023 ;; (line . move-string)
1024 ;; Invalid elements blissfully ignored. :-D
1025 (let* ((tree (gnugo-get :sgf-gametree))
1026 (ends (gnugo--tree-ends tree))
1027 (width (length ends))
1028 (monkey (gnugo-get :monkey))
1029 (line (case (cdr (assq 'line how))
1031 (count-lines (point-min) (line-beginning-position)))
1034 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1037 (col (current-column))
1038 (a (unless (> 10 col)
1039 (let ((try (/ (- col 10)
1041 (unless (<= width try)
1044 (when (memq 'require-valid-branch how)
1046 (user-error "No branch here")))
1047 (loop with omit = (cdr (assq 'omit how))
1048 for (name . value) in `((line . ,line)
1049 (bidx . ,(aref monkey 1))
1054 do (unless (memq name omit)
1058 (defmacro gnugo--awakened (how &rest body)
1059 (declare (indent 1))
1060 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1062 for name in '(line bidx monkey
1065 do (unless (memq name omit)
1068 (gnugo--awake ',how)
1071 (defsubst gnugo--move-to-bcol (bidx)
1072 (move-to-column (+ 10 (* 6 bidx))))
1074 (defun gnugo--swiz (direction &optional blunt)
1075 (gnugo--awakened (require-valid-branch
1078 (let* ((b (cond ((numberp blunt)
1079 (unless (and (< -1 blunt)
1081 (user-error "No such branch: %s" blunt))
1083 (t (mod (+ direction a) width))))
1084 (flit (if blunt (lambda (n)
1089 (mod (+ direction n) width))))
1090 (was (copy-sequence ends))
1091 (new-bidx (funcall flit bidx)))
1092 (loop for bx below width
1093 do (aset ends (funcall flit bx)
1095 (unless (= new-bidx bidx)
1096 (aset monkey 1 new-bidx))
1097 (gnugo-frolic-in-the-leaves)
1098 (goto-char (point-min))
1100 (gnugo--move-to-bcol b))))
1102 (defun gnugo-frolic-exchange-left ()
1103 "Exchange the current branch with the one to its left."
1107 (defun gnugo-frolic-rotate-left ()
1108 "Rotate all branches left."
1112 (defun gnugo-frolic-exchange-right ()
1113 "Exchange the current branch with the one to its right."
1117 (defun gnugo-frolic-rotate-right ()
1118 "Rotate all branches right."
1122 (defun gnugo-frolic-set-as-main-line ()
1123 "Make the current branch the main line."
1125 (gnugo--swiz nil 0))
1127 (defun gnugo-frolic-prune-branch ()
1128 "Remove the current branch from the gametree.
1129 This fails if there is only one branch in the tree.
1130 This fails if the monkey is on the current branch
1131 \(a restriction that will probably be lifted Real Soon Now\)."
1133 (gnugo--awakened (require-valid-branch
1134 (line . move-string))
1135 ;; todo: define meaningful eviction semantics; remove restriction
1137 (user-error "Cannot prune with monkey on branch"))
1139 (user-error "Cannot prune last remaining branch"))
1140 (let ((new (append ends nil)))
1141 ;; Explicit ignorance avoids byte-compiler warning.
1142 (ignore (pop (nthcdr a new)))
1143 (gnugo--set-tree-ends tree new))
1145 (aset monkey 1 (decf bidx)))
1146 (gnugo-frolic-in-the-leaves)
1148 (goto-char (point-min))
1149 (search-forward line)
1150 (gnugo--move-to-bcol (min a (- width 2))))))
1152 (defun gnugo--sideways (backwards n)
1153 (gnugo--awakened ((omit tree ends monkey bidx line))
1154 (gnugo--move-to-bcol (mod (if backwards
1159 (defun gnugo-frolic-backward-branch (&optional n)
1160 "Move backward N (default 1) branches."
1162 (gnugo--sideways t n))
1164 (defun gnugo-frolic-forward-branch (&optional n)
1165 "Move forward N (default 1) branches."
1167 (gnugo--sideways nil n))
1169 (defun gnugo--vertical (n direction)
1172 direction (- direction)))
1173 (gnugo--awakened ((line . numeric)
1174 (omit tree ends width monkey bidx))
1175 (let ((stop (if (> 0 direction)
1177 (max 0 (1- (count-lines (point-min)
1181 (loop while (not (= line stop))
1183 (forward-line direction)
1184 (incf line direction))
1185 until (get-text-property (point) 'n))
1186 until (zerop (decf n)))
1188 (gnugo--move-to-bcol a)
1189 (move-to-column col)))))
1191 (defun gnugo-frolic-previous-move (&optional n)
1192 "Move to the Nth (default 1) previous move."
1194 (gnugo--vertical n -1))
1196 (defun gnugo-frolic-next-move (&optional n)
1197 "Move to the Nth (default 1) next move."
1199 (gnugo--vertical n 1))
1201 (defun gnugo-boss-is-near ()
1202 "Do `bury-buffer' until the current one is not a GNU Board."
1204 (while (gnugo-board-buffer-p)
1207 (defsubst gnugo--passp (string)
1208 (string= "PASS" string))
1210 (defsubst gnugo--no-regrets (monkey ends)
1211 (eq (aref ends (aref monkey 1))
1214 (defun gnugo--as-cc-func ()
1215 (lexical-let ((size (gnugo-get :SZ)))
1217 (let* ((col (aref pos 0))
1218 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1219 (two (+ ?a (- size (string-to-number
1220 (substring pos 1))))))
1221 (format "%c%c" one two)))))
1223 (defsubst gnugo--decorate (node alist)
1224 ;; NB: ALIST should not have :B or :W keys.
1225 (setcdr (last node) alist))
1227 (defun gnugo-close-game (end-time resign)
1228 (gnugo-put :game-end-time end-time)
1229 (let ((now (or end-time (current-time))))
1230 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1232 (gnugo-put :game-over
1233 (if (or (eq t resign)
1234 (and (stringp resign)
1235 (string-match "[BW][+][Rr]esign" resign)))
1237 ((ls (color) (mapcar
1242 (gnugo-query "worm_stones %s" color)
1244 (let ((live (append (ls "black") (ls "white"))))
1247 (let ((dd (gnugo-query "dragon_data"))
1248 (start 0) mem color ent live dead)
1249 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1251 (setq mem (match-string 1 dd)
1252 color (match-string 2 dd)
1254 ent (cons (list color)
1255 (sort (gnugo-lsquery "dragon_stones %s" mem)
1257 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1259 (if (match-string 2 dd)
1262 (setq start (match-end 0)))
1266 (defun gnugo--unclose-game ()
1267 (gnugo--forget :game-over ; all those in -close-game
1270 (let* ((root (gnugo--root-node))
1271 (cur (assq :RE root)))
1273 (assert (not (eq cur (car root))) nil
1274 ":RE at head of root node: %S"
1278 (defun gnugo-push-move (who move)
1279 (let* ((simple (booleanp who))
1280 (ucolor (gnugo-get :user-color))
1284 (gnugo-get :gnugo-color))
1286 (start (gnugo-get :waiting-start))
1287 (now (current-time))
1288 (resignp (string= "resign" move))
1289 (passp (gnugo--passp move))
1290 (head (gnugo-move-history 'car))
1291 (onep (and head (gnugo--passp head)))
1292 (donep (or resignp (and onep passp))))
1294 (gnugo--q/ue "play %s %s" color move))
1296 (gnugo-merge-showboard-results))
1297 (gnugo-put :last-mover color)
1300 (string= ucolor color))
1301 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1302 ;; update :sgf-gametree and :monkey
1303 (let* ((property (gnugo--prop<-color color))
1304 (pair (cons property (cond (resignp move)
1306 (t (funcall (gnugo--as-cc-func)
1309 (monkey (gnugo-get :monkey))
1310 (mem (aref monkey 0))
1312 (tree (gnugo-get :sgf-gametree))
1313 (ends (gnugo--tree-ends tree))
1314 (mnum (gnugo--tree-mnum tree))
1315 (count (length ends))
1316 (tip-move-num (gethash tip mnum))
1317 (bidx (aref monkey 1)))
1318 ;; Detect déjà-vu. That is, when placing "A", avoid:
1324 ;; (such "variations" do not actually vary!) in favor of:
1330 ;; This linear search loses for multiple ‘old’ w/ "A",
1331 ;; a very unusual (but not invalid, sigh) situation.
1335 ;; Start with latest / highest likelihood for hit.
1336 ;; (See "to the right" comment, below.)
1337 from (if (gnugo--no-regrets monkey ends)
1341 if (setq bx (mod (+ bidx i) count)
1344 for m on (aref ends bx)
1345 while (< tip-move-num
1346 (gethash (setq node (car m))
1350 (when (equal pair (assq property node))
1358 (rotatef (aref ends bidx)
1360 (setq mem previous))
1364 (unless (gnugo--no-regrets monkey ends)
1365 (setq ends (gnugo--set-tree-ends
1366 tree (let ((ls (append ends nil)))
1367 ;; copy old to the right of new
1368 (push mem (nthcdr bidx ls))
1370 (puthash fruit (1+ (gethash tip mnum)) mnum)
1372 (aset ends bidx mem)))
1373 (setf (aref monkey 0) mem))
1375 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1377 (gnugo-close-game now resignp))
1378 (gnugo-put :waiting-start (and (not donep) now))
1381 (defun gnugo-venerate (yin yang)
1382 (let* ((fg-yy (gnugo-yy yin yang))
1383 (fg-disp (or (get fg-yy 'display)
1384 (get fg-yy 'do-not-display)))
1385 (fg-data (plist-get (cdr fg-disp) :data))
1386 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1387 (bg-disp (or (get bg-yy 'display)
1388 (get bg-yy 'do-not-display)))
1389 (bg-data (plist-get (cdr bg-disp) :data))
1393 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1394 (setq start (match-end 0))
1395 (string-to-number (match-string 1 s)))))
1396 (while (and (not (cl-minusp ncolors))
1397 (string-match ",\n" s start))
1398 (setq start (match-end 0)
1399 ncolors (1- ncolors)))
1400 (string-match "\"" s start)
1402 (new (copy-sequence fg-data))
1403 (lx (length fg-data))
1404 (sx (funcall bop fg-data))
1405 (sb (funcall bop bg-data))
1406 (color-key (aref new sx))) ; blech, heuristic
1408 (when (and (not (= color-key (aref new sx)))
1409 (cl-plusp (random 4)))
1410 (aset new sx (aref bg-data sb)))
1413 (create-image new 'xpm t :ascent 'center)))
1415 (defun gnugo-refresh (&optional nocache)
1416 "Update GNUGO Board buffer display.
1417 While a game is in progress, parenthesize the last-played stone (no parens
1418 for pass). If the buffer is currently displayed in the selected window,
1419 recenter the board (presuming there is extra space in the window). Update
1420 the mode line. Lastly, move point to the last position played by the user,
1421 if that move was not a pass.
1423 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1424 be slow. (This should normally be unnecessary; specify it only if the display
1425 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1428 (let* ((last-mover (gnugo-get :last-mover))
1429 (other (gnugo-other last-mover))
1430 (move (gnugo-move-history 'car))
1431 (game-over (gnugo-get :game-over))
1432 (inhibit-read-only t)
1434 (when (and nocache (not (gnugo-get :waiting)))
1435 (gnugo-propertize-board-buffer))
1438 (destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1439 (if (member move '("PASS" "resign"))
1440 (mapc 'delete-overlay (list l-ov r-ov))
1441 (gnugo-goto-pos move)
1443 (hspec (gnugo-get :highlight-last-move-spec))
1444 (display-value (nth 0 hspec))
1445 (l-offset (nth 1 hspec))
1446 (l-new-pos (+ p l-offset))
1447 (r-action (nth 2 hspec)))
1448 (overlay-put l-ov 'display
1449 (if (functionp display-value)
1450 (funcall display-value p)
1452 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1454 (funcall r-action r-ov)
1455 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1457 (rename-buffer (concat (gnugo-get :diamond)
1459 (format "%s(game over)"
1460 (if (string= move "resign")
1461 (concat move "ation ")
1463 (format "%s(%s to play)"
1464 (if move (concat move " ") "")
1468 (let ((live (cdr (assq 'live game-over)))
1469 (dead (cdr (assq 'dead game-over)))
1471 (unless (eq game-over (get-text-property 1 'game-over))
1472 (dolist (group (append live dead))
1473 (dolist (pos (cdr group))
1474 (gnugo-goto-pos pos)
1476 (put-text-property p (1+ p) 'group group)))
1477 (put-text-property 1 2 'game-over game-over))
1478 (dolist (group live)
1479 (when (setq pall (cdar group))
1480 (mapc 'delete-overlay pall)
1481 (setcdr (car group) nil)))
1482 (dolist (group dead)
1483 (unless (cdar group)
1484 (let (ov pall c (color (caar group)))
1485 (setq c (if (gnugo--blackp color) "x" "o"))
1486 (dolist (pos (cdr group))
1487 (gnugo-goto-pos pos)
1488 (setq p (point) ov (make-overlay p (1+ p)))
1491 (if (gnugo-get :display-using-images)
1492 ;; respect the dead individually; it takes more time
1493 ;; but that's not a problem (for them)
1494 (gnugo-venerate (get-text-property p 'gnugo-yin)
1495 (gnugo-yang (aref (upcase c) 0)))
1496 (propertize c 'face 'font-lock-warning-face)))
1498 (setcdr (car group) pall))))))
1500 (when (setq window (get-buffer-window (current-buffer)))
1501 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1502 (size (gnugo-get :SZ))
1503 (under10p (< size 10))
1504 (mul (gnugo-get :mul))
1505 (h (- (truncate (- (window-height window)
1510 (edges (window-edges window))
1511 (right-w-edge (nth 2 edges))
1512 (avail-width (- right-w-edge (nth 0 edges)))
1514 (imagesp (symbol-plist (gnugo-f 'ispc)))
1515 (w (/ (- avail-width
1520 2 ; between board and grid
1525 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1526 `(display ,(make-string h 10))
1527 '(invisible :nogrid)))
1532 (cond (imagesp (+ (* 0.5 wmul)
1538 (gspc . ,(when imagesp
1542 ;; DWR: image width alone => OBOE!
1544 ;; NB: ‘(* wmul cw)’ is the same
1545 ;; as ‘(car (image-size ... t))’.
1546 (let ((cw (frame-char-width)))
1547 (/ (+ 1.0 (* wmul cw))
1550 (lpad . ,(let ((d `(display (space :align-to ,w))))
1551 ;; We distinguish between these cases to
1552 ;; workaround a display bug whereby the
1553 ;; `before-string' is omitted entirely (not
1554 ;; rendered) when interacting w/ the text
1555 ;; mode last-move left-paren for moves in
1559 ,(apply 'propertize " " d))
1562 (space :align-to ,(1- avail-width))))))
1563 (setplist (gnugo-f (car pair)) (cdr pair)))))
1565 (let ((cur (gnugo-get :mode-line)))
1566 (unless (equal cur gnugo-mode-line)
1567 (setq cur gnugo-mode-line)
1568 (gnugo-put :mode-line cur)
1569 (gnugo-put :mode-line-form
1570 (cond ((stringp cur)
1571 (setq cur (copy-sequence cur))
1573 (while (setq cut (string-match "~[bwpmtu]" cur))
1575 (setq c (aref cur (incf cut)))
1578 `(,(intern (format "squig-%c" c))
1580 (?b '(or (gnugo-get :black-captures) 0))
1581 (?w '(or (gnugo-get :white-captures) 0))
1582 (?p '(gnugo-current-player))
1583 (?t '(let ((ws (gnugo-get :waiting-start)))
1585 (cadr (time-since ws))
1587 (?u '(or (gnugo-get :last-waiting) "-"))
1588 (?m '(let ((tree (gnugo-get :sgf-gametree))
1589 (monkey (gnugo-get :monkey)))
1590 (gethash (car (aref monkey 0))
1591 (gnugo--tree-mnum tree)
1592 ;; should be unnecessary
1595 `(let ,(delete-dups (copy-sequence acc))
1596 (format ,cur ,@(reverse (mapcar 'car acc))))))
1598 (let ((form (gnugo-get :mode-line-form)))
1599 (setq mode-line-process
1601 ;; this dynamicism is nice but excessive in its wantonness
1602 ;;- `(" [" (:eval ,form) "]")
1603 ;; this dynamicism is ok because the user triggers it
1604 (list (format " [%s]" (eval form))
1605 '(:eval (if (gnugo-get :abd)
1608 (force-mode-line-update))
1610 (when (setq last (gnugo-get :last-user-bpos))
1611 (gnugo-goto-pos last))))
1613 (defun gnugo--finish-move (buf)
1614 (run-hooks 'gnugo-post-move-hook)
1615 (with-current-buffer buf
1618 ;;;---------------------------------------------------------------------------
1619 ;;; Game play actions
1621 (defun gnugo--rename-buffer-portion (&optional back)
1622 (let ((old "to play")
1623 (new "waiting for suggestion"))
1626 (let ((name (buffer-name)))
1627 (when (string-match old name)
1628 (rename-buffer (replace-match new t t name))))))
1630 (defun gnugo-get-move-insertion-filter (proc string)
1631 (with-current-buffer (process-buffer proc)
1632 (let* ((so-far (gnugo-get :get-move-string))
1633 (full (gnugo-put :get-move-string (concat so-far string))))
1634 (when (string-match "^= \\(.+\\)\n\n" full)
1635 (setq full (match-string 1 full)) ; POS or "PASS"
1636 (destructuring-bind (color . suggestion)
1637 (gnugo-get :waiting)
1638 (gnugo--forget :get-move-string
1642 (gnugo--rename-buffer-portion t)
1643 (unless (or (gnugo--passp full)
1644 (eq 'nowarp suggestion))
1645 (gnugo-goto-pos full))
1646 (message "%sSuggestion for %s: %s"
1647 (gnugo-get :diamond)
1649 (let* ((donep (gnugo-push-move color full))
1650 (buf (current-buffer)))
1651 (gnugo--finish-move buf)
1652 (when (gnugo-get :abd)
1656 2 ;;; sec (frettoloso? dubioso!)
1657 nil (lambda (buf color)
1658 (with-current-buffer buf
1659 (gnugo-get-move color)))
1661 (gnugo-other color))))))))))))
1663 (defun gnugo-get-move (color &optional suggestion)
1664 (gnugo-put :waiting (cons color suggestion))
1665 (gnugo--begin-exchange
1666 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1667 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1668 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1669 (concat "reg_genmove " color))
1670 (accept-process-output))
1672 (defun gnugo-cleanup ()
1673 (when (gnugo-board-buffer-p)
1674 (unless (zerop (buffer-size))
1675 (message "Thank you for playing GNU Go."))
1677 (setplist sym nil) ; "...is next to fordliness." --Huxley
1678 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1679 ;; No worries, things will be Much Better w/ structs, RSN...
1681 (append (gnugo-get :all-yy)
1690 (setq gnugo-state nil)))
1692 (defun gnugo-position ()
1693 (or (get-text-property (point) 'gnugo-position)
1694 (user-error "Not a proper position point")))
1696 (defun gnugo-request-suggestion (&optional nowarp)
1697 "Request a move suggestion from GNU Go.
1698 After some time (during which you can do other stuff),
1699 Emacs displays the suggestion in the echo area and warps the
1700 cursor to the suggested position. Prefix arg inhibits warp."
1703 (gnugo--rename-buffer-portion)
1704 (gnugo-get-move (gnugo-current-player)
1709 (defun gnugo--user-play (pos-or-pass)
1711 ;; The "user" in this func's name used to signify both
1712 ;; who does the action and for whom the action is done.
1713 ;; Now, it signifies only the former.
1714 (let* ((gcolor (gnugo-get :gnugo-color))
1715 (userp (string= gcolor (gnugo-get :last-mover)))
1716 (donep (gnugo-push-move userp pos-or-pass))
1717 (buf (current-buffer)))
1718 (gnugo--finish-move buf)
1719 (when (and userp (not donep))
1720 (with-current-buffer buf
1721 (gnugo-get-move gcolor)))))
1723 (defun gnugo-move ()
1724 "Make a move on the GNUGO Board buffer.
1725 The position is computed from current point.
1726 Signal error if done out-of-turn or if game-over.
1727 To start a game try M-x gnugo."
1729 (gnugo--user-play (gnugo-position)))
1731 (defun gnugo-mouse-move (e)
1732 "Do `gnugo-move' at mouse location."
1735 (when (memq (following-char) '(?. ?+))
1738 (defun gnugo-pass ()
1739 "Make a pass on the GNUGO Board buffer.
1740 Signal error if done out-of-turn or if game-over.
1741 To start a game try M-x gnugo."
1743 (gnugo--user-play "PASS"))
1745 (defun gnugo-mouse-pass (e)
1746 "Do `gnugo-pass' at mouse location."
1751 (defun gnugo-resign ()
1754 (if (not (y-or-n-p "Resign? "))
1755 (message "(not resigning)")
1756 (gnugo-push-move t "resign")
1759 (defun gnugo-animate-group (w/d)
1760 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1761 (let* ((pos (gnugo-position))
1762 (orig-b-m-p (buffer-modified-p))
1764 (unless (memq (following-char) '(?X ?O))
1765 (user-error "No stone at %s" pos))
1766 (setq blurb (message "Computing %s stones ..." w/d)
1767 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1768 (message "%s %s in group." blurb (length stones))
1769 (setplist (gnugo-f 'anim) nil)
1770 (let* ((spec (if (gnugo-get :display-using-images)
1771 (loop with yin = (get-text-property (point) 'gnugo-yin)
1772 with yang = (gnugo-yang (following-char))
1773 with up = (get (gnugo-yy yin yang t) 'display)
1774 with dn = (get (gnugo-yy yin yang) 'display)
1775 for n below (length gnugo-animation-string)
1776 collect (if (zerop (logand 1 n))
1778 (split-string gnugo-animation-string "" t)))
1780 (ovs (save-excursion
1781 (mapcar (lambda (pos)
1782 (gnugo-goto-pos pos)
1784 (ov (make-overlay p (1+ p))))
1785 (overlay-put ov 'category (gnugo-f 'anim))
1786 (overlay-put ov 'priority most-positive-fixnum)
1789 (setplist (gnugo-f 'anim) (cons 'display cell))
1790 (while (and (cdr spec) ; let last linger lest levity lost
1791 (sit-for 0.08675309)) ; jenny jenny i got your number...
1792 (setcar cell (setq spec (cdr spec)))
1793 ;; Force redisplay of overlays.
1794 (set-buffer-modified-p orig-b-m-p))
1796 (mapc 'delete-overlay ovs)
1799 (defun gnugo-display-group-data (command buffer-name)
1800 (message "Computing %s ..." command)
1801 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1802 (switch-to-buffer buffer-name)
1805 (message "Computing %s ... done." command))
1807 (defun gnugo-worm-stones ()
1808 "In the GNUGO Board buffer, animate \"worm\" at current position.
1809 Signal error if done out-of-turn or if game-over.
1810 See variable `gnugo-animation-string' for customization."
1813 (gnugo-animate-group 'worm))
1815 (defun gnugo-worm-data ()
1816 "Display in another buffer data from \"worm\" at current position.
1817 Signal error if done out-of-turn or if game-over."
1820 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1822 (defun gnugo-dragon-stones ()
1823 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1824 Signal error if done out-of-turn or if game-over.
1825 See variable `gnugo-animation-string' for customization."
1828 (gnugo-animate-group 'dragon))
1830 (defun gnugo-dragon-data ()
1831 "Display in another buffer data from \"dragon\" at current position.
1832 Signal error if done out-of-turn or if game-over."
1835 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1837 (defun gnugo-estimate-score ()
1838 "Display estimated score of a game of GNU Go.
1839 Output includes number of stones on the board and number of stones
1840 captured by each player, and the estimate of who has the advantage (and
1841 by how many stones)."
1843 (message "Est.score ...")
1844 (let ((black (gnugo--count-query "list_stones black"))
1845 (white (gnugo--count-query "list_stones white"))
1846 (black-captures (gnugo-query "captures black"))
1847 (white-captures (gnugo-query "captures white"))
1848 (est (gnugo-query "estimate_score")))
1849 ;; might as well update this
1850 (gnugo-put :black-captures black-captures)
1851 (gnugo-put :white-captures white-captures)
1852 (message "Est.score ... B %s %s | W %s %s | %s"
1853 black black-captures white white-captures est)))
1855 (defun gnugo-write-sgf-file (filename)
1856 "Save the game history to FILENAME (even if unfinished).
1857 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1858 (interactive "FWrite game as SGF file: ")
1859 (when (and (file-exists-p filename)
1860 (not (y-or-n-p "File exists. Continue? ")))
1861 (user-error "Not writing %s" filename))
1862 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1863 (set-buffer-modified-p nil))
1865 (defun gnugo--who-is-who (wait play samep)
1866 (message "GNU Go %splays as %s, you as %s (%s)"
1867 (if samep "" "now ")
1870 "NOTE: this is a switch!")))
1872 (defsubst gnugo--nodep (x)
1873 (keywordp (caar x)))
1875 (defun gnugo--SZ! (size)
1876 (gnugo-put :SZ size)
1877 (gnugo-put :center-position
1878 (funcall (gnugo--as-pos-func)
1879 (let ((c (+ -1 ?a (truncate (1+ size) 2))))
1882 (defun gnugo--plant-and-climb (collection &optional sel)
1883 (gnugo-put :sgf-collection collection)
1884 (let ((tree (nth (or sel 0) collection)))
1885 (gnugo-put :sgf-gametree tree)
1886 (gnugo-put :monkey (vector
1888 (aref (gnugo--tree-ends tree) 0)
1893 (defun gnugo-read-sgf-file (filename)
1894 "Load the first game tree from FILENAME, a file in SGF format."
1895 (interactive "fSGF file to load: ")
1896 (when (file-directory-p filename)
1897 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1898 (let (play wait samep coll tree game-over)
1899 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1900 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1901 (setq play (gnugo--q/ue "loadsgf %s" (expand-file-name filename))
1902 wait (gnugo-other play)
1903 samep (string= (gnugo-get :user-color) play))
1904 (gnugo-put :last-mover wait)
1906 (gnugo-put :gnugo-color wait)
1907 (gnugo-put :user-color play))
1908 (setq coll (gnugo/sgf-create filename)
1909 tree (gnugo--plant-and-climb
1910 coll (let ((n (length coll)))
1914 ;; (let* ((q (format "Which game? (1-%d)" n))
1915 ;; (choice (1- (read-number q 1))))
1916 ;; (if (and (< -1 choice) (< choice n))
1918 ;; (message "(Selecting the first game)")
1920 ;; but this is what we use (for now) to accomodate
1921 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1923 (message "(Selecting the first game)"))
1925 ;; This is deliberately undocumented for now.
1926 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1927 (when (setq game-over (or (gnugo--root-prop :RE tree)
1928 (when (equal '("PASS" "PASS")
1929 (gnugo-move-history 'two))
1931 (gnugo-close-game nil game-over))
1932 (gnugo-put :last-user-bpos
1933 (gnugo-move-history 'bpos (gnugo-get :user-color)))
1935 (set-buffer-modified-p nil)
1936 (gnugo--who-is-who wait play samep)))
1938 (defun gnugo--mem-with-played-stone (pos &optional noerror)
1939 (let ((color (case (following-char)
1944 (user-error "No stone at %s" pos))
1945 (loop with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
1946 for mem on (aref (gnugo-get :monkey) 0)
1947 when (equal fruit (caar mem))
1949 finally return nil))))
1951 (defun gnugo--climb-towards-root (spec &optional noalt keep)
1953 (let* ((user-color (gnugo-get :user-color))
1954 (monkey (gnugo-get :monkey))
1955 (tree (gnugo-get :sgf-gametree))
1956 (ends (gnugo--tree-ends tree))
1957 (remorseful (not (gnugo--no-regrets monkey ends)))
1958 (stop (if (numberp spec)
1959 (nthcdr (if (zerop spec)
1960 (if (string= (gnugo-get :last-mover)
1966 (let* ((pos (if (stringp spec)
1969 (hmm (gnugo--mem-with-played-stone pos)))
1970 ;; todo: relax ‘gnugo--user-play’ then lift restriction
1971 (unless (eq (gnugo--prop<-color user-color)
1972 (car (gnugo--move-prop (car hmm))))
1973 (user-error "%s not occupied by %s"
1976 (when (gnugo-get :game-over)
1977 (gnugo--unclose-game))
1978 (while (not (eq stop (aref monkey 0)))
1979 (gnugo--q/ue "undo")
1980 (pop (aref monkey 0))
1981 (gnugo-put :last-mover (gnugo-current-player))
1982 (gnugo-merge-showboard-results) ; all
1983 (gnugo-refresh) ; this
1984 (redisplay)) ; eye candy
1985 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1987 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1988 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1990 (gnugo-get :center-position)))
1992 (unless (or keep remorseful)
1993 (aset ends (aref monkey 1) (aref monkey 0)))
1994 (when (and ulastp (not noalt))
1995 (gnugo-get-move (gnugo-get :gnugo-color))))))
1997 (defun gnugo-undo-one-move (&optional me-next)
1998 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1999 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
2000 Prefix arg ME-NEXT means to arrange for you to play
2001 the color of the next move (and GNU Go the opposite).
2002 This is useful after loading an SGF file whose last
2003 move was done by the color you prefer to play:
2004 \\[gnugo-read-sgf-file] FILENAME RET
2005 C-u \\[gnugo-undo-one-move]
2007 See also `gnugo-undo-two-moves'."
2011 (let* ((play (gnugo-get :last-mover))
2012 (wait (gnugo-other play)))
2013 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
2014 (gnugo-put :user-color play)
2015 (gnugo-put :gnugo-color wait)))
2016 (gnugo--climb-towards-root 1 t))
2018 (defun gnugo-undo-two-moves ()
2019 "Undo a pair of moves (GNU Go's and yours).
2020 However, if you are the last mover, undo only one move.
2021 Regardless, after undoing, it is your turn to play again."
2024 (gnugo--climb-towards-root 0))
2026 (defun gnugo-oops (&optional position)
2027 "Like `gnugo-undo-two-moves', but keep the undone moves.
2028 The kept moves become a sub-gametree (variation) when play resumes.
2029 Prefix arg means, instead, undo repeatedly up to and including
2030 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2033 (gnugo--climb-towards-root (unless position
2037 (defun gnugo-okay (&optional full)
2038 "Redo a pair of undone moves.
2039 Prefix arg means to redo all the undone moves."
2042 (let* ((tree (gnugo-get :sgf-gametree))
2043 (ends (gnugo--tree-ends tree))
2044 (monkey (gnugo-get :monkey)))
2045 (if (gnugo--no-regrets monkey ends)
2046 (message "Oop ack!")
2047 (let* ((as-pos (gnugo--as-pos-func))
2048 (mnum (gnugo--tree-mnum tree))
2049 (mem (aref monkey 0))
2050 (bidx (aref monkey 1))
2051 (end (aref ends bidx))
2052 (ucolor (gnugo-get :user-color))
2053 (uprop (gnugo--prop<-color ucolor)))
2054 (cl-flet ((mvno (node) (gethash node mnum)))
2058 (+ 2 (mvno (car mem))))
2059 with (node move todo)
2063 move (gnugo--move-prop node))
2064 (when (and move (>= ok (mvno node)))
2065 (let ((userp (eq uprop (car move))))
2067 (funcall as-pos (cdr move)))
2069 until (eq mem (cdr ls))
2072 for (userp pos) in todo
2074 (gnugo-push-move userp pos)
2078 (defun gnugo-display-final-score (&optional comment)
2079 "Display final score and other info in another buffer (when game over).
2080 If the game is still ongoing, Emacs asks if you wish to stop play (by
2081 making sure two \"pass\" moves are played consecutively, if necessary).
2082 Also, add the `:RE' SGF property to the root node of the game tree.
2083 Prefix arg COMMENT means to also attach the text (slightly compacted)
2084 to the last move, as a comment."
2086 (let ((game-over (gnugo-get :game-over)))
2087 (unless (or game-over
2088 (and (not (gnugo-get :waiting))
2089 (y-or-n-p "Game still in play. Stop play now? ")))
2090 (user-error "Sorry, game still in play"))
2094 (message "Playing PASS for %s ..."
2095 (gnugo-get (if userp :user-color :gnugo-color)))
2097 (gnugo-push-move userp "PASS")))
2102 (let ((b= " Black = ")
2104 (res (when (string= "resign" (gnugo-move-history 'car))
2105 (gnugo-get :last-mover)))
2109 (format "%s wins.\n"
2110 (substring (if (= ?b (aref res 0)) w= b=)
2112 "The game is over.\n"
2113 (format "Resignation by %s.\n" res))
2114 result (concat (upcase (substring (gnugo-other res) 0 1))
2116 (message "Computing final score ...")
2117 (let* ((g-over (gnugo-get :game-over))
2118 (live (cdr (assq 'live g-over)))
2119 (dead (cdr (assq 'dead g-over)))
2120 (seed (gnugo-get :scoring-seed))
2121 (terr-q (format "final_status_list %%s_territory %d" seed))
2124 (b-terr (gnugo--count-query terr-q "black"))
2125 (w-terr (gnugo--count-query terr-q "white"))
2126 (b-capt (string-to-number (gnugo-get :black-captures)))
2127 (w-capt (string-to-number (gnugo-get :white-captures)))
2128 (komi (gnugo--root-prop :KM)))
2129 (setq blurb (list "The game is over. Final score:\n")
2130 result (gnugo-query "final_score %d" seed))
2131 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2132 (dolist (group live)
2133 (incf (if (gnugo--blackp (caar group))
2136 (length (cdr group))))
2137 (dolist (group dead)
2138 (incf (if (gnugo--blackp (caar group))
2141 (length (cdr group))))
2142 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2143 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2144 w-terr terr komi 'komi (+ w-terr komi))
2147 (dolist (group dead)
2148 (incf (if (gnugo--blackp (caar group))
2151 (* 2 (length (cdr group)))))
2152 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2157 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2161 (+ w-terr w-capt komi))
2163 (push (if (string= "0" result)
2164 "The game is a draw.\n"
2165 (format "%s wins by %s.\n"
2166 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2167 (substring result 2)))
2169 (message "Computing final score ... done")))
2171 (let ((beg (gnugo-get :game-start-time))
2172 (end (gnugo-get :game-end-time)))
2176 ((yep (pretty moment)
2177 (push (format-time-string
2178 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2181 (yep "Game start" beg)
2183 (setq blurb (apply 'concat (nreverse blurb)))
2184 (gnugo--set-root-prop :RE result)
2186 (let ((node (car (aref (gnugo-get :monkey) 0))))
2188 (delq (assq :C node) node)
2189 (with-temp-buffer ; lame
2191 (when (search-backward "\n\nGame start:" nil t)
2192 (delete-region (point) (point-max)))
2193 (cl-flet ((rep (old new)
2194 (goto-char (point-min))
2195 (while (search-forward old nil t)
2196 (replace-match new))))
2197 (rep "The game is over. " "")
2198 (rep "territory" "T")
2199 (rep "captures" "C")
2201 `((:C . ,(buffer-string)))))))
2202 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2206 (defun gnugo-quit ()
2207 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2208 If the game is not over, ask for confirmation first."
2210 (if (or (gnugo-get :game-over)
2211 (y-or-n-p "Quit? "))
2213 (message "(not quitting)")))
2215 (defun gnugo-leave-me-alone ()
2216 "Kill the current buffer unconditionally."
2220 (defun gnugo-fancy-undo (count)
2221 "Rewind the game tree in various ways.
2222 Prefix arg COUNT means to undo that many moves.
2223 Otherwise, undo repeatedly up to and including the move
2224 which placed the stone at point."
2226 (gnugo--climb-towards-root
2227 (cond ((numberp count) count)
2228 ((consp count) (car count)))))
2230 (defun gnugo-toggle-image-display-command () ; ugh
2231 "Toggle use of images to display the board, then refresh."
2233 (gnugo-toggle-image-display)
2234 (save-excursion (gnugo-refresh)))
2236 (defsubst gnugo--node-with-played-stone (pos &optional noerror)
2237 (car (gnugo--mem-with-played-stone pos noerror)))
2239 (defun gnugo-describe-position ()
2240 "Display the board position under cursor in the echo area.
2241 If there a stone at that position, also display its move number."
2243 (let* ((pos (gnugo-position)) ; do first (can throw)
2244 (node (gnugo--node-with-played-stone pos t)))
2248 (let* ((tree (gnugo-get :sgf-gametree))
2249 (mnum (gnugo--tree-mnum tree))
2250 (move-num (gethash node mnum)))
2251 (format " (move %d)" move-num)))
2254 (defun gnugo-switch-to-another ()
2255 "Switch to another GNU Go game buffer (if any)."
2257 (loop for buf in (cdr (buffer-list))
2258 if (gnugo-board-buffer-p buf)
2261 (switch-to-buffer buf))
2262 finally do (message "(only one)")))
2264 (defun gnugo-comment (node comment)
2265 "Add to NODE a COMMENT (string) property.
2266 Called interactively, NODE is the one corresponding to the
2267 stone at point, and any previous comment is inserted as the
2268 initial-input (see `read-string').
2270 If COMMENT is nil or the empty string, remove the property entirely."
2272 (let* ((pos (gnugo-position))
2273 (node (gnugo--node-with-played-stone pos)))
2275 (read-string (format "Comment for %s: "
2276 (gnugo-describe-position))
2277 (cdr (assq :C node))))))
2278 (setq node (delq (assq :C node) node))
2279 (unless (zerop (length comment))
2280 (gnugo--decorate node `((:C . ,comment)))))
2282 (defun gnugo-toggle-abdication ()
2283 "Toggle abdication, i.e., letting GNU Go play for you.
2284 When enabled, the mode line includes \"Abd\".
2285 Enabling signals error if the game is over.
2286 When disabling, if GNU Go has already started thinking of
2287 a move to play for you, the thinking is not cancelled but instead
2288 transformed into a move suggestion (see `gnugo-request-suggestion')."
2290 (let ((last-mover (gnugo-get :last-mover))
2291 (abd (gnugo-get :abd))
2295 (let* ((gcolor (gnugo-get :gnugo-color))
2296 (waiting (gnugo-get :waiting))
2297 (userp (string= last-mover gcolor)))
2298 (when (and userp waiting)
2299 (gnugo--rename-buffer-portion)
2300 (setcdr waiting (setq xform 'nowarp)))
2303 (gnugo--forget :abd)
2304 (unless (or userp waiting)
2305 (gnugo-get-move gcolor)))
2309 (gnugo-get-move (gnugo-other last-mover)))
2310 (message "Abdication %sabled%s"
2311 (if (gnugo-get :abd)
2315 (format " (suggestion for %s forthcoming)"
2316 (gnugo-get :user-color))
2321 ;;;---------------------------------------------------------------------------
2322 ;;; Command properties and gnugo-command
2324 ;; GTP commands entered by the user are never issued directly to GNU Go;
2325 ;; instead, their behavior and output are controlled by the property
2326 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2327 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2329 ;; :full -- completely interpret the command string; the value is a
2330 ;; func that takes the list of words derived from splitting the
2331 ;; command string (minus the command) and handles everything.
2333 ;; :output -- either a keyword specifying the preferred output method:
2334 ;; :message -- show output in minibuffer
2335 ;; :discard -- sometimes you just don't care;
2336 ;; or a function that takes one arg, the output string, and
2337 ;; handles it completely. default is to switch to buffer
2338 ;; "*gnugo command output*" if the output has a newline,
2339 ;; otherwise use `message'.
2341 ;; :post-thunk -- run after output processing (at the very end).
2343 (defun gnugo-command (command)
2344 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2345 Output and Emacs behavior depend on which command is given (some
2346 commands are handled completely by Emacs w/o using the subprocess;
2347 some commands have their output displayed in specially prepared
2348 buffers or in the echo area; some commands are instrumented to do
2349 gnugo.el-specific housekeeping).
2351 For example, for the command \"help\", Emacs visits the
2352 GTP command reference info page.
2354 NOTE: At this time, GTP command handling specification is still
2355 incomplete. Thus, some commands WILL confuse gnugo.el."
2356 (interactive "sCommand: ")
2357 (if (string= "" command)
2358 (message "(no command given)")
2359 (let* ((split (split-string command))
2360 (cmd (intern (car split)))
2361 (spec (get cmd :gnugo-gtp-command-spec))
2362 (full (plist-get spec :full)))
2364 (funcall full (cdr split))
2365 (message "Doing %s ..." command)
2366 (let* ((ans (gnugo--q command))
2367 (where (plist-get spec :output)))
2368 (if (string-match "unknown.command" ans)
2370 (cond ((functionp where) (funcall where ans))
2371 ((eq :discard where) (message ""))
2372 ((or (eq :message where)
2373 (not (string-match "\n" ans)))
2375 (t (switch-to-buffer "*gnugo command output*")
2378 (message "Doing %s ... done." command)))
2379 (let ((thunk (plist-get spec :post-thunk)))
2380 (when thunk (funcall thunk)))))))))
2382 ;;;---------------------------------------------------------------------------
2383 ;;; Major mode for interacting with a GNUGO subprocess
2385 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2386 "Major mode for playing GNU Go.
2387 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2388 In this mode, keys do not self insert.
2390 \\{gnugo-board-mode-map}"
2391 (buffer-disable-undo) ; todo: undo undo undoing
2392 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2394 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2395 (set (make-local-variable 'gnugo-state)
2396 (gnugo--mkht :size (1- 42)))
2397 (gnugo-put :highlight-last-move-spec
2398 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2399 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2400 (let ((ov (make-overlay 1 1)))
2401 (overlay-put ov 'display ")")
2403 (gnugo-put :mul '(1 . 1))
2404 (add-to-invisibility-spec :nogrid))
2406 ;;;---------------------------------------------------------------------------
2410 (defun gnugo (&optional new-game)
2411 "Run gnugo in a buffer, or resume a game in progress.
2412 If there is already a game in progress you may resume it instead
2413 of starting a new one. Prefix arg means skip the game-in-progress
2414 check and start a new game straight away.
2416 Before starting, Emacs queries you for additional command-line
2417 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2419 Note that specifying \"--infile FILENAME\" (or, \"-l FILENAME\")
2420 silently clobbers certain other options, such as \"--color\".
2421 For details, see info node `(gnugo) Invoking GNU Go'.
2423 \\<gnugo-board-mode-map>
2424 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2425 See `gnugo-board-mode' for a full list of commands."
2427 (let* ((all (let (acc)
2428 (dolist (buf (buffer-list))
2429 (when (gnugo-board-buffer-p buf)
2430 (push (cons (buffer-name buf) buf) acc)))
2433 (if (and (not new-game)
2435 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2436 (if (= 1 n) "" "s"))))
2441 (let ((sel (completing-read "Which one? " all nil t)))
2442 (if (string= "" sel)
2444 (assoc sel all))))))
2446 (unless (executable-find gnugo-program)
2447 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2448 ;; set up a new board
2449 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2451 (let* ((filename nil)
2452 (user-color "black")
2454 with ls = (split-string
2455 ;; todo: grok ‘gnugo --help’; completion
2458 (car gnugo-option-history)
2459 'gnugo-option-history))
2462 (let ((arg (pop ls)))
2466 (warn "%s %s ignored" opt fn)
2467 (setq filename fn))))
2469 ((string= "--color" arg)
2472 ;; Unfortunately, GTP does not provide
2473 ;; a way to query the user color, so
2474 ;; we must resort to this weirdness.
2478 ((string= "--infile" arg)
2479 (ex "--infile" (pop ls)))
2480 ((string-match "^-l" arg)
2481 (ex "-l" (if (< 2 (length arg))
2484 (t (push arg ok)))))
2485 finally return (nreverse ok)))
2486 (proc (apply 'start-process "gnugo"
2489 "--mode" "gtp" "--quiet"
2491 root board-size handicap komi)
2492 (gnugo-put :user-color user-color)
2493 (gnugo-put :proc proc)
2494 (set-process-sentinel proc 'gnugo-sentinel)
2495 ;; Emacs is too protective sometimes, blech.
2496 (set-process-query-on-exit-flag proc nil)
2497 (gnugo-put :diamond (substring (process-name proc) 5))
2498 (gnugo-put :gnugo-color (gnugo-other user-color))
2500 (gnugo-read-sgf-file (expand-file-name filename))
2504 root (loop ; hmm, available elsewhere?
2506 collect (let* ((k (pop plist))
2510 (setq root (gnugo--root-node
2511 (gnugo--plant-and-climb
2512 (gnugo/sgf-create "(;FF[4]GM[1])" t)))
2513 komi (gnugo--nquery "get_komi")
2514 handicap (gnugo--nquery "get_handicap")
2515 board-size (gnugo--nquery "query_boardsize")))
2517 :DT (format-time-string "%Y-%m-%d")
2518 :RU (if (member "--chinese-rules" args)
2521 :AP (cons "gnugo.el" gnugo-version)
2523 (let ((ub (gnugo--blackp user-color)))
2524 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2525 (if ub :PB :PW) (user-full-name)))
2526 (unless (zerop handicap)
2528 :AB (mapcar (gnugo--as-cc-func)
2529 (gnugo-lsquery "fixed_handicap %d"
2531 (gnugo-put :waiting-start (current-time))
2533 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2534 (gnugo-get :center-position)))
2536 (gnugo-put :game-start-time (current-time))
2537 (let ((g (gnugo-get :gnugo-color))
2538 (n (or (gnugo--root-prop :HA) 0))
2539 (u (gnugo-get :user-color)))
2540 (unless (gnugo-get :last-mover)
2541 (gnugo-put :last-mover
2542 (if (or (and (gnugo--blackp u) (< 1 n))
2543 (and (gnugo--blackp g) (< n 2)))
2546 (run-hooks 'gnugo-start-game-hook)
2547 (when (and (not (gnugo-get :game-over))
2548 (string= g (gnugo-current-player)))
2550 (gnugo-get-move g))))))
2552 ;;;---------------------------------------------------------------------------
2553 ;;; Load-time actions
2555 (unless gnugo-frolic-mode-map
2556 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2557 (suppress-keymap gnugo-frolic-mode-map)
2558 (mapc (lambda (pair)
2559 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2560 '(("q" . gnugo-frolic-quit)
2561 ("Q" . gnugo-frolic-quit)
2562 ("\C-q" . gnugo-frolic-quit)
2563 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2564 ("\C-b" . gnugo-frolic-backward-branch)
2565 ("\C-f" . gnugo-frolic-forward-branch)
2566 ("\C-p" . gnugo-frolic-previous-move)
2567 ("\C-n" . gnugo-frolic-next-move)
2568 ("j" . gnugo-frolic-exchange-left)
2569 ("J" . gnugo-frolic-rotate-left)
2570 ("k" . gnugo-frolic-exchange-right)
2571 ("K" . gnugo-frolic-rotate-right)
2572 ("\C-m" . gnugo-frolic-set-as-main-line)
2573 ("\C-\M-p" . gnugo-frolic-prune-branch)
2574 ("o" . gnugo-frolic-return-to-origin))))
2576 (unless gnugo-board-mode-map
2577 (setq gnugo-board-mode-map (make-sparse-keymap))
2578 (suppress-keymap gnugo-board-mode-map)
2579 (mapc (lambda (pair)
2580 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2581 '(("?" . describe-mode)
2582 ("S" . gnugo-request-suggestion)
2583 ("\C-m" . gnugo-move)
2586 ("R" . gnugo-resign)
2588 ("Q" . gnugo-leave-me-alone)
2589 ("U" . gnugo-fancy-undo)
2590 ("\M-u" . gnugo-undo-one-move)
2591 ("u" . gnugo-undo-two-moves)
2592 ("\C-?" . gnugo-undo-two-moves)
2595 ("\C-l" . gnugo-refresh)
2596 ("\M-_" . gnugo-boss-is-near)
2597 ("_" . gnugo-boss-is-near)
2598 ("h" . gnugo-move-history)
2599 ("L" . gnugo-frolic-in-the-leaves)
2600 ("\C-c\C-l" . gnugo-frolic-in-the-leaves)
2601 ("i" . gnugo-toggle-image-display-command)
2602 ("w" . gnugo-worm-stones)
2603 ("W" . gnugo-worm-data)
2604 ("d" . gnugo-dragon-stones)
2605 ("D" . gnugo-dragon-data)
2606 ("g" . gnugo-toggle-grid)
2607 ("!" . gnugo-estimate-score)
2608 (":" . gnugo-command)
2609 (";" . gnugo-command)
2610 ("=" . gnugo-describe-position)
2611 ("s" . gnugo-write-sgf-file)
2612 ("\C-x\C-s" . gnugo-write-sgf-file)
2613 ("\C-x\C-w" . gnugo-write-sgf-file)
2614 ("l" . gnugo-read-sgf-file)
2615 ("F" . gnugo-display-final-score)
2616 ("A" . gnugo-switch-to-another)
2617 ("C" . gnugo-comment)
2618 ("\C-c\C-a" . gnugo-toggle-abdication)
2620 ([(down-mouse-1)] . gnugo-mouse-move)
2621 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2622 ([(down-mouse-3)] . gnugo-mouse-pass)
2623 ;; delving into the curiosities
2624 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2626 (unless (get 'help :gnugo-gtp-command-spec)
2628 ((sget (x) (get x :gnugo-gtp-command-spec))
2629 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2630 (plist-put (sget cmd) prop val)))
2631 (validpos (s &optional go)
2632 (let ((pos (upcase s)))
2633 (loop with size = (gnugo-get :SZ)
2634 for c across (funcall (gnugo--as-cc-func)
2636 do (let ((norm (- c ?a)))
2637 (unless (and (< -1 norm)
2639 (user-error "Invalid position: %s"
2642 (gnugo-goto-pos pos))
2644 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2647 (jam cmd (car ls) (cadr ls))
2648 (setq ls (cddr ls)))))))
2649 (cl-macrolet ((deffull (who &body body)
2650 (declare (indent 1))
2651 `(defgtp ',who :full (lambda (sel)
2655 (info "(gnugo)GTP command reference")
2656 (when sel (setq sel (intern (car sel))))
2657 (let (buffer-read-only pad cur spec output found)
2659 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2660 (goto-char (point-min))
2662 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2665 (setq pad (make-string (- (match-beginning 1)
2666 (match-beginning 0))
2670 (get (setq cur (intern (match-string 1)))
2671 :gnugo-gtp-command-spec))
2673 (note "handles this command completely"))
2674 (when (setq output (plist-get spec :output))
2675 (if (functionp output)
2676 (note "handles the output specially")
2678 (:discard (note "discards the output"))
2679 (:message (note "displays the output in the echo area")))))
2681 (setq found (match-beginning 0))))))
2682 (cond (found (goto-char found))
2684 (t (message "(no such command: %s)" sel)))))
2686 (deffull final_score
2687 ;; Explicit ignorance avoids byte-compiler warning.
2689 (gnugo-display-final-score))
2695 :post-thunk (lambda ()
2696 (gnugo--unclose-game)
2697 (gnugo--forget :last-mover)
2699 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2703 (gnugo-read-sgf-file (car sel)))
2705 (deffull (undo gg-undo)
2706 (gnugo--climb-towards-root
2709 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2710 (t (validpos (car sel) t)))))))))
2715 ;;;---------------------------------------------------------------------------
2716 ;;; The remainder of this file defines a simplified SGF-handling library.
2717 ;;; When/if it should start to attain generality, it should be split off into
2718 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2719 ;;; "gnugo/" prefix.
2721 (defconst gnugo/sgf-*r4-properties*
2722 '((AB "Add Black" setup list stone)
2723 (AE "Add Empty" game list point)
2724 (AN "Annotation" game simpletext)
2725 (AP "Application" root (simpletext . simpletext))
2726 (AR "Arrow" - list (point . point))
2727 (AS "Who adds stones" - simpletext) ; (LOA)
2728 (AW "Add White" setup list stone)
2729 (B "Black" move move)
2730 (BL "Black time left" move real)
2731 (BM "Bad move" move double)
2732 (BR "Black rank" game simpletext)
2733 (BT "Black team" game simpletext)
2734 (C "Comment" - text)
2735 (CA "Charset" root simpletext)
2736 (CP "Copyright" game simpletext)
2737 (CR "Circle" - list point)
2738 (DD "Dim points" - elist point) ; (inherit)
2739 (DM "Even position" - double)
2740 (DO "Doubtful" move none)
2741 (DT "Date" game simpletext)
2742 (EV "Event" game simpletext)
2743 (FF "Fileformat" root [number (1 . 4)])
2744 (FG "Figure" - (or none (number . simpletext)))
2745 (GB "Good for Black" - double)
2746 (GC "Game comment" game text)
2747 (GM "Game" root [number (1 . 20)])
2748 (GN "Game name" game simpletext)
2749 (GW "Good for White" - double)
2750 (HA "Handicap" game number) ; (Go)
2751 (HO "Hotspot" - double)
2752 (IP "Initial pos." game simpletext) ; (LOA)
2753 (IT "Interesting" move none)
2754 (IY "Invert Y-axis" game simpletext) ; (LOA)
2755 (KM "Komi" game real) ; (Go)
2757 (LB "Label" - list (point . simpletext))
2758 (LN "Line" - list (point . point))
2759 (MA "Mark" - list point)
2760 (MN "set move number" move number)
2761 (N "Nodename" - simpletext)
2762 (OB "OtStones Black" move number)
2763 (ON "Opening" game text)
2764 (OT "Overtime" game simpletext)
2765 (OW "OtStones White" move number)
2766 (PB "Player Black" game simpletext)
2767 (PC "Place" game simpletext)
2768 (PL "Player to play" setup color)
2769 (PM "Print move mode" - number) ; (inherit)
2770 (PW "Player White" game simpletext)
2771 (RE "Result" game simpletext)
2772 (RO "Round" game simpletext)
2773 (RU "Rules" game simpletext)
2774 (SE "Markup" - point) ; (LOA)
2775 (SL "Selected" - list point)
2776 (SO "Source" game simpletext)
2777 (SQ "Square" - list point)
2778 (ST "Style" root [number (0 . 3)])
2779 (SU "Setup type" game simpletext) ; (LOA)
2780 (SZ "Size" root (or number (number . number)))
2781 (TB "Territory Black" - elist point) ; (Go)
2782 (TE "Tesuji" move double)
2783 (TM "Timelimit" game real)
2784 (TR "Triangle" - list point)
2785 (TW "Territory White" - elist point) ; (Go)
2786 (UC "Unclear pos" - double)
2787 (US "User" game simpletext)
2789 (VW "View" - elist point) ; (inherit)
2790 (W "White" move move)
2791 (WL "White time left" move real)
2792 (WR "White rank" game simpletext)
2793 (WT "White team" game simpletext)
2794 (LT "Lose on time" setup simpletext))
2795 ;; r4-specific notes
2796 ;; - changed: DT FG LB RE RU SZ
2797 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2798 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2800 (defun gnugo/sgf-create (file-or-data &optional data-p)
2801 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2802 FILE-OR-DATA is a file name or SGF[4] data.
2803 Optional arg DATA-P non-nil means FILE-OR-DATA is
2804 a string containing SGF[4] data.
2805 A collection is a list of gametrees, each a vector of four elements:
2807 ENDS -- a vector of node lists, with shared tails
2808 (last element of all the lists is the root node)
2810 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2811 have a move number of the previous \"move\" node (or zero)
2813 ROOT -- the root node"
2814 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2815 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2816 (put 'gnugo/sgf-*r4-properties* :keywords
2817 (mapcar (lambda (full)
2819 (intern (format ":%s" (car full)))))
2820 gnugo/sgf-*r4-properties*))))
2821 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2822 (put 'gnugo/sgf-*r4-properties* :specs
2823 (mapcar (lambda (full)
2824 (cons (car full) (cdddr full)))
2825 gnugo/sgf-*r4-properties*))))
2828 ((sw () (skip-chars-forward " \t\n"))
2829 (x (end preserve-whitespace)
2832 (:end (lambda (char) (= ?\] char)))
2833 (:mid (lambda (char) (= ?\: char)))
2834 (t (lambda (char) (or (= ?\: char)
2837 (while (not (funcall endp (setq c (following-char))))
2843 ((unless preserve-whitespace
2844 (looking-at "\\s-+"))
2845 (delete-region (point) (match-end 0))
2847 (t (forward-char 1))))
2848 (buffer-substring-no-properties beg (point))))
2849 (one (type end) (let ((s (progn
2851 (x end (eq 'text type)))))
2854 ;; blech, begone bu"tt"-ugly blatherings
2855 ;; (but bide brobdingnagian boards)...
2856 (if (and (string= "tt" s)
2861 ((simpletext color) s)
2862 ((number real double) (string-to-number s))
2865 (t (error "Unhandled type: %S" type)))))
2866 (val (spec) (cond ((symbolp spec)
2869 ;; todo: check range here.
2870 (one (aref spec 0) :end))
2871 ((eq 'or (car spec))
2872 (let ((v (one (cadr spec) t)))
2873 (if (= ?\] (following-char))
2876 ;; todo: this assumes `spec' has the form
2877 ;; (or foo (foo . bar))
2878 ;; i.e., foo is not rescanned. e.g., `SZ'.
2879 ;; probably this assumption is consistent
2880 ;; w/ the SGF authors' desire to make the
2881 ;; parsing easy, but you never know...
2882 (cons v (one (cdaddr spec) :end)))))
2883 (t (cons (one (car spec) :mid)
2884 (one (cdr spec) :end)))))
2885 (short (who) (when (eobp)
2886 (error "Unexpected EOF while reading %s" who)))
2887 (atvalp () (= ?\[ (following-char)))
2888 (PROP () (let (name spec ltype)
2889 (sw) (short 'property)
2890 (when (looking-at "[A-Z]")
2891 (setq name (read (current-buffer))
2892 spec (cdr (assq name specs)))
2895 (cdr (assq name keywords))
2896 (prog1 (if (= 1 (length spec))
2898 (unless (memq (setq ltype (car spec))
2900 (error "Bad spec: %S" spec))
2901 (if (and (eq 'elist ltype) (sw)
2904 (let ((type (cadr spec))
2906 (while (and (sw) (atvalp)
2907 (setq mo (val type)))
2912 (forward-char 1))))))
2913 (morep () (and (sw) (not (eobp))))
2914 (seek (c) (and (morep) (= c (following-char))))
2915 (seek-into (c) (when (seek c)
2918 (NODE () (when (seek-into ?\;)
2920 while (setq prop (PROP))
2922 (when (eq :SZ (car prop))
2923 (setq SZ (cdr prop)))
2932 (puthash node (+ (if (gnugo--move-prop node)
2935 (gethash prev mnum 0))
2940 (if (not (seek ?\())
2944 (loop while (seek ?\()
2945 append (TREE ls mnum)))
2949 (insert-file-contents file-or-data)
2950 (insert file-or-data)
2951 (goto-char (point-min)))
2953 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2954 (ends (TREE nil mnum))
2955 (root (car (last (car ends)))))
2956 (vector (apply 'vector ends)
2960 (defun gnugo/sgf-write-file (collection filename)
2961 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2962 (me (cons "gnugo.el" gnugo-version))
2963 (specs (mapcar (lambda (full)
2964 (cons (intern (format ":%s" (car full)))
2966 gnugo/sgf-*r4-properties*))
2969 ((esc (composed fmt arg)
2970 (mapconcat (lambda (c)
2972 ;; ‘?\[’ is not strictly required
2973 ;; but neither is it forbidden.
2974 ((?\[ ?\] ?\\) (format "\\%c" c))
2975 (?: (concat (if composed "\\" "") ":"))
2977 (string-to-list (format fmt arg))
2979 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2980 (>>two (v) (insert "["
2981 (esc t "%s" (car v))
2983 (esc t "%s" (cdr v))
2985 (>>nl () (cond ((memq name aft-newline-appreciated)
2987 ((< 60 (current-column))
2995 (insert (substring (symbol-name name) 1))
2998 (setq spec (cdr (assq name specs)))
3002 (let ((>> (if (consp (cadr spec))
3005 (dolist (little-v v)
3007 (funcall >> little-v)
3014 (loop initially (insert ";")
3018 (unless (zerop (current-column))
3022 (funcall (if (gnugo--nodep x)
3028 (dolist (tree collection)
3029 ;; take responsibility for our actions
3030 (gnugo--set-root-prop :AP me tree)
3032 (let ((ht (gnugo--mkht))
3033 (leaves (append (gnugo--tree-ends tree) nil)))
3037 with rh ; rectified history
3038 with bp ; branch point
3040 until (setq bp (gethash node ht))
3042 (push node rh) ; good for now: ½τ
3046 ;; first run: main line
3048 ;; subsequent runs: grafts (value discarded)
3050 ;; Maintain order of ‘leaves’.
3051 (let ((was (cdr bp)))
3052 (if (gnugo--nodep (car was))
3056 (setq tree (hang (pop leaves)))
3057 (mapc #'hang leaves)
3060 (write-file filename)))))
3062 ;;; gnugo.el ends here