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 (defsubst gnugo--no-worries (string)
425 (= ?= (aref string 0)))
427 (defun gnugo--q/ue (fmt &rest args)
428 (let ((ans (apply 'gnugo--q fmt args)))
429 (unless (gnugo--no-worries ans)
430 (user-error "%s" ans))
433 (defun gnugo-query (message-format &rest args)
434 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
435 Return a string that omits the first two characters (corresponding
436 to the status indicator in the Go Text Protocol). Use this function
437 when you are sure the command cannot fail."
438 (substring (apply 'gnugo--q message-format args)
441 (defun gnugo--nquery (cmd)
442 (string-to-number (gnugo-query cmd)))
444 (defun gnugo-lsquery (message-format &rest args)
445 (split-string (apply 'gnugo-query message-format args)))
447 (defsubst gnugo--count-query (fmt &rest args)
448 (length (apply 'gnugo-lsquery fmt args)))
450 (defsubst gnugo--root-prop (prop &optional tree)
451 (cdr (assq prop (gnugo--root-node tree))))
453 (defun gnugo--set-root-prop (prop value &optional tree)
454 (let* ((root (gnugo--root-node tree))
455 (cur (assq prop root)))
458 (push (cons prop value)
459 (cdr (last root))))))
461 (defun gnugo-goto-pos (pos)
462 "Move point to board position POS, a letter-number string."
463 (goto-char (point-min))
464 (forward-line (- (1+ (gnugo-get :SZ))
465 (string-to-number (substring pos 1))))
467 (forward-char (+ (if (= 32 (following-char)) 1 2)
468 (* 2 (- (let ((letter (aref pos 0)))
474 (defun gnugo-f (frag)
475 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
477 (defun gnugo-yang (c)
478 (cdr (assq c '((?+ . hoshi)
480 (?X . (bmoku . bpmoku))
481 (?O . (wmoku . wpmoku))))))
483 (defun gnugo-yy (yin yang &optional momentaryp)
484 (gnugo-f (format "%d-%s"
485 yin (cond ((and (consp yang) momentaryp) (cdr yang))
486 ((consp yang) (car yang))
489 (defun gnugo-toggle-image-display ()
490 (unless (and (fboundp 'display-images-p) (display-images-p))
491 (user-error "Display does not support images, sorry"))
492 (require 'gnugo-xpms)
493 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
494 (user-error "Could not load `gnugo-xpms', sorry"))
495 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
496 (unless (eq fresh (gnugo-get :xpms))
497 (gnugo-put :xpms fresh)
498 (gnugo--forget :all-yy)))
499 (let* ((new (not (gnugo-get :display-using-images)))
500 (act (if new 'display 'do-not-display)))
502 (setcar (symbol-plist yy) act))
503 (or (gnugo-get :all-yy)
505 (prog1 (mapcar (lambda (ent)
507 (yy (gnugo-yy (cdr k) (car k))))
508 (setplist yy `(not-yet ,(cdr ent)))
512 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
514 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
515 (gnugo-put :highlight-last-move-spec
518 (get (gnugo-yy (get-text-property p 'gnugo-yin)
519 (get-text-property p 'gnugo-yang)
523 (gnugo-get :default-highlight-last-move-spec)))
524 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
525 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
526 (mapc 'delete-overlay (cdar group))
527 (setcdr (car group) nil))
528 (gnugo-put :mul (if new
531 (gnugo-put :display-using-images new)))
533 (defun gnugo-toggle-grid ()
534 "Turn the grid around the board on or off."
536 (funcall (if (memq :nogrid buffer-invisibility-spec)
537 'remove-from-invisibility-spec
538 'add-to-invisibility-spec)
540 (save-excursion (gnugo-refresh)))
542 (defun gnugo-propertize-board-buffer ()
544 (insert (substring (gnugo--q "showboard") 3))
545 (let* ((grid-props (list 'invisible :nogrid
546 'font-lock-face gnugo-grid-face))
547 (%gpad (gnugo-f 'gpad))
548 (%gspc (gnugo-f 'gspc))
549 (%lpad (gnugo-f 'lpad))
550 (%rpad (gnugo-f 'rpad))
551 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
552 (size (gnugo-get :SZ))
553 (size-string (number-to-string size)))
554 (goto-char (point-min))
555 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
556 (skip-chars-forward " ")
557 (put-text-property (1- (point)) (point) 'category %gpad)
558 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
560 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
561 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
562 (let* ((row (match-string-no-properties 1))
564 (other-edge (+ edge (* 2 size) -1))
565 (right-empty (+ other-edge (length row) 1))
566 (top-p (string= size-string row))
567 (bot-p (string= "1" row)))
568 (let* ((nL (- edge 1 (length size-string)))
570 (ov (make-overlay nL nR (current-buffer) t)))
571 (add-text-properties nL nR grid-props)
572 ;; We redundantly set `invisible' in the overlay to workaround
573 ;; a display bug whereby text *following* the overlaid text is
574 ;; displayed with the face of the overlaid text, but only when
575 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
576 ;; This has something to do w/ the bletcherous `before-string'.
577 (overlay-put ov 'invisible :nogrid)
578 (overlay-put ov 'category %lpad))
579 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
581 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
582 (truncate (- p edge) 2))
584 (yin (let ((A-p (= edge p))
585 (Z-p (= (1- other-edge) p)))
586 (cond ((and top-p A-p) 1)
595 (yang (gnugo-yang (char-after p))))
596 (add-text-properties p (1+ p)
606 (gnugo-position gnugo-yin))))
607 (unless (= (1- other-edge) p)
608 (add-text-properties (1+ p) (+ 2 p) ispc-props)
609 (put-text-property p (+ 2 p) 'intangible ival)))
610 (add-text-properties (1+ other-edge) right-empty grid-props)
611 (goto-char right-empty)
612 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
613 (let ((prop (if (string= "WH" (match-string 1))
616 (beg (match-beginning 2))
618 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
619 (gnugo-put prop (match-string-no-properties 2))))
621 (put-text-property right-empty (point) 'category %rpad)
623 (add-text-properties (1- (point)) (point-max) grid-props)
624 (skip-chars-forward " ")
625 (put-text-property (1- (point)) (point) 'category %gpad)
626 (put-text-property (point) (progn (end-of-line) (point))
629 (defun gnugo-merge-showboard-results ()
630 (let ((aft (substring (gnugo--q "showboard") 3))
631 (adj 1) ; string to buffer position adjustment
633 (sync "[0-9]* stones$")
634 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
635 ;; restrictive a condition that fails in the case of:
638 ;; ... WHITE has captured 1 stones
641 ;; ... WHITE has captured 14 stones
644 ;; where the after count has more digits than the before count,
645 ;; but shares the same leading digits. In this case, the result
646 ;; of `compare-strings' points to the SPC following the before
647 ;; count (indicated by caret in this example).
649 (bef (buffer-substring-no-properties (point-min) (point-max)))
650 (bef-start 0) (bef-idx 0)
651 (aft-start 0) (aft-idx 0)
652 aft-sync-backtrack mis inc cut new very-strange
654 (inhibit-read-only t))
655 (while (numberp (setq mis (gnugo--compare-strings
658 (setq aft-sync-backtrack nil
659 inc (if (cl-minusp mis)
662 bef-idx (+ bef-start inc)
663 aft-idx (+ aft-start inc)
664 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
667 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
668 (let ((peek (1- aft-idx)))
669 (while (not (= 32 (aref aft peek)))
670 (setq peek (1- peek)))
671 (setq aft-sync-backtrack (1+ peek))))
675 (if aft-sync-backtrack
676 (- aft-sync-backtrack aft-idx)
679 (if aft-sync-backtrack
680 (let* ((asb aft-sync-backtrack)
681 (l-p (get-text-property cut :gnugo-cf))
684 (keep (text-properties-at cut)))
685 (setq new (substring aft asb (string-match " " aft asb)))
686 (plist-put keep :gnugo-cf (cons (length new) capprop))
687 (gnugo-put capprop new)
688 (delete-char old-len)
689 (insert (apply 'propertize new keep))
690 (incf adj (- (length new) old-len)))
691 (setq new (aref aft aft-idx))
692 (insert-and-inherit (char-to-string new))
693 (let ((yin (get-text-property cut 'gnugo-yin))
694 (yang (gnugo-yang new)))
695 (add-text-properties cut (1+ cut)
699 ,(gnugo-yy yin yang))))
701 ;; do this last to avoid complications w/ font lock
702 ;; (this also means we cannot include `intangible' in `front-sticky')
703 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
704 (put-text-property cut (1+ cut) 'intangible very-strange))))))
706 (defsubst gnugo--move-prop (node)
710 (defun gnugo--as-pos-func ()
711 (lexical-let ((size (gnugo-get :SZ)))
716 (let ((col (aref cc 0)))
718 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
719 (- size (- (aref cc 1) ?a))))))))
721 (defsubst gnugo--resignp (string)
722 (string= "resign" string))
724 (defsubst gnugo--passp (string)
725 (string= "PASS" string))
727 (defun gnugo-move-history (&optional rsel color)
728 "Determine and return the game's move history.
729 Optional arg RSEL controls side effects and return value.
730 If nil, display the history in the echo area as \"(N moves)\"
731 followed by the space-separated list of moves. When called
732 interactively with a prefix arg (i.e., RSEL is `(4)'), display
733 similarly, but suffix with the mover (either \":B\" or \":W\").
734 RSEL may also be a symbol that selects what to return:
735 car -- the most-recent move
736 cadr -- the next-to-most-recent move
737 two -- the last two moves as a list, oldest last
738 bpos -- the last stone on the board placed by COLOR
739 For all other values of RSEL, do nothing and return nil."
741 (let* ((monkey (gnugo-get :monkey))
742 (mem (aref monkey 0))
743 (as-pos (gnugo--as-pos-func))
746 ((as-pos-maybe (x) (if (gnugo--resignp x)
749 (remem () (setq node (pop mem)
750 mprop (gnugo--move-prop node)))
751 (next (byp) (when (remem)
752 (setq move (as-pos-maybe (cdr mprop)))
754 (format "%s%s" move (car mprop))
758 (tell () (message "(%d moves) %s"
760 (mapconcat 'identity (nreverse acc) " ")))
761 (finish (byp) (while mem (next byp)) (tell)))
766 (`cadr (nn) (car (nn)))
768 (`bpos (loop with prop = (gnugo--prop<-color color)
771 (eq prop (car mprop))
772 (setq move (cdr mprop))
773 ;; i.e., "normal CC" position
775 return (funcall as-pos move)))
778 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
779 "A special mode for manipulating a GNUGO gametree.
781 \\{gnugo-frolic-mode-map}"
782 (setq truncate-lines t)
783 (buffer-disable-undo))
785 (defun gnugo-frolic-quit ()
786 "Kill GNUGO Frolic buffer and switch to its parent buffer."
788 (let ((bye (current-buffer)))
789 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
790 gnugo-frolic-parent-buffer))
793 (defun gnugo-frolic-return-to-origin ()
794 "Move point to the board's current position."
796 (if (not gnugo-frolic-origin)
797 (message "No origin")
798 (goto-char gnugo-frolic-origin)
799 (recenter (- (count-lines (line-beginning-position)
802 (defun gnugo-frolic-in-the-leaves ()
803 "Display the game tree in a *GNUGO Frolic* buffer.
804 This looks something like:
807 2 W -- K10 K10 K10 K10
826 with 0, 1, ... N (in this case N is 3) in the header line
827 to indicate the branches. Branch 0 is the \"main line\".
828 Point (* in this example) indicates the current position,
829 \"!\" indicates comment properties (e.g., B8, branch 1),
830 and moves not actually on the game tree (e.g., E7, branch 3)
831 are dimmed. Type \\[describe-mode] in that buffer for details."
833 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
835 (from (or gnugo-frolic-parent-buffer
837 ;; todo: use defface once we finally succumb to ‘customize’
838 (dimmed-node-face (list :inherit 'default
839 :foreground "gray50"))
840 (tree (gnugo-get :sgf-gametree))
841 (ends (copy-sequence (gnugo--tree-ends tree)))
842 (mnum (gnugo--tree-mnum tree))
845 (width (length ends))
846 (lanes (number-sequence 0 (1- width)))
847 (monkey (gnugo-get :monkey))
848 (as-pos (gnugo--as-pos-func))
849 (at (car (aref monkey 0)))
850 (bidx (aref monkey 1))
851 (valid (map 'vector (lambda (end)
852 (gethash (car end) mnum))
854 (max-move-num (apply 'max (append valid nil)))
855 (inhibit-read-only t)
861 (propertize s 'face face))
862 (fsi (properties fmt &rest args)
863 (insert (apply 'propertize
864 (apply 'format fmt args)
871 for node in (aref ends bx)
872 do (if (setq fork (on node))
875 ;; todo: ignore non-"move" nodes
876 (eq node (car (aref ends bix))))
878 (pushnew other (gethash node soil))))
883 (puthash node bx seen))
886 (switch-to-buffer buf)
889 (setq header-line-format
890 (lexical-let ((full (concat
892 (mapconcat (lambda (n)
902 `(space :width ,w))))
904 (when (eq 'left scroll-bar-mode)
905 (let ((w (or scroll-bar-width
907 nil 'scroll-bar-width)))
908 (cw (frame-char-width)))
912 (let ((fc (fringe-columns 'left t)))
916 (substring full (window-hscroll))
918 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
919 (set (make-local-variable 'gnugo-state)
920 (buffer-local-value 'gnugo-state from))
924 from max-move-num downto 1
925 do (setq props (list 'n n))
930 (goto-char (point-min))
933 n (aref ["W" "B"] (logand 1 n))))
935 do (let* ((node (unless (< (aref valid bx) n)
936 ;; todo: ignore non-"move" nodes
937 (pop (aref ends bx))))
938 (zow (list* 'bx bx props))
942 (cdr (assq :C node))))
943 (s (cond ((not node) "")
944 ((not (setq move (gnugo--move-prop node))) "-")
945 (t (funcall as-pos (cdr move))))))
948 (push 'help-echo zow))
949 (when (and ok (setq br (gethash node soil)))
950 (push (cons bx (sort br '<))
955 (cond ((and (eq at node)
958 (setq finish (point-marker)))
959 (emph s (list :inherit 'default
960 :foreground (frame-parameter
961 nil 'cursor-color))))
963 (emph s dimmed-node-face))
966 (when (progn (fsi props "\n")
967 (setq forks (nreverse forks)))
968 (let* ((margin (make-string 11 ?\s))
969 (heads (mapcar #'car forks))
970 (tails (mapcar #'cdr forks)))
972 ((spaced (lanes func)
973 (mapconcat func lanes " "))
974 ;; live to play ~ ~ ()
975 ;; play to learn (+) (-) . o O
976 ;; learn to live --ttn .M. _____U
977 (dashed (lanes func) ;;; _____ ^^^^
978 (mapconcat func lanes "-----"))
980 (spaced lanes (lambda (bx)
984 (pad-unless (condition)
995 do (let* ((one (car ls))
998 (mapcar 'car (cdr ls))
1000 (apply 'append (mapcar 'cdr bef))))
1003 (end (car (last ord))))
1005 ((also (b e) (cnxn (number-sequence b e)
1010 (pad-unless (zerop beg))
1011 (dashed (number-sequence beg end)
1013 (cond ((memq bx ord) "+")
1016 (pad-unless (>= end width))
1017 (also (1+ end) (1- width))
1020 (edge (apply 'append tails))
1021 (aa2u (line-beginning-position
1022 (- (1+ (length forks))))
1025 (set (make-local-variable 'gnugo-frolic-origin) finish)
1026 (gnugo-frolic-return-to-origin))))
1028 (defun gnugo--awake (how)
1029 ;; Valid HOW elements:
1030 ;; require-valid-branch
1032 ;; (line . move-string)
1033 ;; Invalid elements blissfully ignored. :-D
1034 (let* ((tree (gnugo-get :sgf-gametree))
1035 (ends (gnugo--tree-ends tree))
1036 (width (length ends))
1037 (monkey (gnugo-get :monkey))
1038 (line (case (cdr (assq 'line how))
1040 (count-lines (point-min) (line-beginning-position)))
1043 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1046 (col (current-column))
1047 (a (unless (> 10 col)
1048 (let ((try (/ (- col 10)
1050 (unless (<= width try)
1053 (when (memq 'require-valid-branch how)
1055 (user-error "No branch here")))
1056 (loop with omit = (cdr (assq 'omit how))
1057 for (name . value) in `((line . ,line)
1058 (bidx . ,(aref monkey 1))
1063 do (unless (memq name omit)
1067 (defmacro gnugo--awakened (how &rest body)
1068 (declare (indent 1))
1069 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1071 for name in '(line bidx monkey
1074 do (unless (memq name omit)
1077 (gnugo--awake ',how)
1080 (defsubst gnugo--move-to-bcol (bidx)
1081 (move-to-column (+ 10 (* 6 bidx))))
1083 (defun gnugo--swiz (direction &optional blunt)
1084 (gnugo--awakened (require-valid-branch
1087 (let* ((b (cond ((numberp blunt)
1088 (unless (and (< -1 blunt)
1090 (user-error "No such branch: %s" blunt))
1092 (t (mod (+ direction a) width))))
1093 (flit (if blunt (lambda (n)
1098 (mod (+ direction n) width))))
1099 (was (copy-sequence ends))
1100 (new-bidx (funcall flit bidx)))
1101 (loop for bx below width
1102 do (aset ends (funcall flit bx)
1104 (unless (= new-bidx bidx)
1105 (aset monkey 1 new-bidx))
1106 (gnugo-frolic-in-the-leaves)
1107 (goto-char (point-min))
1109 (gnugo--move-to-bcol b))))
1111 (defun gnugo-frolic-exchange-left ()
1112 "Exchange the current branch with the one to its left."
1116 (defun gnugo-frolic-rotate-left ()
1117 "Rotate all branches left."
1121 (defun gnugo-frolic-exchange-right ()
1122 "Exchange the current branch with the one to its right."
1126 (defun gnugo-frolic-rotate-right ()
1127 "Rotate all branches right."
1131 (defun gnugo-frolic-set-as-main-line ()
1132 "Make the current branch the main line."
1134 (gnugo--swiz nil 0))
1136 (defun gnugo-frolic-prune-branch ()
1137 "Remove the current branch from the gametree.
1138 This fails if there is only one branch in the tree.
1139 This fails if the monkey is on the current branch
1140 \(a restriction that will probably be lifted Real Soon Now\)."
1142 (gnugo--awakened (require-valid-branch
1143 (line . move-string))
1144 ;; todo: define meaningful eviction semantics; remove restriction
1146 (user-error "Cannot prune with monkey on branch"))
1148 (user-error "Cannot prune last remaining branch"))
1149 (let ((new (append ends nil)))
1150 ;; Explicit ignorance avoids byte-compiler warning.
1151 (ignore (pop (nthcdr a new)))
1152 (gnugo--set-tree-ends tree new))
1154 (aset monkey 1 (decf bidx)))
1155 (gnugo-frolic-in-the-leaves)
1157 (goto-char (point-min))
1158 (search-forward line)
1159 (gnugo--move-to-bcol (min a (- width 2))))))
1161 (defun gnugo--sideways (backwards n)
1162 (gnugo--awakened ((omit tree ends monkey bidx line))
1163 (gnugo--move-to-bcol (mod (if backwards
1168 (defun gnugo-frolic-backward-branch (&optional n)
1169 "Move backward N (default 1) branches."
1171 (gnugo--sideways t n))
1173 (defun gnugo-frolic-forward-branch (&optional n)
1174 "Move forward N (default 1) branches."
1176 (gnugo--sideways nil n))
1178 (defun gnugo--vertical (n direction)
1181 direction (- direction)))
1182 (gnugo--awakened ((line . numeric)
1183 (omit tree ends width monkey bidx))
1184 (let ((stop (if (> 0 direction)
1186 (max 0 (1- (count-lines (point-min)
1190 (loop while (not (= line stop))
1192 (forward-line direction)
1193 (incf line direction))
1194 until (get-text-property (point) 'n))
1195 until (zerop (decf n)))
1197 (gnugo--move-to-bcol a)
1198 (move-to-column col)))))
1200 (defun gnugo-frolic-previous-move (&optional n)
1201 "Move to the Nth (default 1) previous move."
1203 (gnugo--vertical n -1))
1205 (defun gnugo-frolic-next-move (&optional n)
1206 "Move to the Nth (default 1) next move."
1208 (gnugo--vertical n 1))
1210 (defun gnugo-boss-is-near ()
1211 "Do `bury-buffer' until the current one is not a GNU Board."
1213 (while (gnugo-board-buffer-p)
1216 (defsubst gnugo--no-regrets (monkey ends)
1217 (eq (aref ends (aref monkey 1))
1220 (defun gnugo--as-cc-func ()
1221 (lexical-let ((size (gnugo-get :SZ)))
1223 (let* ((col (aref pos 0))
1224 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1225 (two (+ ?a (- size (string-to-number
1226 (substring pos 1))))))
1227 (format "%c%c" one two)))))
1229 (defsubst gnugo--decorate (node alist)
1230 ;; NB: ALIST should not have :B or :W keys.
1231 (setcdr (last node) alist))
1233 (defun gnugo-close-game (end-time resign)
1234 (gnugo-put :game-end-time end-time)
1235 (let ((now (or end-time (current-time))))
1236 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1238 (gnugo-put :game-over
1239 (if (or (eq t resign)
1240 (and (stringp resign)
1241 (string-match "[BW][+][Rr]esign" resign)))
1243 ((ls (color) (mapcar
1248 (gnugo-query "worm_stones %s" color)
1250 (let ((live (append (ls "black") (ls "white"))))
1253 (let ((dd (gnugo-query "dragon_data"))
1254 (start 0) mem color ent live dead)
1255 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1257 (setq mem (match-string 1 dd)
1258 color (match-string 2 dd)
1260 ent (cons (list color)
1261 (sort (gnugo-lsquery "dragon_stones %s" mem)
1263 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1265 (if (match-string 2 dd)
1268 (setq start (match-end 0)))
1272 (defun gnugo--unclose-game ()
1273 (gnugo--forget :game-over ; all those in -close-game
1276 (let* ((root (gnugo--root-node))
1277 (cur (assq :RE root)))
1279 (assert (not (eq cur (car root))) nil
1280 ":RE at head of root node: %S"
1284 (defun gnugo-push-move (who move)
1285 (let* ((simple (booleanp who))
1286 (ucolor (gnugo-get :user-color))
1290 (gnugo-get :gnugo-color))
1292 (start (gnugo-get :waiting-start))
1293 (now (current-time))
1294 (resignp (gnugo--resignp move))
1295 (passp (gnugo--passp move))
1296 (head (gnugo-move-history 'car))
1297 (onep (and head (gnugo--passp head)))
1298 (donep (or resignp (and onep passp))))
1300 (gnugo--q/ue "play %s %s" color move))
1302 (gnugo-merge-showboard-results))
1303 (gnugo-put :last-mover color)
1306 (string= ucolor color))
1307 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1308 ;; update :sgf-gametree and :monkey
1309 (let* ((property (gnugo--prop<-color color))
1310 (pair (cons property (cond (resignp move)
1312 (t (funcall (gnugo--as-cc-func)
1315 (monkey (gnugo-get :monkey))
1316 (mem (aref monkey 0))
1318 (tree (gnugo-get :sgf-gametree))
1319 (ends (gnugo--tree-ends tree))
1320 (mnum (gnugo--tree-mnum tree))
1321 (count (length ends))
1322 (tip-move-num (gethash tip mnum))
1323 (bidx (aref monkey 1)))
1324 ;; Detect déjà-vu. That is, when placing "A", avoid:
1330 ;; (such "variations" do not actually vary!) in favor of:
1336 ;; This linear search loses for multiple ‘old’ w/ "A",
1337 ;; a very unusual (but not invalid, sigh) situation.
1341 ;; Start with latest / highest likelihood for hit.
1342 ;; (See "to the right" comment, below.)
1343 from (if (gnugo--no-regrets monkey ends)
1347 if (setq bx (mod (+ bidx i) count)
1350 for m on (aref ends bx)
1351 while (< tip-move-num
1352 (gethash (setq node (car m))
1356 (when (equal pair (assq property node))
1364 (rotatef (aref ends bidx)
1366 (setq mem previous))
1370 (unless (gnugo--no-regrets monkey ends)
1371 (setq ends (gnugo--set-tree-ends
1372 tree (let ((ls (append ends nil)))
1373 ;; copy old to the right of new
1374 (push mem (nthcdr bidx ls))
1376 (puthash fruit (1+ (gethash tip mnum)) mnum)
1378 (aset ends bidx mem)))
1379 (setf (aref monkey 0) mem))
1381 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1383 (gnugo-close-game now resignp))
1384 (gnugo-put :waiting-start (and (not donep) now))
1387 (defun gnugo-venerate (yin yang)
1388 (let* ((fg-yy (gnugo-yy yin yang))
1389 (fg-disp (or (get fg-yy 'display)
1390 (get fg-yy 'do-not-display)))
1391 (fg-data (plist-get (cdr fg-disp) :data))
1392 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1393 (bg-disp (or (get bg-yy 'display)
1394 (get bg-yy 'do-not-display)))
1395 (bg-data (plist-get (cdr bg-disp) :data))
1399 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1400 (setq start (match-end 0))
1401 (string-to-number (match-string 1 s)))))
1402 (while (and (not (cl-minusp ncolors))
1403 (string-match ",\n" s start))
1404 (setq start (match-end 0)
1405 ncolors (1- ncolors)))
1406 (string-match "\"" s start)
1408 (new (copy-sequence fg-data))
1409 (lx (length fg-data))
1410 (sx (funcall bop fg-data))
1411 (sb (funcall bop bg-data))
1412 (color-key (aref new sx))) ; blech, heuristic
1414 (when (and (not (= color-key (aref new sx)))
1415 (cl-plusp (random 4)))
1416 (aset new sx (aref bg-data sb)))
1419 (create-image new 'xpm t :ascent 'center)))
1421 (defun gnugo-refresh (&optional nocache)
1422 "Update GNUGO Board buffer display.
1423 While a game is in progress, parenthesize the last-played stone (no parens
1424 for pass). If the buffer is currently displayed in the selected window,
1425 recenter the board (presuming there is extra space in the window). Update
1426 the mode line. Lastly, move point to the last position played by the user,
1427 if that move was not a pass.
1429 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1430 be slow. (This should normally be unnecessary; specify it only if the display
1431 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1434 (let* ((move (gnugo-move-history 'car))
1435 (game-over (gnugo-get :game-over))
1436 (inhibit-read-only t)
1438 (when (and nocache (not (gnugo-get :waiting)))
1439 (gnugo-propertize-board-buffer))
1442 (destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1443 (if (member move '("PASS" "resign"))
1444 (mapc 'delete-overlay (list l-ov r-ov))
1445 (gnugo-goto-pos move)
1447 (hspec (gnugo-get :highlight-last-move-spec))
1448 (display-value (nth 0 hspec))
1449 (l-offset (nth 1 hspec))
1450 (l-new-pos (+ p l-offset))
1451 (r-action (nth 2 hspec)))
1452 (overlay-put l-ov 'display
1453 (if (functionp display-value)
1454 (funcall display-value p)
1456 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1458 (funcall r-action r-ov)
1459 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1461 (rename-buffer (concat (gnugo-get :diamond)
1463 (format "%s(game over)"
1464 (if (gnugo--resignp move)
1465 (concat move "ation ")
1467 (format "%s(%s to play)"
1468 (if move (concat move " ") "")
1469 (gnugo-current-player)))))
1472 (let ((live (cdr (assq 'live game-over)))
1473 (dead (cdr (assq 'dead game-over)))
1475 (unless (eq game-over (get-text-property 1 'game-over))
1476 (dolist (group (append live dead))
1477 (dolist (pos (cdr group))
1478 (gnugo-goto-pos pos)
1480 (put-text-property p (1+ p) 'group group)))
1481 (put-text-property 1 2 'game-over game-over))
1482 (dolist (group live)
1483 (when (setq pall (cdar group))
1484 (mapc 'delete-overlay pall)
1485 (setcdr (car group) nil)))
1486 (dolist (group dead)
1487 (unless (cdar group)
1488 (let (ov pall c (color (caar group)))
1489 (setq c (if (gnugo--blackp color) "x" "o"))
1490 (dolist (pos (cdr group))
1491 (gnugo-goto-pos pos)
1492 (setq p (point) ov (make-overlay p (1+ p)))
1495 (if (gnugo-get :display-using-images)
1496 ;; respect the dead individually; it takes more time
1497 ;; but that's not a problem (for them)
1498 (gnugo-venerate (get-text-property p 'gnugo-yin)
1499 (gnugo-yang (aref (upcase c) 0)))
1500 (propertize c 'face 'font-lock-warning-face)))
1502 (setcdr (car group) pall))))))
1504 (when (setq window (get-buffer-window (current-buffer)))
1505 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1506 (size (gnugo-get :SZ))
1507 (under10p (< size 10))
1508 (mul (gnugo-get :mul))
1509 (h (- (truncate (- (window-height window)
1514 (edges (window-edges window))
1515 (right-w-edge (nth 2 edges))
1516 (avail-width (- right-w-edge (nth 0 edges)))
1518 (imagesp (symbol-plist (gnugo-f 'ispc)))
1519 (w (/ (- avail-width
1524 2 ; between board and grid
1529 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1530 `(display ,(make-string h 10))
1531 '(invisible :nogrid)))
1536 (cond (imagesp (+ (* 0.5 wmul)
1542 (gspc . ,(when imagesp
1546 ;; DWR: image width alone => OBOE!
1548 ;; NB: ‘(* wmul cw)’ is the same
1549 ;; as ‘(car (image-size ... t))’.
1550 (let ((cw (frame-char-width)))
1551 (/ (+ 1.0 (* wmul cw))
1554 (lpad . ,(let ((d `(display (space :align-to ,w))))
1555 ;; We distinguish between these cases to
1556 ;; workaround a display bug whereby the
1557 ;; `before-string' is omitted entirely (not
1558 ;; rendered) when interacting w/ the text
1559 ;; mode last-move left-paren for moves in
1563 ,(apply 'propertize " " d))
1566 (space :align-to ,(1- avail-width))))))
1567 (setplist (gnugo-f (car pair)) (cdr pair)))))
1569 (let ((cur (gnugo-get :mode-line)))
1570 (unless (equal cur gnugo-mode-line)
1571 (setq cur gnugo-mode-line)
1572 (gnugo-put :mode-line cur)
1573 (gnugo-put :mode-line-form
1574 (cond ((stringp cur)
1575 (setq cur (copy-sequence cur))
1577 (while (setq cut (string-match "~[bwpmtu]" cur))
1579 (setq c (aref cur (incf cut)))
1582 `(,(intern (format "squig-%c" c))
1584 (?b '(or (gnugo-get :black-captures) 0))
1585 (?w '(or (gnugo-get :white-captures) 0))
1586 (?p '(gnugo-current-player))
1587 (?t '(let ((ws (gnugo-get :waiting-start)))
1589 (cadr (time-since ws))
1591 (?u '(or (gnugo-get :last-waiting) "-"))
1592 (?m '(let ((tree (gnugo-get :sgf-gametree))
1593 (monkey (gnugo-get :monkey)))
1594 (gethash (car (aref monkey 0))
1595 (gnugo--tree-mnum tree)
1596 ;; should be unnecessary
1599 `(let ,(delete-dups (copy-sequence acc))
1600 (format ,cur ,@(reverse (mapcar 'car acc))))))
1602 (let ((form (gnugo-get :mode-line-form)))
1603 (setq mode-line-process
1605 ;; this dynamicism is nice but excessive in its wantonness
1606 ;;- `(" [" (:eval ,form) "]")
1607 ;; this dynamicism is ok because the user triggers it
1608 (list (format " [%s]" (eval form))
1609 '(:eval (if (gnugo-get :abd)
1612 (force-mode-line-update))
1614 (when (setq last (gnugo-get :last-user-bpos))
1615 (gnugo-goto-pos last))))
1617 (defun gnugo--finish-move (buf)
1618 (run-hooks 'gnugo-post-move-hook)
1619 (with-current-buffer buf
1622 ;;;---------------------------------------------------------------------------
1623 ;;; Game play actions
1625 (defun gnugo--rename-buffer-portion (&optional back)
1626 (let ((old "to play")
1627 (new "waiting for suggestion"))
1630 (let ((name (buffer-name)))
1631 (when (string-match old name)
1632 (rename-buffer (replace-match new t t name))))))
1634 (defun gnugo-get-move-insertion-filter (proc string)
1635 (with-current-buffer (process-buffer proc)
1636 (let* ((so-far (gnugo-get :get-move-string))
1637 (full (gnugo-put :get-move-string (concat so-far string))))
1638 (when (string-match "^= \\(.+\\)\n\n" full)
1639 (setq full (match-string 1 full)) ; POS or "PASS"
1640 (destructuring-bind (color . suggestion)
1641 (gnugo-get :waiting)
1642 (gnugo--forget :get-move-string
1646 (gnugo--rename-buffer-portion t)
1647 (unless (or (gnugo--passp full)
1648 (eq 'nowarp suggestion))
1649 (gnugo-goto-pos full))
1650 (message "%sSuggestion for %s: %s"
1651 (gnugo-get :diamond)
1653 (let* ((donep (gnugo-push-move color full))
1654 (buf (current-buffer)))
1655 (gnugo--finish-move buf)
1656 (when (gnugo-get :abd)
1660 2 ;;; sec (frettoloso? dubioso!)
1661 nil (lambda (buf color)
1662 (with-current-buffer buf
1663 (gnugo-get-move color)))
1665 (gnugo-other color))))))))))))
1667 (defun gnugo-get-move (color &optional suggestion)
1668 (gnugo-put :waiting (cons color suggestion))
1669 (gnugo--begin-exchange
1670 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1671 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1672 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1673 (concat "reg_genmove " color))
1674 (accept-process-output))
1676 (defun gnugo-cleanup ()
1677 (when (gnugo-board-buffer-p)
1678 (unless (zerop (buffer-size))
1679 (message "Thank you for playing GNU Go."))
1681 (setplist sym nil) ; "...is next to fordliness." --Huxley
1682 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1683 ;; No worries, things will be Much Better w/ structs, RSN...
1685 (append (gnugo-get :all-yy)
1694 (setq gnugo-state nil)))
1696 (defun gnugo-position ()
1697 (or (get-text-property (point) 'gnugo-position)
1698 (user-error "Not a proper position point")))
1700 (defun gnugo-request-suggestion (&optional nowarp)
1701 "Request a move suggestion from GNU Go.
1702 After some time (during which you can do other stuff),
1703 Emacs displays the suggestion in the echo area and warps the
1704 cursor to the suggested position. Prefix arg inhibits warp."
1707 (gnugo--rename-buffer-portion)
1708 (gnugo-get-move (gnugo-current-player)
1713 (defun gnugo--user-play (pos-or-pass)
1715 ;; The "user" in this func's name used to signify both
1716 ;; who does the action and for whom the action is done.
1717 ;; Now, it signifies only the former.
1718 (let* ((gcolor (gnugo-get :gnugo-color))
1719 (userp (string= gcolor (gnugo-get :last-mover)))
1720 (donep (gnugo-push-move userp pos-or-pass))
1721 (buf (current-buffer)))
1722 (gnugo--finish-move buf)
1723 (when (and userp (not donep))
1724 (with-current-buffer buf
1725 (gnugo-get-move gcolor)))))
1727 (defun gnugo-move ()
1728 "Make a move on the GNUGO Board buffer.
1729 The position is computed from current point.
1730 Signal error if done out-of-turn or if game-over.
1731 To start a game try M-x gnugo."
1733 (gnugo--user-play (gnugo-position)))
1735 (defun gnugo-mouse-move (e)
1736 "Do `gnugo-move' at mouse location."
1739 (when (memq (following-char) '(?. ?+))
1742 (defun gnugo-pass ()
1743 "Make a pass on the GNUGO Board buffer.
1744 Signal error if done out-of-turn or if game-over.
1745 To start a game try M-x gnugo."
1747 (gnugo--user-play "PASS"))
1749 (defun gnugo-mouse-pass (e)
1750 "Do `gnugo-pass' at mouse location."
1755 (defun gnugo-resign ()
1758 (if (not (y-or-n-p "Resign? "))
1759 (message "(not resigning)")
1760 (gnugo-push-move t "resign")
1763 (defun gnugo-animate-group (w/d)
1764 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1765 (let* ((pos (gnugo-position))
1766 (orig-b-m-p (buffer-modified-p))
1768 (unless (memq (following-char) '(?X ?O))
1769 (user-error "No stone at %s" pos))
1770 (setq blurb (message "Computing %s stones ..." w/d)
1771 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1772 (message "%s %s in group." blurb (length stones))
1773 (setplist (gnugo-f 'anim) nil)
1774 (let* ((spec (if (gnugo-get :display-using-images)
1775 (loop with yin = (get-text-property (point) 'gnugo-yin)
1776 with yang = (gnugo-yang (following-char))
1777 with up = (get (gnugo-yy yin yang t) 'display)
1778 with dn = (get (gnugo-yy yin yang) 'display)
1779 for n below (length gnugo-animation-string)
1780 collect (if (zerop (logand 1 n))
1782 (split-string gnugo-animation-string "" t)))
1784 (ovs (save-excursion
1785 (mapcar (lambda (pos)
1786 (gnugo-goto-pos pos)
1788 (ov (make-overlay p (1+ p))))
1789 (overlay-put ov 'category (gnugo-f 'anim))
1790 (overlay-put ov 'priority most-positive-fixnum)
1793 (setplist (gnugo-f 'anim) (cons 'display cell))
1794 (while (and (cdr spec) ; let last linger lest levity lost
1795 (sit-for 0.08675309)) ; jenny jenny i got your number...
1796 (setcar cell (setq spec (cdr spec)))
1797 ;; Force redisplay of overlays.
1798 (set-buffer-modified-p orig-b-m-p))
1800 (mapc 'delete-overlay ovs)
1803 (defun gnugo-display-group-data (command buffer-name)
1804 (message "Computing %s ..." command)
1805 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1806 (switch-to-buffer buffer-name)
1809 (message "Computing %s ... done." command))
1811 (defun gnugo-worm-stones ()
1812 "In the GNUGO Board buffer, animate \"worm\" at current position.
1813 Signal error if done out-of-turn or if game-over.
1814 See variable `gnugo-animation-string' for customization."
1817 (gnugo-animate-group 'worm))
1819 (defun gnugo-worm-data ()
1820 "Display in another buffer data from \"worm\" at current position.
1821 Signal error if done out-of-turn or if game-over."
1824 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1826 (defun gnugo-dragon-stones ()
1827 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1828 Signal error if done out-of-turn or if game-over.
1829 See variable `gnugo-animation-string' for customization."
1832 (gnugo-animate-group 'dragon))
1834 (defun gnugo-dragon-data ()
1835 "Display in another buffer data from \"dragon\" at current position.
1836 Signal error if done out-of-turn or if game-over."
1839 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1841 (defun gnugo-estimate-score ()
1842 "Display estimated score of a game of GNU Go.
1843 Output includes number of stones on the board and number of stones
1844 captured by each player, and the estimate of who has the advantage (and
1845 by how many stones)."
1847 (message "Est.score ...")
1848 (let ((black (gnugo--count-query "list_stones black"))
1849 (white (gnugo--count-query "list_stones white"))
1850 (black-captures (gnugo-query "captures black"))
1851 (white-captures (gnugo-query "captures white"))
1852 (est (gnugo-query "estimate_score")))
1853 ;; might as well update this
1854 (gnugo-put :black-captures black-captures)
1855 (gnugo-put :white-captures white-captures)
1856 (message "Est.score ... B %s %s | W %s %s | %s"
1857 black black-captures white white-captures est)))
1859 (defun gnugo-write-sgf-file (filename)
1860 "Save the game history to FILENAME (even if unfinished).
1861 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1862 (interactive "FWrite game as SGF file: ")
1863 (when (and (file-exists-p filename)
1864 (not (y-or-n-p "File exists. Continue? ")))
1865 (user-error "Not writing %s" filename))
1866 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1867 (set-buffer-modified-p nil))
1869 (defun gnugo--who-is-who (wait play samep)
1870 (message "GNU Go %splays as %s, you as %s (%s)"
1871 (if samep "" "now ")
1874 "NOTE: this is a switch!")))
1876 (defsubst gnugo--nodep (x)
1877 (keywordp (caar x)))
1879 (defun gnugo--SZ! (size)
1880 (gnugo-put :SZ size)
1881 (gnugo-put :center-position
1882 (funcall (gnugo--as-pos-func)
1883 (let ((c (+ -1 ?a (truncate (1+ size) 2))))
1886 (defun gnugo--plant-and-climb (collection &optional sel)
1887 (gnugo-put :sgf-collection collection)
1888 (let ((tree (nth (or sel 0) collection)))
1889 (gnugo-put :sgf-gametree tree)
1890 (gnugo-put :monkey (vector
1892 (aref (gnugo--tree-ends tree) 0)
1897 (defun gnugo-read-sgf-file (filename)
1898 "Load the first game tree from FILENAME, a file in SGF format."
1899 (interactive "fSGF file to load: ")
1900 (when (file-directory-p filename)
1901 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1902 (let (play wait samep coll tree game-over)
1903 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1904 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1905 (setq play (gnugo--q/ue "loadsgf %s" (expand-file-name filename))
1906 wait (gnugo-other play)
1907 samep (string= (gnugo-get :user-color) play))
1908 (gnugo-put :last-mover wait)
1910 (gnugo-put :gnugo-color wait)
1911 (gnugo-put :user-color play))
1912 (setq coll (gnugo/sgf-create filename)
1913 tree (gnugo--plant-and-climb
1914 coll (let ((n (length coll)))
1918 ;; (let* ((q (format "Which game? (1-%d)" n))
1919 ;; (choice (1- (read-number q 1))))
1920 ;; (if (and (< -1 choice) (< choice n))
1922 ;; (message "(Selecting the first game)")
1924 ;; but this is what we use (for now) to accomodate
1925 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1927 (message "(Selecting the first game)"))
1929 ;; This is deliberately undocumented for now.
1930 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1931 (when (setq game-over (or (gnugo--root-prop :RE tree)
1932 (when (equal '("PASS" "PASS")
1933 (gnugo-move-history 'two))
1935 (gnugo-close-game nil game-over))
1936 (gnugo-put :last-user-bpos
1937 (gnugo-move-history 'bpos (gnugo-get :user-color)))
1939 (set-buffer-modified-p nil)
1940 (gnugo--who-is-who wait play samep)))
1942 (defun gnugo--mem-with-played-stone (pos &optional noerror)
1943 (let ((color (case (following-char)
1948 (user-error "No stone at %s" pos))
1949 (loop with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
1950 for mem on (aref (gnugo-get :monkey) 0)
1951 when (equal fruit (caar mem))
1953 finally return nil))))
1955 (defun gnugo--climb-towards-root (spec &optional noalt keep)
1957 (let* ((user-color (gnugo-get :user-color))
1958 (monkey (gnugo-get :monkey))
1959 (tree (gnugo-get :sgf-gametree))
1960 (ends (gnugo--tree-ends tree))
1961 (remorseful (not (gnugo--no-regrets monkey ends)))
1962 (stop (if (numberp spec)
1963 (nthcdr (if (zerop spec)
1964 (if (string= (gnugo-get :last-mover)
1970 (let* ((pos (if (stringp spec)
1973 (hmm (gnugo--mem-with-played-stone pos)))
1974 ;; todo: relax ‘gnugo--user-play’ then lift restriction
1975 (unless (eq (gnugo--prop<-color user-color)
1976 (car (gnugo--move-prop (car hmm))))
1977 (user-error "%s not occupied by %s"
1980 (when (gnugo-get :game-over)
1981 (gnugo--unclose-game))
1982 (while (not (eq stop (aref monkey 0)))
1983 (gnugo--q/ue "undo")
1984 (pop (aref monkey 0))
1985 (gnugo-put :last-mover (gnugo-current-player))
1986 (gnugo-merge-showboard-results) ; all
1987 (gnugo-refresh) ; this
1988 (redisplay)) ; eye candy
1989 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1991 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1992 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1994 (gnugo-get :center-position)))
1996 (unless (or keep remorseful)
1997 (aset ends (aref monkey 1) (aref monkey 0)))
1998 (when (and ulastp (not noalt))
1999 (gnugo-get-move (gnugo-get :gnugo-color))))))
2001 (defun gnugo-undo-one-move (&optional me-next)
2002 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
2003 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
2004 Prefix arg ME-NEXT means to arrange for you to play
2005 the color of the next move (and GNU Go the opposite).
2006 This is useful after loading an SGF file whose last
2007 move was done by the color you prefer to play:
2008 \\[gnugo-read-sgf-file] FILENAME RET
2009 C-u \\[gnugo-undo-one-move]
2011 See also `gnugo-undo-two-moves'."
2015 (let* ((play (gnugo-get :last-mover))
2016 (wait (gnugo-other play)))
2017 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
2018 (gnugo-put :user-color play)
2019 (gnugo-put :gnugo-color wait)))
2020 (gnugo--climb-towards-root 1 t))
2022 (defun gnugo-undo-two-moves ()
2023 "Undo a pair of moves (GNU Go's and yours).
2024 However, if you are the last mover, undo only one move.
2025 Regardless, after undoing, it is your turn to play again."
2028 (gnugo--climb-towards-root 0))
2030 (defun gnugo-oops (&optional position)
2031 "Like `gnugo-undo-two-moves', but keep the undone moves.
2032 The kept moves become a sub-gametree (variation) when play resumes.
2033 Prefix arg means, instead, undo repeatedly up to and including
2034 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2037 (gnugo--climb-towards-root (unless position
2041 (defun gnugo-okay (&optional full)
2042 "Redo a pair of undone moves.
2043 Prefix arg means to redo all the undone moves."
2046 (let* ((tree (gnugo-get :sgf-gametree))
2047 (ends (gnugo--tree-ends tree))
2048 (monkey (gnugo-get :monkey)))
2049 (if (gnugo--no-regrets monkey ends)
2050 (message "Oop ack!")
2051 (let* ((as-pos (gnugo--as-pos-func))
2052 (mnum (gnugo--tree-mnum tree))
2053 (mem (aref monkey 0))
2054 (bidx (aref monkey 1))
2055 (end (aref ends bidx))
2056 (ucolor (gnugo-get :user-color))
2057 (uprop (gnugo--prop<-color ucolor)))
2058 (cl-flet ((mvno (node) (gethash node mnum)))
2062 (+ 2 (mvno (car mem))))
2063 with (node move todo)
2067 move (gnugo--move-prop node))
2068 (when (and move (>= ok (mvno node)))
2069 (let ((userp (eq uprop (car move))))
2071 (funcall as-pos (cdr move)))
2073 until (eq mem (cdr ls))
2076 for (userp pos) in todo
2078 (gnugo-push-move userp pos)
2082 (defun gnugo-display-final-score (&optional comment)
2083 "Display final score and other info in another buffer (when game over).
2084 If the game is still ongoing, Emacs asks if you wish to stop play (by
2085 making sure two \"pass\" moves are played consecutively, if necessary).
2086 Also, add the `:RE' SGF property to the root node of the game tree.
2087 Prefix arg COMMENT means to also attach the text (slightly compacted)
2088 to the last move, as a comment."
2090 (let ((game-over (gnugo-get :game-over)))
2091 (unless (or game-over
2092 (and (not (gnugo-get :waiting))
2093 (y-or-n-p "Game still in play. Stop play now? ")))
2094 (user-error "Sorry, game still in play"))
2098 (message "Playing PASS for %s ..."
2099 (gnugo-get (if userp :user-color :gnugo-color)))
2101 (gnugo-push-move userp "PASS")))
2106 (let ((b= " Black = ")
2108 (res (when (gnugo--resignp (gnugo-move-history 'car))
2109 (gnugo-get :last-mover)))
2113 (format "%s wins.\n"
2114 (substring (if (= ?b (aref res 0)) w= b=)
2116 "The game is over.\n"
2117 (format "Resignation by %s.\n" res))
2118 result (concat (upcase (substring (gnugo-other res) 0 1))
2120 (message "Computing final score ...")
2121 (let* ((g-over (gnugo-get :game-over))
2122 (live (cdr (assq 'live g-over)))
2123 (dead (cdr (assq 'dead g-over)))
2124 (seed (gnugo-get :scoring-seed))
2125 (terr-q (format "final_status_list %%s_territory %d" seed))
2128 (b-terr (gnugo--count-query terr-q "black"))
2129 (w-terr (gnugo--count-query terr-q "white"))
2130 (b-capt (string-to-number (gnugo-get :black-captures)))
2131 (w-capt (string-to-number (gnugo-get :white-captures)))
2132 (komi (gnugo--root-prop :KM)))
2133 (setq blurb (list "The game is over. Final score:\n")
2134 result (gnugo-query "final_score %d" seed))
2135 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2136 (dolist (group live)
2137 (incf (if (gnugo--blackp (caar group))
2140 (length (cdr group))))
2141 (dolist (group dead)
2142 (incf (if (gnugo--blackp (caar group))
2145 (length (cdr group))))
2146 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2147 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2148 w-terr terr komi 'komi (+ w-terr komi))
2151 (dolist (group dead)
2152 (incf (if (gnugo--blackp (caar group))
2155 (* 2 (length (cdr group)))))
2156 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2161 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2165 (+ w-terr w-capt komi))
2167 (push (if (string= "0" result)
2168 "The game is a draw.\n"
2169 (format "%s wins by %s.\n"
2170 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2171 (substring result 2)))
2173 (message "Computing final score ... done")))
2175 (let ((beg (gnugo-get :game-start-time))
2176 (end (gnugo-get :game-end-time)))
2180 ((yep (pretty moment)
2181 (push (format-time-string
2182 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2185 (yep "Game start" beg)
2187 (setq blurb (apply 'concat (nreverse blurb)))
2188 (gnugo--set-root-prop :RE result)
2190 (let ((node (car (aref (gnugo-get :monkey) 0))))
2192 (delq (assq :C node) node)
2193 (with-temp-buffer ; lame
2195 (when (search-backward "\n\nGame start:" nil t)
2196 (delete-region (point) (point-max)))
2197 (cl-flet ((rep (old new)
2198 (goto-char (point-min))
2199 (while (search-forward old nil t)
2200 (replace-match new))))
2201 (rep "The game is over. " "")
2202 (rep "territory" "T")
2203 (rep "captures" "C")
2205 `((:C . ,(buffer-string)))))))
2206 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2210 (defun gnugo-quit ()
2211 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2212 If the game is not over, ask for confirmation first."
2214 (if (or (gnugo-get :game-over)
2215 (y-or-n-p "Quit? "))
2217 (message "(not quitting)")))
2219 (defun gnugo-leave-me-alone ()
2220 "Kill the current buffer unconditionally."
2224 (defun gnugo-fancy-undo (count)
2225 "Rewind the game tree in various ways.
2226 Prefix arg COUNT means to undo that many moves.
2227 Otherwise, undo repeatedly up to and including the move
2228 which placed the stone at point."
2230 (gnugo--climb-towards-root
2231 (cond ((numberp count) count)
2232 ((consp count) (car count)))))
2234 (defun gnugo-toggle-image-display-command () ; ugh
2235 "Toggle use of images to display the board, then refresh."
2237 (gnugo-toggle-image-display)
2238 (save-excursion (gnugo-refresh)))
2240 (defsubst gnugo--node-with-played-stone (pos &optional noerror)
2241 (car (gnugo--mem-with-played-stone pos noerror)))
2243 (defun gnugo-describe-position ()
2244 "Display the board position under cursor in the echo area.
2245 If there a stone at that position, also display its move number."
2247 (let* ((pos (gnugo-position)) ; do first (can throw)
2248 (node (gnugo--node-with-played-stone pos t)))
2252 (let* ((tree (gnugo-get :sgf-gametree))
2253 (mnum (gnugo--tree-mnum tree))
2254 (move-num (gethash node mnum)))
2255 (format " (move %d)" move-num)))
2258 (defun gnugo-switch-to-another ()
2259 "Switch to another GNU Go game buffer (if any)."
2261 (loop for buf in (cdr (buffer-list))
2262 if (gnugo-board-buffer-p buf)
2265 (switch-to-buffer buf))
2266 finally do (message "(only one)")))
2268 (defun gnugo-comment (node comment)
2269 "Add to NODE a COMMENT (string) property.
2270 Called interactively, NODE is the one corresponding to the
2271 stone at point, and any previous comment is inserted as the
2272 initial-input (see `read-string').
2274 If COMMENT is nil or the empty string, remove the property entirely."
2276 (let* ((pos (gnugo-position))
2277 (node (gnugo--node-with-played-stone pos)))
2279 (read-string (format "Comment for %s: "
2280 (gnugo-describe-position))
2281 (cdr (assq :C node))))))
2282 (setq node (delq (assq :C node) node))
2283 (unless (zerop (length comment))
2284 (gnugo--decorate node `((:C . ,comment)))))
2286 (defun gnugo-toggle-abdication ()
2287 "Toggle abdication, i.e., letting GNU Go play for you.
2288 When enabled, the mode line includes \"Abd\".
2289 Enabling signals error if the game is over.
2290 When disabling, if GNU Go has already started thinking of
2291 a move to play for you, the thinking is not cancelled but instead
2292 transformed into a move suggestion (see `gnugo-request-suggestion')."
2294 (let ((last-mover (gnugo-get :last-mover))
2295 (abd (gnugo-get :abd))
2299 (let* ((gcolor (gnugo-get :gnugo-color))
2300 (waiting (gnugo-get :waiting))
2301 (userp (string= last-mover gcolor)))
2302 (when (and userp waiting)
2303 (gnugo--rename-buffer-portion)
2304 (setcdr waiting (setq xform 'nowarp)))
2307 (gnugo--forget :abd)
2308 (unless (or userp waiting)
2309 (gnugo-get-move gcolor)))
2313 (gnugo-get-move (gnugo-other last-mover)))
2314 (message "Abdication %sabled%s"
2315 (if (gnugo-get :abd)
2319 (format " (suggestion for %s forthcoming)"
2320 (gnugo-get :user-color))
2325 ;;;---------------------------------------------------------------------------
2326 ;;; Command properties and gnugo-command
2328 ;; GTP commands entered by the user are never issued directly to GNU Go;
2329 ;; instead, their behavior and output are controlled by the property
2330 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2331 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2333 ;; :full -- completely interpret the command string; the value is a
2334 ;; func that takes the list of words derived from splitting the
2335 ;; command string (minus the command) and handles everything.
2337 ;; :output -- either a keyword specifying the preferred output method:
2338 ;; :message -- show output in minibuffer
2339 ;; :discard -- sometimes you just don't care;
2340 ;; or a function that takes one arg, the output string, and
2341 ;; handles it completely. default is to switch to buffer
2342 ;; "*gnugo command output*" if the output has a newline,
2343 ;; otherwise use `message'.
2345 ;; :post-thunk -- run after output processing (at the very end).
2347 (defun gnugo-command (command)
2348 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2349 Output and Emacs behavior depend on which command is given (some
2350 commands are handled completely by Emacs w/o using the subprocess;
2351 some commands have their output displayed in specially prepared
2352 buffers or in the echo area; some commands are instrumented to do
2353 gnugo.el-specific housekeeping).
2355 For example, for the command \"help\", Emacs visits the
2356 GTP command reference info page.
2358 NOTE: At this time, GTP command handling specification is still
2359 incomplete. Thus, some commands WILL confuse gnugo.el."
2360 (interactive "sCommand: ")
2361 (if (string= "" command)
2362 (message "(no command given)")
2363 (let* ((split (split-string command))
2364 (cmd (intern (car split)))
2365 (spec (get cmd :gnugo-gtp-command-spec))
2366 (full (plist-get spec :full)))
2368 (funcall full (cdr split))
2369 (message "Doing %s ..." command)
2370 (let* ((ans (gnugo--q command))
2371 (where (plist-get spec :output)))
2372 (if (string-match "unknown.command" ans)
2374 (cond ((functionp where) (funcall where ans))
2375 ((eq :discard where) (message ""))
2376 ((or (eq :message where)
2377 (not (string-match "\n" ans)))
2379 (t (switch-to-buffer "*gnugo command output*")
2382 (message "Doing %s ... done." command)))
2383 (let ((thunk (plist-get spec :post-thunk)))
2384 (when thunk (funcall thunk)))))))))
2386 ;;;---------------------------------------------------------------------------
2387 ;;; Major mode for interacting with a GNUGO subprocess
2389 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2390 "Major mode for playing GNU Go.
2391 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2392 In this mode, keys do not self insert.
2394 \\{gnugo-board-mode-map}"
2395 (buffer-disable-undo) ; todo: undo undo undoing
2396 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2398 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2399 (set (make-local-variable 'gnugo-state)
2400 (gnugo--mkht :size (1- 42)))
2401 (gnugo-put :highlight-last-move-spec
2402 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2403 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2404 (let ((ov (make-overlay 1 1)))
2405 (overlay-put ov 'display ")")
2407 (gnugo-put :mul '(1 . 1))
2408 (add-to-invisibility-spec :nogrid))
2410 ;;;---------------------------------------------------------------------------
2414 (defun gnugo (&optional new-game)
2415 "Run gnugo in a buffer, or resume a game in progress.
2416 If there is already a game in progress you may resume it instead
2417 of starting a new one. Prefix arg means skip the game-in-progress
2418 check and start a new game straight away.
2420 Before starting, Emacs queries you for additional command-line
2421 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2423 Note that specifying \"--infile FILENAME\" (or, \"-l FILENAME\")
2424 silently clobbers certain other options, such as \"--color\".
2425 For details, see info node `(gnugo) Invoking GNU Go'.
2427 \\<gnugo-board-mode-map>
2428 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2429 See `gnugo-board-mode' for a full list of commands."
2431 (let* ((all (let (acc)
2432 (dolist (buf (buffer-list))
2433 (when (gnugo-board-buffer-p buf)
2434 (push (cons (buffer-name buf) buf) acc)))
2437 (if (and (not new-game)
2439 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2440 (if (= 1 n) "" "s"))))
2445 (let ((sel (completing-read "Which one? " all nil t)))
2446 (if (string= "" sel)
2448 (assoc sel all))))))
2450 (unless (executable-find gnugo-program)
2451 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2452 ;; set up a new board
2453 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2455 (let* ((filename nil)
2456 (user-color "black")
2458 with ls = (split-string
2459 ;; todo: grok ‘gnugo --help’; completion
2462 (car gnugo-option-history)
2463 'gnugo-option-history))
2466 (let ((arg (pop ls)))
2470 (warn "%s %s ignored" opt fn)
2471 (setq filename fn))))
2473 ((string= "--color" arg)
2476 ;; Unfortunately, GTP does not provide
2477 ;; a way to query the user color, so
2478 ;; we must resort to this weirdness.
2482 ((string= "--infile" arg)
2483 (ex "--infile" (pop ls)))
2484 ((string-match "^-l" arg)
2485 (ex "-l" (if (< 2 (length arg))
2488 (t (push arg ok)))))
2489 finally return (nreverse ok)))
2490 (proc (apply 'start-process "gnugo"
2493 "--mode" "gtp" "--quiet"
2495 root board-size handicap komi)
2496 (gnugo-put :user-color user-color)
2497 (gnugo-put :proc proc)
2498 (set-process-sentinel proc 'gnugo-sentinel)
2499 ;; Emacs is too protective sometimes, blech.
2500 (set-process-query-on-exit-flag proc nil)
2501 (gnugo-put :diamond (substring (process-name proc) 5))
2502 (gnugo-put :gnugo-color (gnugo-other user-color))
2504 (gnugo-read-sgf-file (expand-file-name filename))
2508 root (loop ; hmm, available elsewhere?
2510 collect (let* ((k (pop plist))
2514 (setq root (gnugo--root-node
2515 (gnugo--plant-and-climb
2516 (gnugo/sgf-create "(;FF[4]GM[1])" t)))
2517 komi (gnugo--nquery "get_komi")
2518 handicap (gnugo--nquery "get_handicap")
2519 board-size (gnugo--nquery "query_boardsize")))
2521 :DT (format-time-string "%Y-%m-%d")
2522 :RU (if (member "--chinese-rules" args)
2525 :AP (cons "gnugo.el" gnugo-version)
2527 (let ((ub (gnugo--blackp user-color)))
2528 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2529 (if ub :PB :PW) (user-full-name)))
2530 (unless (zerop handicap)
2532 :AB (mapcar (gnugo--as-cc-func)
2533 (gnugo-lsquery "fixed_handicap %d"
2535 (gnugo-put :waiting-start (current-time))
2537 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2538 (gnugo-get :center-position)))
2540 (gnugo-put :game-start-time (current-time))
2541 (let ((g (gnugo-get :gnugo-color))
2542 (n (or (gnugo--root-prop :HA) 0))
2543 (u (gnugo-get :user-color)))
2544 (unless (gnugo-get :last-mover)
2545 (gnugo-put :last-mover
2546 (if (or (and (gnugo--blackp u) (< 1 n))
2547 (and (gnugo--blackp g) (< n 2)))
2550 (run-hooks 'gnugo-start-game-hook)
2551 (when (and (not (gnugo-get :game-over))
2552 (string= g (gnugo-current-player)))
2554 (gnugo-get-move g))))))
2556 ;;;---------------------------------------------------------------------------
2557 ;;; Load-time actions
2559 (unless gnugo-frolic-mode-map
2560 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2561 (suppress-keymap gnugo-frolic-mode-map)
2562 (mapc (lambda (pair)
2563 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2564 '(("q" . gnugo-frolic-quit)
2565 ("Q" . gnugo-frolic-quit)
2566 ("\C-q" . gnugo-frolic-quit)
2567 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2568 ("\C-b" . gnugo-frolic-backward-branch)
2569 ("\C-f" . gnugo-frolic-forward-branch)
2570 ("\C-p" . gnugo-frolic-previous-move)
2571 ("\C-n" . gnugo-frolic-next-move)
2572 ("j" . gnugo-frolic-exchange-left)
2573 ("J" . gnugo-frolic-rotate-left)
2574 ("k" . gnugo-frolic-exchange-right)
2575 ("K" . gnugo-frolic-rotate-right)
2576 ("\C-m" . gnugo-frolic-set-as-main-line)
2577 ("\C-\M-p" . gnugo-frolic-prune-branch)
2578 ("o" . gnugo-frolic-return-to-origin))))
2580 (unless gnugo-board-mode-map
2581 (setq gnugo-board-mode-map (make-sparse-keymap))
2582 (suppress-keymap gnugo-board-mode-map)
2583 (mapc (lambda (pair)
2584 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2585 '(("?" . describe-mode)
2586 ("S" . gnugo-request-suggestion)
2587 ("\C-m" . gnugo-move)
2590 ("R" . gnugo-resign)
2592 ("Q" . gnugo-leave-me-alone)
2593 ("U" . gnugo-fancy-undo)
2594 ("\M-u" . gnugo-undo-one-move)
2595 ("u" . gnugo-undo-two-moves)
2596 ("\C-?" . gnugo-undo-two-moves)
2599 ("\C-l" . gnugo-refresh)
2600 ("\M-_" . gnugo-boss-is-near)
2601 ("_" . gnugo-boss-is-near)
2602 ("h" . gnugo-move-history)
2603 ("L" . gnugo-frolic-in-the-leaves)
2604 ("\C-c\C-l" . gnugo-frolic-in-the-leaves)
2605 ("i" . gnugo-toggle-image-display-command)
2606 ("w" . gnugo-worm-stones)
2607 ("W" . gnugo-worm-data)
2608 ("d" . gnugo-dragon-stones)
2609 ("D" . gnugo-dragon-data)
2610 ("g" . gnugo-toggle-grid)
2611 ("!" . gnugo-estimate-score)
2612 (":" . gnugo-command)
2613 (";" . gnugo-command)
2614 ("=" . gnugo-describe-position)
2615 ("s" . gnugo-write-sgf-file)
2616 ("\C-x\C-s" . gnugo-write-sgf-file)
2617 ("\C-x\C-w" . gnugo-write-sgf-file)
2618 ("l" . gnugo-read-sgf-file)
2619 ("F" . gnugo-display-final-score)
2620 ("A" . gnugo-switch-to-another)
2621 ("C" . gnugo-comment)
2622 ("\C-c\C-a" . gnugo-toggle-abdication)
2624 ([(down-mouse-1)] . gnugo-mouse-move)
2625 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2626 ([(down-mouse-3)] . gnugo-mouse-pass)
2627 ;; delving into the curiosities
2628 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2630 (unless (get 'help :gnugo-gtp-command-spec)
2632 ((sget (x) (get x :gnugo-gtp-command-spec))
2633 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2634 (plist-put (sget cmd) prop val)))
2635 (validpos (s &optional go)
2636 (let ((pos (upcase s)))
2637 (loop with size = (gnugo-get :SZ)
2638 for c across (funcall (gnugo--as-cc-func)
2640 do (let ((norm (- c ?a)))
2641 (unless (and (< -1 norm)
2643 (user-error "Invalid position: %s"
2646 (gnugo-goto-pos pos))
2648 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2651 (jam cmd (car ls) (cadr ls))
2652 (setq ls (cddr ls)))))))
2653 (cl-macrolet ((deffull (who &body body)
2654 (declare (indent 1))
2655 `(defgtp ',who :full (lambda (sel)
2659 (info "(gnugo)GTP command reference")
2660 (when sel (setq sel (intern (car sel))))
2661 (let (buffer-read-only pad cur spec output found)
2663 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2664 (goto-char (point-min))
2666 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2669 (setq pad (make-string (- (match-beginning 1)
2670 (match-beginning 0))
2674 (get (setq cur (intern (match-string 1)))
2675 :gnugo-gtp-command-spec))
2677 (note "handles this command completely"))
2678 (when (setq output (plist-get spec :output))
2679 (if (functionp output)
2680 (note "handles the output specially")
2682 (:discard (note "discards the output"))
2683 (:message (note "displays the output in the echo area")))))
2685 (setq found (match-beginning 0))))))
2686 (cond (found (goto-char found))
2688 (t (message "(no such command: %s)" sel)))))
2690 (deffull final_score
2691 ;; Explicit ignorance avoids byte-compiler warning.
2693 (gnugo-display-final-score))
2699 :post-thunk (lambda ()
2700 (gnugo--unclose-game)
2701 (gnugo--forget :last-mover)
2703 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2707 (gnugo-read-sgf-file (car sel)))
2709 (deffull (undo gg-undo)
2710 (gnugo--climb-towards-root
2713 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2714 (t (validpos (car sel) t)))))))))
2719 ;;;---------------------------------------------------------------------------
2720 ;;; The remainder of this file defines a simplified SGF-handling library.
2721 ;;; When/if it should start to attain generality, it should be split off into
2722 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2723 ;;; "gnugo/" prefix.
2725 (defconst gnugo/sgf-*r4-properties*
2726 '((AB "Add Black" setup list stone)
2727 (AE "Add Empty" game list point)
2728 (AN "Annotation" game simpletext)
2729 (AP "Application" root (simpletext . simpletext))
2730 (AR "Arrow" - list (point . point))
2731 (AS "Who adds stones" - simpletext) ; (LOA)
2732 (AW "Add White" setup list stone)
2733 (B "Black" move move)
2734 (BL "Black time left" move real)
2735 (BM "Bad move" move double)
2736 (BR "Black rank" game simpletext)
2737 (BT "Black team" game simpletext)
2738 (C "Comment" - text)
2739 (CA "Charset" root simpletext)
2740 (CP "Copyright" game simpletext)
2741 (CR "Circle" - list point)
2742 (DD "Dim points" - elist point) ; (inherit)
2743 (DM "Even position" - double)
2744 (DO "Doubtful" move none)
2745 (DT "Date" game simpletext)
2746 (EV "Event" game simpletext)
2747 (FF "Fileformat" root [number (1 . 4)])
2748 (FG "Figure" - (or none (number . simpletext)))
2749 (GB "Good for Black" - double)
2750 (GC "Game comment" game text)
2751 (GM "Game" root [number (1 . 20)])
2752 (GN "Game name" game simpletext)
2753 (GW "Good for White" - double)
2754 (HA "Handicap" game number) ; (Go)
2755 (HO "Hotspot" - double)
2756 (IP "Initial pos." game simpletext) ; (LOA)
2757 (IT "Interesting" move none)
2758 (IY "Invert Y-axis" game simpletext) ; (LOA)
2759 (KM "Komi" game real) ; (Go)
2761 (LB "Label" - list (point . simpletext))
2762 (LN "Line" - list (point . point))
2763 (MA "Mark" - list point)
2764 (MN "set move number" move number)
2765 (N "Nodename" - simpletext)
2766 (OB "OtStones Black" move number)
2767 (ON "Opening" game text)
2768 (OT "Overtime" game simpletext)
2769 (OW "OtStones White" move number)
2770 (PB "Player Black" game simpletext)
2771 (PC "Place" game simpletext)
2772 (PL "Player to play" setup color)
2773 (PM "Print move mode" - number) ; (inherit)
2774 (PW "Player White" game simpletext)
2775 (RE "Result" game simpletext)
2776 (RO "Round" game simpletext)
2777 (RU "Rules" game simpletext)
2778 (SE "Markup" - point) ; (LOA)
2779 (SL "Selected" - list point)
2780 (SO "Source" game simpletext)
2781 (SQ "Square" - list point)
2782 (ST "Style" root [number (0 . 3)])
2783 (SU "Setup type" game simpletext) ; (LOA)
2784 (SZ "Size" root (or number (number . number)))
2785 (TB "Territory Black" - elist point) ; (Go)
2786 (TE "Tesuji" move double)
2787 (TM "Timelimit" game real)
2788 (TR "Triangle" - list point)
2789 (TW "Territory White" - elist point) ; (Go)
2790 (UC "Unclear pos" - double)
2791 (US "User" game simpletext)
2793 (VW "View" - elist point) ; (inherit)
2794 (W "White" move move)
2795 (WL "White time left" move real)
2796 (WR "White rank" game simpletext)
2797 (WT "White team" game simpletext)
2798 (LT "Lose on time" setup simpletext))
2799 ;; r4-specific notes
2800 ;; - changed: DT FG LB RE RU SZ
2801 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2802 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2804 (defun gnugo/sgf-create (file-or-data &optional data-p)
2805 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2806 FILE-OR-DATA is a file name or SGF[4] data.
2807 Optional arg DATA-P non-nil means FILE-OR-DATA is
2808 a string containing SGF[4] data.
2809 A collection is a list of gametrees, each a vector of four elements:
2811 ENDS -- a vector of node lists, with shared tails
2812 (last element of all the lists is the root node)
2814 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2815 have a move number of the previous \"move\" node (or zero)
2817 ROOT -- the root node"
2818 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2819 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2820 (put 'gnugo/sgf-*r4-properties* :keywords
2821 (mapcar (lambda (full)
2823 (intern (format ":%s" (car full)))))
2824 gnugo/sgf-*r4-properties*))))
2825 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2826 (put 'gnugo/sgf-*r4-properties* :specs
2827 (mapcar (lambda (full)
2828 (cons (car full) (cdddr full)))
2829 gnugo/sgf-*r4-properties*))))
2832 ((sw () (skip-chars-forward " \t\n"))
2833 (x (end preserve-whitespace)
2836 (:end (lambda (char) (= ?\] char)))
2837 (:mid (lambda (char) (= ?\: char)))
2838 (t (lambda (char) (or (= ?\: char)
2841 (while (not (funcall endp (setq c (following-char))))
2847 ((unless preserve-whitespace
2848 (looking-at "\\s-+"))
2849 (delete-region (point) (match-end 0))
2851 (t (forward-char 1))))
2852 (buffer-substring-no-properties beg (point))))
2853 (one (type end) (let ((s (progn
2855 (x end (eq 'text type)))))
2858 ;; blech, begone bu"tt"-ugly blatherings
2859 ;; (but bide brobdingnagian boards)...
2860 (if (and (string= "tt" s)
2865 ((simpletext color) s)
2866 ((number real double) (string-to-number s))
2869 (t (error "Unhandled type: %S" type)))))
2870 (val (spec) (cond ((symbolp spec)
2873 ;; todo: check range here.
2874 (one (aref spec 0) :end))
2875 ((eq 'or (car spec))
2876 (let ((v (one (cadr spec) t)))
2877 (if (= ?\] (following-char))
2880 ;; todo: this assumes `spec' has the form
2881 ;; (or foo (foo . bar))
2882 ;; i.e., foo is not rescanned. e.g., `SZ'.
2883 ;; probably this assumption is consistent
2884 ;; w/ the SGF authors' desire to make the
2885 ;; parsing easy, but you never know...
2886 (cons v (one (cdaddr spec) :end)))))
2887 (t (cons (one (car spec) :mid)
2888 (one (cdr spec) :end)))))
2889 (short (who) (when (eobp)
2890 (error "Unexpected EOF while reading %s" who)))
2891 (atvalp () (= ?\[ (following-char)))
2892 (PROP () (let (name spec ltype)
2893 (sw) (short 'property)
2894 (when (looking-at "[A-Z]")
2895 (setq name (read (current-buffer))
2896 spec (cdr (assq name specs)))
2899 (cdr (assq name keywords))
2900 (prog1 (if (= 1 (length spec))
2902 (unless (memq (setq ltype (car spec))
2904 (error "Bad spec: %S" spec))
2905 (if (and (eq 'elist ltype) (sw)
2908 (let ((type (cadr spec))
2910 (while (and (sw) (atvalp)
2911 (setq mo (val type)))
2916 (forward-char 1))))))
2917 (morep () (and (sw) (not (eobp))))
2918 (seek (c) (and (morep) (= c (following-char))))
2919 (seek-into (c) (when (seek c)
2922 (NODE () (when (seek-into ?\;)
2924 while (setq prop (PROP))
2926 (when (eq :SZ (car prop))
2927 (setq SZ (cdr prop)))
2936 (puthash node (+ (if (gnugo--move-prop node)
2939 (gethash prev mnum 0))
2944 (if (not (seek ?\())
2948 (loop while (seek ?\()
2949 append (TREE ls mnum)))
2953 (insert-file-contents file-or-data)
2954 (insert file-or-data)
2955 (goto-char (point-min)))
2957 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2958 (ends (TREE nil mnum))
2959 (root (car (last (car ends)))))
2960 (vector (apply 'vector ends)
2964 (defun gnugo/sgf-write-file (collection filename)
2965 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2966 (me (cons "gnugo.el" gnugo-version))
2967 (specs (mapcar (lambda (full)
2968 (cons (intern (format ":%s" (car full)))
2970 gnugo/sgf-*r4-properties*))
2973 ((esc (composed fmt arg)
2974 (mapconcat (lambda (c)
2976 ;; ‘?\[’ is not strictly required
2977 ;; but neither is it forbidden.
2978 ((?\[ ?\] ?\\) (format "\\%c" c))
2979 (?: (concat (if composed "\\" "") ":"))
2981 (string-to-list (format fmt arg))
2983 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2984 (>>two (v) (insert "["
2985 (esc t "%s" (car v))
2987 (esc t "%s" (cdr v))
2989 (>>nl () (cond ((memq name aft-newline-appreciated)
2991 ((< 60 (current-column))
2999 (insert (substring (symbol-name name) 1))
3002 (setq spec (cdr (assq name specs)))
3006 (let ((>> (if (consp (cadr spec))
3009 (dolist (little-v v)
3011 (funcall >> little-v)
3018 (loop initially (insert ";")
3022 (unless (zerop (current-column))
3026 (funcall (if (gnugo--nodep x)
3032 (dolist (tree collection)
3033 ;; take responsibility for our actions
3034 (gnugo--set-root-prop :AP me tree)
3036 (let ((ht (gnugo--mkht))
3037 (leaves (append (gnugo--tree-ends tree) nil)))
3041 with rh ; rectified history
3042 with bp ; branch point
3044 until (setq bp (gethash node ht))
3046 (push node rh) ; good for now: ½τ
3050 ;; first run: main line
3052 ;; subsequent runs: grafts (value discarded)
3054 ;; Maintain order of ‘leaves’.
3055 (let ((was (cdr bp)))
3056 (if (gnugo--nodep (car was))
3060 (setq tree (hang (pop leaves)))
3061 (mapc #'hang leaves)
3064 (write-file filename)))))
3066 ;;; gnugo.el ends here