1 ;;; gnugo.el --- play GNU Go in a buffer -*- lexical-binding: t -*-
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
7 ;; Package-Requires: ((ascii-art-to-unicode "1.5"))
9 ;; This program is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
14 ;; This program is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; This file provides the command `gnugo' which allows you to play the game of
28 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
29 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
30 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
31 ;; Go" to refer to the process object created by running the external program.
33 ;; At the start of a new game, you can pass additional command-line arguments
34 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
35 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
36 ;; both komi and handicap.
38 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
39 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
40 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
41 ;; back through an arbitrary stone that you played, place the cursor on a
42 ;; stone and type `U' (note: uppercase).
44 ;; There are a great many other commands. Other keybindings are described in
45 ;; the `gnugo-board-mode' documentation, which you may view with the command
46 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
47 ;; the last move and who is currently to play. Capture counts and other info
48 ;; are shown on the mode line immediately following the major mode name.
50 ;; While GNU Go is pondering its next move, certain commands that rely on its
51 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
52 ;; is normal. When it is your turn again you may retry the command. In the
53 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
54 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
56 ;; If GNU Go should crash during a game the mode line will show "no process".
57 ;; Please report the event to the GNU Go maintainers so that they can improve
61 ;; Meta-Playing (aka Customizing)
62 ;; ------------------------------
64 ;; Customization is presently limited to
65 ;; vars: `gnugo-program'
66 ;; `gnugo-animation-string'
68 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
70 ;; normal hooks: `gnugo-board-mode-hook'
71 ;; `gnugo-frolic-mode-hook'
72 ;; `gnugo-start-game-hook'
73 ;; `gnugo-post-move-hook'
74 ;; and the keymap: `gnugo-board-mode-map'
76 ;; The variable `gnugo-xpms' is a special case. To set it you need to load
77 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
82 (eval-when-compile (require 'cl)) ; use the source luke!
83 (require 'ascii-art-to-unicode) ; for `aa2u'
84 (require 'time-date) ; for `time-subtract'
86 ;;;---------------------------------------------------------------------------
89 (defconst gnugo-version "2.3.1"
90 "Version of gnugo.el currently loaded.
91 This follows a MAJOR.MINOR.PATCH scheme.")
93 ;;;---------------------------------------------------------------------------
94 ;;; Variables for the uninquisitive programmer
96 (defvar gnugo-program "gnugo"
97 "Name of the GNU Go program (executable file).
98 \\[gnugo] validates this using `executable-find'.
99 This program must accept command line args:
101 For more information on GTP and GNU Go, please visit:
102 <http://www.gnu.org/software/gnugo>")
104 (defvar gnugo-board-mode-map nil
105 "Keymap for GNUGO Board mode.")
107 (defvar gnugo-frolic-mode-map nil
108 "Keymap for GNUGO Frolic mode.")
110 (defvar gnugo-board-mode-hook nil
111 "Hook run when entering GNUGO Board mode.")
113 (defvar gnugo-start-game-hook nil
114 "Normal hook run immediately before the first move of the game.
115 To find out who is to move first, use `gnugo-current-player'.
116 See also `gnugo-board-mode'.")
118 (defvar gnugo-post-move-hook nil
119 "Normal hook run after a move and before the board is refreshed.
120 Initially, when `run-hooks' is called, the current buffer is the GNUGO
121 Board buffer of the game. Hook functions that switch buffers must take
122 care not to call (directly or indirectly through some other function)
123 `gnugo-put' or `gnugo-get' after the switch.")
125 (defvar gnugo-animation-string
126 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
127 (concat jam jam jam jam jam
128 ;; "SECRET MESSAGE HERE"
129 blink blink blink blink blink blink blink blink
130 ;; Playing go is like fighting ignorance: when you think you have
131 ;; surrounded something by knowing it very well it often turns
132 ;; out that in the time you spent deepening this understanding,
133 ;; other areas of ignorance have surrounded you.
134 spin spin spin spin spin spin spin spin spin
135 ;; Playing go is not like fighting ignorance: what one person
136 ;; knows many people may come to know; knowledge does not build
137 ;; solely move by move. Wisdom, on the other hand...
139 "String whose individual characters are used for animation.
140 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
141 render the stones in their respective result groups as the first character
142 in the string, then the next, and so on.")
144 (defvar gnugo-mode-line "~b ~w :~m :~u"
145 "A `mode-line-format'-compliant value for GNUGO Board mode.
146 If a single string, the following special escape sequences are
147 replaced with their associated information:
148 ~b,~w black,white captures (a number)
149 ~p current player (black or white)
151 ~t time waiting for the current move
152 ~u time taken for the Ultimate (most recent) move
153 The times are in seconds, or \"-\" if that information is not available.
154 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
156 (defvar gnugo-X-face 'font-lock-string-face
157 "Name of face to use for X (black) stones.")
159 (defvar gnugo-O-face 'font-lock-builtin-face
160 "Name of face to use for O (white) stones.")
162 (defvar gnugo-grid-face 'default
163 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
165 ;;;---------------------------------------------------------------------------
166 ;;; Variables for the inquisitive programmer
168 (defconst gnugo-font-lock-keywords
169 '(("X" . gnugo-X-face)
170 ("O" . gnugo-O-face))
171 "Font lock keywords for `gnugo-board-mode'.")
173 (defvar gnugo-option-history nil)
175 (defvar gnugo-state nil) ; hint: C-c C-p
178 (defvar gnugo-xpms nil))
180 (defvar gnugo-frolic-parent-buffer nil)
181 (defvar gnugo-frolic-origin nil)
183 ;;;---------------------------------------------------------------------------
184 ;;; Support functions
186 (defsubst gnugo--mkht (&rest etc)
187 (apply 'make-hash-table :test 'eq etc))
189 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
190 (compare-strings s1 beg1 nil s2 beg2 nil))
192 (defun gnugo-put (key value)
193 "Associate move/game/board-specific property KEY with VALUE.
195 There are many properties, each named by a keyword, that record and control
196 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
197 of properties, stored in the hash table `gnugo-state'. Here we document
198 some of the more stable properties. You may wish to use them as part of
199 a `gnugo-post-move-hook' function, for example. Be careful to preserve
200 the current buffer as `gnugo-state' is made into a buffer-local variable.
201 NOTE: In the following, \"see foo\" actually means \"see foo source or
202 you may never really understand to any degree of personal satisfaction\".
204 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
206 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
208 :game-over -- nil until game over at which time its value is set to
209 the alist `((live GROUP ...) (dead GROUP ...))'
211 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
212 a simple list of one or more gametrees, updated in
213 conjunction w/ :sgf-gametree and :monkey
215 :sgf-gametree -- one of the gametrees in :sgf-collection
217 :monkey -- vector of two elements:
218 MEM, a pointer to one of the branches in the gametree;
219 BIDX, the index of the \"current branch\"
221 :gnugo-color -- either \"black\" or \"white\"
225 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
228 :black-captures -- these are strings since gnugo.el doesn't do anything
229 :white-captures w/ the information besides display it in the mode line;
230 gory details in functions `gnugo-propertize-board-buffer'
231 and `gnugo-merge-showboard-results' (almost more effort
232 than they are worth!)
234 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
235 `gnugo-toggle-image-display' and `gnugo-refresh',
236 as well as gnugo-xpms.el (available elsewhere)
238 :all-yy -- list of 46 keywords used as the `category' text property
239 (so that their plists, typically w/ property `display' or
240 `do-not-display') are consulted by the Emacs display engine;
241 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
242 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
244 :paren-ov -- a pair (left and right) of overlays shuffled about to indicate
245 the last move; only one is used when displaying using images
247 :last-user-bpos -- board position; keep the hapless human happy
249 As things stabilize probably more info will be added to this docstring."
251 (puthash key value gnugo-state))
253 (defun gnugo-get (key)
254 "Return the move/game/board-specific value for KEY.
256 (gethash key gnugo-state))
258 (defun gnugo--forget (&rest keys)
260 (remhash key gnugo-state)))
262 (defsubst gnugo--tree-mnum (tree)
265 (defsubst gnugo--tree-ends (tree)
268 (defsubst gnugo--set-tree-ends (tree ls)
269 (aset tree 0 (apply 'vector ls))
270 (gnugo--tree-ends tree))
272 (defun gnugo--root-node (&optional tree)
273 (aref (or tree (gnugo-get :sgf-gametree))
276 (defun gnugo-describe-internal-properties ()
277 "Pretty-print `gnugo-state' properties in another buffer.
278 Handle the big, slow-to-render, and/or uninteresting ones specially."
280 (let ((buf (current-buffer))
281 (d (gnugo-get :diamond))
283 (loop for key being the hash-keys of gnugo-state
284 using (hash-values val)
288 (format "hash: %X (%d images)"
294 (list (hash-table-count
295 (gnugo--tree-mnum val))
296 (gnugo--root-node val)
297 (gnugo--tree-ends val)))
299 (let ((mem (aref val 0)))
304 (switch-to-buffer (get-buffer-create
305 (format "%s*GNUGO Board Properties*"
306 (gnugo-get :diamond))))
309 (setq truncate-lines t)
313 (goto-char (point-min))
314 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
318 (while (re-search-forward rx (point-max) t)
319 (let ((pos (get-text-property (string-to-number (match-string 1))
320 'gnugo-position buf)))
321 (delete-region (+ 2 (match-beginning 0)) (point))
322 (insert (format " %S" pos))))))
323 (message "%d properties" (length acc))))
325 (defun gnugo-board-buffer-p (&optional buffer)
326 "Return non-nil if BUFFER is a GNUGO Board buffer."
327 (eq 'gnugo-board-mode
330 (or buffer (current-buffer)))))
332 (defun gnugo-board-user-play-ok-p (&optional buffer)
333 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
334 (with-current-buffer (or buffer (current-buffer))
335 (and gnugo-state (not (gnugo-get :waiting)))))
337 (defsubst gnugo--blackp (string)
338 (string= "black" string))
340 (defun gnugo-other (color)
341 (if (gnugo--blackp color) "white" "black"))
343 (defun gnugo-current-player ()
344 "Return the current player, either \"black\" or \"white\"."
345 (gnugo-other (gnugo-get :last-mover)))
347 (defsubst gnugo--prop<-color (color)
348 (if (gnugo--blackp color) :B :W))
350 (defsubst gnugo--gate-game-over (enable)
351 (when (and enable (gnugo-get :game-over))
352 (user-error "Sorry, game over")))
354 (defun gnugo--ERR-wait (color why)
355 (user-error "%s -- please wait for \"(%s to play)\""
358 (defun gnugo-gate (&optional in-progress-p)
359 (unless (gnugo-board-buffer-p)
360 (user-error "Wrong buffer -- try M-x gnugo"))
361 (unless (gnugo-get :proc)
362 (user-error "No \"gnugo\" process!"))
363 (let ((slow (gnugo-get :waiting)))
365 (gnugo--ERR-wait (gnugo-get :user-color)
368 "Not your turn yet"))))
369 (gnugo--gate-game-over in-progress-p))
371 (defun gnugo-sentinel (proc string)
372 (let ((status (process-status proc)))
373 (when (memq status '(exit signal))
374 (let ((buf (process-buffer proc)))
375 (when (buffer-live-p buf)
376 (with-current-buffer buf
377 (setq mode-line-process
379 (propertize (car (split-string string))
380 'face 'font-lock-warning-face)
382 (when (eq proc (gnugo-get :proc))
383 (gnugo--forget :proc))))))))
385 (defun gnugo--begin-exchange (proc filter line)
386 (declare (indent 2)) ; good time, for a rime
387 ; nice style, for a wile...
388 (set-process-filter proc filter)
389 (process-send-string proc line)
390 (process-send-string proc "\n"))
392 (defun gnugo--q (fmt &rest args)
393 "Send formatted command \"FMT ARGS...\"; wait for / return response.
394 The response is a string whose first two characters indicate the
395 status of the command. See also `gnugo-query'."
396 (let ((slow (gnugo-get :waiting))
397 (proc (gnugo-get :proc)))
399 (user-error "Sorry, still waiting for %s to %s"
400 (car slow) (if (cdr slow)
401 "receive a suggestion"
403 (process-put proc :incomplete t)
404 (process-put proc :srs "") ; synchronous return stash
405 (gnugo--begin-exchange
406 proc (lambda (proc string)
407 (let ((full (concat (process-get proc :srs)
409 (process-put proc :srs full)
410 (unless (numberp (gnugo--compare-strings
411 full (max 0 (- (length full)
414 (process-put proc :incomplete nil))))
417 (apply #'format fmt args)))
418 (while (process-get proc :incomplete)
419 (accept-process-output proc 30))
420 (prog1 (substring (process-get proc :srs) 0 -2)
421 (process-put proc :srs ""))))
423 (defun gnugo-query (message-format &rest args)
424 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
425 Return a string that omits the first two characters (corresponding
426 to the status indicator in the Go Text Protocol). Use this function
427 when you are sure the command cannot fail."
428 (substring (apply 'gnugo--q message-format args)
431 (defun gnugo--nquery (cmd)
432 (string-to-number (gnugo-query cmd)))
434 (defun gnugo-lsquery (message-format &rest args)
435 (split-string (apply 'gnugo-query message-format args)))
437 (defsubst gnugo--count-query (fmt &rest args)
438 (length (apply 'gnugo-lsquery fmt args)))
440 (defsubst gnugo--root-prop (prop &optional tree)
441 (cdr (assq prop (gnugo--root-node tree))))
443 (defun gnugo--set-root-prop (prop value &optional tree)
444 (let* ((root (gnugo--root-node tree))
445 (cur (assq prop root)))
448 (push (cons prop value)
449 (cdr (last root))))))
451 (defun gnugo-goto-pos (pos)
452 "Move point to board position POS, a letter-number string."
453 (goto-char (point-min))
454 (forward-line (- (1+ (gnugo-get :SZ))
455 (string-to-number (substring pos 1))))
457 (forward-char (+ (if (= 32 (following-char)) 1 2)
458 (* 2 (- (let ((letter (aref pos 0)))
464 (defun gnugo-f (frag)
465 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
467 (defun gnugo-yang (c)
468 (cdr (assq c '((?+ . hoshi)
470 (?X . (bmoku . bpmoku))
471 (?O . (wmoku . wpmoku))))))
473 (defun gnugo-yy (yin yang &optional momentaryp)
474 (gnugo-f (format "%d-%s"
475 yin (cond ((and (consp yang) momentaryp) (cdr yang))
476 ((consp yang) (car yang))
479 (defun gnugo-toggle-image-display ()
480 (unless (and (fboundp 'display-images-p) (display-images-p))
481 (user-error "Display does not support images, sorry"))
482 (require 'gnugo-xpms)
483 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
484 (user-error "Could not load `gnugo-xpms', sorry"))
485 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
486 (unless (eq fresh (gnugo-get :xpms))
487 (gnugo-put :xpms fresh)
488 (gnugo--forget :all-yy)))
489 (let* ((new (not (gnugo-get :display-using-images)))
490 (act (if new 'display 'do-not-display)))
492 (setcar (symbol-plist yy) act))
493 (or (gnugo-get :all-yy)
495 (prog1 (mapcar (lambda (ent)
497 (yy (gnugo-yy (cdr k) (car k))))
498 (setplist yy `(not-yet ,(cdr ent)))
502 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
504 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
505 (gnugo-put :highlight-last-move-spec
508 (get (gnugo-yy (get-text-property p 'gnugo-yin)
509 (get-text-property p 'gnugo-yang)
513 (gnugo-get :default-highlight-last-move-spec)))
514 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
515 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
516 (mapc 'delete-overlay (cdar group))
517 (setcdr (car group) nil))
518 (gnugo-put :mul (if new
521 (gnugo-put :display-using-images new)))
523 (defun gnugo-toggle-grid ()
524 "Turn the grid around the board on or off."
526 (funcall (if (memq :nogrid buffer-invisibility-spec)
527 'remove-from-invisibility-spec
528 'add-to-invisibility-spec)
530 (save-excursion (gnugo-refresh)))
532 (defun gnugo-propertize-board-buffer ()
534 (insert (substring (gnugo--q "showboard") 3))
535 (let* ((grid-props (list 'invisible :nogrid
536 'font-lock-face gnugo-grid-face))
537 (%gpad (gnugo-f 'gpad))
538 (%gspc (gnugo-f 'gspc))
539 (%lpad (gnugo-f 'lpad))
540 (%rpad (gnugo-f 'rpad))
541 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
542 (size (gnugo-get :SZ))
543 (size-string (number-to-string size)))
544 (goto-char (point-min))
545 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
546 (skip-chars-forward " ")
547 (put-text-property (1- (point)) (point) 'category %gpad)
548 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
550 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
551 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
552 (let* ((row (match-string-no-properties 1))
554 (other-edge (+ edge (* 2 size) -1))
555 (right-empty (+ other-edge (length row) 1))
556 (top-p (string= size-string row))
557 (bot-p (string= "1" row)))
558 (let* ((nL (- edge 1 (length size-string)))
560 (ov (make-overlay nL nR (current-buffer) t)))
561 (add-text-properties nL nR grid-props)
562 ;; We redundantly set `invisible' in the overlay to workaround
563 ;; a display bug whereby text *following* the overlaid text is
564 ;; displayed with the face of the overlaid text, but only when
565 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
566 ;; This has something to do w/ the bletcherous `before-string'.
567 (overlay-put ov 'invisible :nogrid)
568 (overlay-put ov 'category %lpad))
569 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
571 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
572 (truncate (- p edge) 2))
574 (yin (let ((A-p (= edge p))
575 (Z-p (= (1- other-edge) p)))
576 (cond ((and top-p A-p) 1)
585 (yang (gnugo-yang (char-after p))))
586 (add-text-properties p (1+ p)
596 (gnugo-position gnugo-yin))))
597 (unless (= (1- other-edge) p)
598 (add-text-properties (1+ p) (+ 2 p) ispc-props)
599 (put-text-property p (+ 2 p) 'intangible ival)))
600 (add-text-properties (1+ other-edge) right-empty grid-props)
601 (goto-char right-empty)
602 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
603 (let ((prop (if (string= "WH" (match-string 1))
606 (beg (match-beginning 2))
608 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
609 (gnugo-put prop (match-string-no-properties 2))))
611 (put-text-property right-empty (point) 'category %rpad)
613 (add-text-properties (1- (point)) (point-max) grid-props)
614 (skip-chars-forward " ")
615 (put-text-property (1- (point)) (point) 'category %gpad)
616 (put-text-property (point) (progn (end-of-line) (point))
619 (defun gnugo-merge-showboard-results ()
620 (let ((aft (substring (gnugo--q "showboard") 3))
621 (adj 1) ; string to buffer position adjustment
623 (sync "[0-9]* stones$")
624 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
625 ;; restrictive a condition that fails in the case of:
628 ;; ... WHITE has captured 1 stones
631 ;; ... WHITE has captured 14 stones
634 ;; where the after count has more digits than the before count,
635 ;; but shares the same leading digits. In this case, the result
636 ;; of `compare-strings' points to the SPC following the before
637 ;; count (indicated by caret in this example).
639 (bef (buffer-substring-no-properties (point-min) (point-max)))
640 (bef-start 0) (bef-idx 0)
641 (aft-start 0) (aft-idx 0)
642 aft-sync-backtrack mis inc cut new very-strange
644 (inhibit-read-only t))
645 (while (numberp (setq mis (gnugo--compare-strings
648 (setq aft-sync-backtrack nil
649 inc (if (cl-minusp mis)
652 bef-idx (+ bef-start inc)
653 aft-idx (+ aft-start inc)
654 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
657 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
658 (let ((peek (1- aft-idx)))
659 (while (not (= 32 (aref aft peek)))
660 (setq peek (1- peek)))
661 (setq aft-sync-backtrack (1+ peek))))
665 (if aft-sync-backtrack
666 (- aft-sync-backtrack aft-idx)
669 (if aft-sync-backtrack
670 (let* ((asb aft-sync-backtrack)
671 (l-p (get-text-property cut :gnugo-cf))
674 (keep (text-properties-at cut)))
675 (setq new (substring aft asb (string-match " " aft asb)))
676 (plist-put keep :gnugo-cf (cons (length new) capprop))
677 (gnugo-put capprop new)
678 (delete-char old-len)
679 (insert (apply 'propertize new keep))
680 (incf adj (- (length new) old-len)))
681 (setq new (aref aft aft-idx))
682 (insert-and-inherit (char-to-string new))
683 (let ((yin (get-text-property cut 'gnugo-yin))
684 (yang (gnugo-yang new)))
685 (add-text-properties cut (1+ cut)
689 ,(gnugo-yy yin yang))))
691 ;; do this last to avoid complications w/ font lock
692 ;; (this also means we cannot include `intangible' in `front-sticky')
693 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
694 (put-text-property cut (1+ cut) 'intangible very-strange))))))
696 (defsubst gnugo--move-prop (node)
700 (defun gnugo--as-pos-func ()
701 (lexical-let ((size (gnugo-get :SZ)))
706 (let ((col (aref cc 0)))
708 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
709 (- size (- (aref cc 1) ?a))))))))
711 (defun gnugo-move-history (&optional rsel color)
712 "Determine and return the game's move history.
713 Optional arg RSEL controls side effects and return value.
714 If nil, display the history in the echo area as \"(N moves)\"
715 followed by the space-separated list of moves. When called
716 interactively with a prefix arg (i.e., RSEL is `(4)'), display
717 similarly, but suffix with the mover (either \":B\" or \":W\").
718 RSEL may also be a symbol that selects what to return:
719 car -- the most-recent move
720 cadr -- the next-to-most-recent move
721 two -- the last two moves as a list, oldest last
722 bpos -- the last stone on the board placed by COLOR
723 For all other values of RSEL, do nothing and return nil."
725 (let* ((monkey (gnugo-get :monkey))
726 (mem (aref monkey 0))
727 (as-pos (gnugo--as-pos-func))
730 ((as-pos-maybe (x) (if (string= "resign" x)
733 (remem () (setq node (pop mem)
734 mprop (gnugo--move-prop node)))
735 (pretty () (setq move (as-pos-maybe (cdr mprop))))
736 (next (byp) (when (remem)
739 (format "%s%s" move (car mprop))
743 (tell () (message "(%d moves) %s"
745 (mapconcat 'identity (nreverse acc) " ")))
746 (finish (byp) (while mem (next byp)) (tell)))
751 (`cadr (nn) (car (nn)))
753 (`bpos (loop with prop = (gnugo--prop<-color color)
755 (eq prop (car mprop))
757 (not (string= "resign" move))
758 (not (gnugo--passp move)))
762 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
763 "A special mode for manipulating a GNUGO gametree.
765 \\{gnugo-frolic-mode-map}"
766 (setq truncate-lines t)
767 (buffer-disable-undo))
769 (defun gnugo-frolic-quit ()
770 "Kill GNUGO Frolic buffer and switch to its parent buffer."
772 (let ((bye (current-buffer)))
773 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
774 gnugo-frolic-parent-buffer))
777 (defun gnugo-frolic-return-to-origin ()
778 "Move point to the board's current position."
780 (if (not gnugo-frolic-origin)
781 (message "No origin")
782 (goto-char gnugo-frolic-origin)
783 (recenter (- (count-lines (line-beginning-position)
786 (defun gnugo-frolic-in-the-leaves ()
787 "Display the game tree in a *GNUGO Frolic* buffer.
788 This looks something like:
791 2 W -- K10 K10 K10 K10
810 with 0, 1, ... N (in this case N is 3) in the header line
811 to indicate the branches. Branch 0 is the \"main line\".
812 Point (* in this example) indicates the current position,
813 \"!\" indicates comment properties (e.g., B8, branch 1),
814 and moves not actually on the game tree (e.g., E7, branch 3)
815 are dimmed. Type \\[describe-mode] in that buffer for details."
817 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
819 (from (or gnugo-frolic-parent-buffer
821 ;; todo: use defface once we finally succumb to ‘customize’
822 (dimmed-node-face (list :inherit 'default
823 :foreground "gray50"))
824 (tree (gnugo-get :sgf-gametree))
825 (ends (copy-sequence (gnugo--tree-ends tree)))
826 (mnum (gnugo--tree-mnum tree))
829 (width (length ends))
830 (lanes (number-sequence 0 (1- width)))
831 (monkey (gnugo-get :monkey))
832 (as-pos (gnugo--as-pos-func))
833 (at (car (aref monkey 0)))
834 (bidx (aref monkey 1))
835 (valid (map 'vector (lambda (end)
836 (gethash (car end) mnum))
838 (max-move-num (apply 'max (append valid nil)))
839 (inhibit-read-only t)
845 (propertize s 'face face))
846 (fsi (properties fmt &rest args)
847 (insert (apply 'propertize
848 (apply 'format fmt args)
855 for node in (aref ends bx)
856 do (if (setq fork (on node))
859 ;; todo: ignore non-"move" nodes
860 (eq node (car (aref ends bix))))
862 (pushnew other (gethash node soil))))
867 (puthash node bx seen))
870 (switch-to-buffer buf)
873 (setq header-line-format
874 (lexical-let ((full (concat
876 (mapconcat (lambda (n)
886 `(space :width ,w))))
888 (when (eq 'left scroll-bar-mode)
889 (let ((w (or scroll-bar-width
891 nil 'scroll-bar-width)))
892 (cw (frame-char-width)))
896 (let ((fc (fringe-columns 'left t)))
900 (substring full (window-hscroll))
902 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
903 (set (make-local-variable 'gnugo-state)
904 (buffer-local-value 'gnugo-state from))
908 from max-move-num downto 1
909 do (setq props (list 'n n))
914 (goto-char (point-min))
917 n (aref ["W" "B"] (logand 1 n))))
919 do (let* ((node (unless (< (aref valid bx) n)
920 ;; todo: ignore non-"move" nodes
921 (pop (aref ends bx))))
922 (zow (list* 'bx bx props))
926 (cdr (assq :C node))))
927 (s (cond ((not node) "")
928 ((not (setq move (gnugo--move-prop node))) "-")
929 (t (funcall as-pos (cdr move))))))
932 (push 'help-echo zow))
933 (when (and ok (setq br (gethash node soil)))
934 (push (cons bx (sort br '<))
939 (cond ((and (eq at node)
942 (setq finish (point-marker)))
943 (emph s (list :inherit 'default
944 :foreground (frame-parameter
945 nil 'cursor-color))))
947 (emph s dimmed-node-face))
950 (when (progn (fsi props "\n")
951 (setq forks (nreverse forks)))
952 (let* ((margin (make-string 11 ?\s))
953 (heads (mapcar #'car forks))
954 (tails (mapcar #'cdr forks)))
956 ((spaced (lanes func)
957 (mapconcat func lanes " "))
958 ;; live to play ~ ~ ()
959 ;; play to learn (+) (-) . o O
960 ;; learn to live --ttn .M. _____U
961 (dashed (lanes func) ;;; _____ ^^^^
962 (mapconcat func lanes "-----"))
964 (spaced lanes (lambda (bx)
968 (pad-unless (condition)
979 do (let* ((one (car ls))
982 (mapcar 'car (cdr ls))
984 (apply 'append (mapcar 'cdr bef))))
987 (end (car (last ord))))
989 ((also (b e) (cnxn (number-sequence b e)
994 (pad-unless (zerop beg))
995 (dashed (number-sequence beg end)
997 (cond ((memq bx ord) "+")
1000 (pad-unless (>= end width))
1001 (also (1+ end) (1- width))
1004 (edge (apply 'append tails))
1005 (aa2u (line-beginning-position
1006 (- (1+ (length forks))))
1009 (set (make-local-variable 'gnugo-frolic-origin) finish)
1010 (gnugo-frolic-return-to-origin))))
1012 (defun gnugo--awake (how)
1013 ;; Valid HOW elements:
1014 ;; require-valid-branch
1016 ;; (line . move-string)
1017 ;; Invalid elements blissfully ignored. :-D
1018 (let* ((tree (gnugo-get :sgf-gametree))
1019 (ends (gnugo--tree-ends tree))
1020 (width (length ends))
1021 (monkey (gnugo-get :monkey))
1022 (line (case (cdr (assq 'line how))
1024 (count-lines (point-min) (line-beginning-position)))
1027 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1030 (col (current-column))
1031 (a (unless (> 10 col)
1032 (let ((try (/ (- col 10)
1034 (unless (<= width try)
1037 (when (memq 'require-valid-branch how)
1039 (user-error "No branch here")))
1040 (loop with omit = (cdr (assq 'omit how))
1041 for (name . value) in `((line . ,line)
1042 (bidx . ,(aref monkey 1))
1047 do (unless (memq name omit)
1051 (defmacro gnugo--awakened (how &rest body)
1052 (declare (indent 1))
1053 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1055 for name in '(line bidx monkey
1058 do (unless (memq name omit)
1061 (gnugo--awake ',how)
1064 (defsubst gnugo--move-to-bcol (bidx)
1065 (move-to-column (+ 10 (* 6 bidx))))
1067 (defun gnugo--swiz (direction &optional blunt)
1068 (gnugo--awakened (require-valid-branch
1071 (let* ((b (cond ((numberp blunt)
1072 (unless (and (< -1 blunt)
1074 (user-error "No such branch: %s" blunt))
1076 (t (mod (+ direction a) width))))
1077 (flit (if blunt (lambda (n)
1082 (mod (+ direction n) width))))
1083 (was (copy-sequence ends))
1084 (new-bidx (funcall flit bidx)))
1085 (loop for bx below width
1086 do (aset ends (funcall flit bx)
1088 (unless (= new-bidx bidx)
1089 (aset monkey 1 new-bidx))
1090 (gnugo-frolic-in-the-leaves)
1091 (goto-char (point-min))
1093 (gnugo--move-to-bcol b))))
1095 (defun gnugo-frolic-exchange-left ()
1096 "Exchange the current branch with the one to its left."
1100 (defun gnugo-frolic-rotate-left ()
1101 "Rotate all branches left."
1105 (defun gnugo-frolic-exchange-right ()
1106 "Exchange the current branch with the one to its right."
1110 (defun gnugo-frolic-rotate-right ()
1111 "Rotate all branches right."
1115 (defun gnugo-frolic-set-as-main-line ()
1116 "Make the current branch the main line."
1118 (gnugo--swiz nil 0))
1120 (defun gnugo-frolic-prune-branch ()
1121 "Remove the current branch from the gametree.
1122 This fails if there is only one branch in the tree.
1123 This fails if the monkey is on the current branch
1124 \(a restriction that will probably be lifted Real Soon Now\)."
1126 (gnugo--awakened (require-valid-branch
1127 (line . move-string))
1128 ;; todo: define meaningful eviction semantics; remove restriction
1130 (user-error "Cannot prune with monkey on branch"))
1132 (user-error "Cannot prune last remaining branch"))
1133 (let ((new (append ends nil)))
1134 ;; Explicit ignorance avoids byte-compiler warning.
1135 (ignore (pop (nthcdr a new)))
1136 (gnugo--set-tree-ends tree new))
1138 (aset monkey 1 (decf bidx)))
1139 (gnugo-frolic-in-the-leaves)
1141 (goto-char (point-min))
1142 (search-forward line)
1143 (gnugo--move-to-bcol (min a (- width 2))))))
1145 (defun gnugo--sideways (backwards n)
1146 (gnugo--awakened ((omit tree ends monkey bidx line))
1147 (gnugo--move-to-bcol (mod (if backwards
1152 (defun gnugo-frolic-backward-branch (&optional n)
1153 "Move backward N (default 1) branches."
1155 (gnugo--sideways t n))
1157 (defun gnugo-frolic-forward-branch (&optional n)
1158 "Move forward N (default 1) branches."
1160 (gnugo--sideways nil n))
1162 (defun gnugo--vertical (n direction)
1165 direction (- direction)))
1166 (gnugo--awakened ((line . numeric)
1167 (omit tree ends width monkey bidx))
1168 (let ((stop (if (> 0 direction)
1170 (max 0 (1- (count-lines (point-min)
1174 (loop while (not (= line stop))
1176 (forward-line direction)
1177 (incf line direction))
1178 until (get-text-property (point) 'n))
1179 until (zerop (decf n)))
1181 (gnugo--move-to-bcol a)
1182 (move-to-column col)))))
1184 (defun gnugo-frolic-previous-move (&optional n)
1185 "Move to the Nth (default 1) previous move."
1187 (gnugo--vertical n -1))
1189 (defun gnugo-frolic-next-move (&optional n)
1190 "Move to the Nth (default 1) next move."
1192 (gnugo--vertical n 1))
1194 (defun gnugo-boss-is-near ()
1195 "Do `bury-buffer' until the current one is not a GNU Board."
1197 (while (gnugo-board-buffer-p)
1200 (defsubst gnugo--passp (string)
1201 (string= "PASS" string))
1203 (defsubst gnugo--no-regrets (monkey ends)
1204 (eq (aref ends (aref monkey 1))
1207 (defun gnugo--as-cc-func ()
1208 (lexical-let ((size (gnugo-get :SZ)))
1210 (let* ((col (aref pos 0))
1211 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1212 (two (+ ?a (- size (string-to-number
1213 (substring pos 1))))))
1214 (format "%c%c" one two)))))
1216 (defsubst gnugo--decorate (node alist)
1217 ;; NB: ALIST should not have :B or :W keys.
1218 (setcdr (last node) alist))
1220 (defun gnugo-close-game (end-time resign)
1221 (gnugo-put :game-end-time end-time)
1222 (let ((now (or end-time (current-time))))
1223 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1225 (gnugo-put :game-over
1226 (if (or (eq t resign)
1227 (and (stringp resign)
1228 (string-match "[BW][+][Rr]esign" resign)))
1230 ((ls (color) (mapcar
1235 (gnugo-query "worm_stones %s" color)
1237 (let ((live (append (ls "black") (ls "white"))))
1240 (let ((dd (gnugo-query "dragon_data"))
1241 (start 0) mem color ent live dead)
1242 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1244 (setq mem (match-string 1 dd)
1245 color (match-string 2 dd)
1247 ent (cons (list color)
1248 (sort (gnugo-lsquery "dragon_stones %s" mem)
1250 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1252 (if (match-string 2 dd)
1255 (setq start (match-end 0)))
1259 (defun gnugo--unclose-game ()
1260 (gnugo--forget :game-over ; all those in -close-game
1263 (let* ((root (gnugo--root-node))
1264 (cur (assq :RE root)))
1266 (assert (not (eq cur (car root))) nil
1267 ":RE at head of root node: %S"
1271 (defun gnugo-push-move (who move)
1272 (let* ((simple (booleanp who))
1273 (ucolor (gnugo-get :user-color))
1277 (gnugo-get :gnugo-color))
1279 (start (gnugo-get :waiting-start))
1280 (now (current-time))
1281 (resignp (string= "resign" move))
1282 (passp (gnugo--passp move))
1283 (head (gnugo-move-history 'car))
1284 (onep (and head (gnugo--passp head)))
1285 (donep (or resignp (and onep passp))))
1287 (let ((accept (gnugo--q (format "play %s %s" color move))))
1288 (unless (= ?= (aref accept 0))
1289 (user-error "%s" accept))))
1291 (gnugo-merge-showboard-results))
1292 (gnugo-put :last-mover color)
1295 (string= ucolor color))
1296 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1297 ;; update :sgf-gametree and :monkey
1298 (let* ((property (gnugo--prop<-color color))
1299 (pair (cons property (cond (resignp move)
1301 (t (funcall (gnugo--as-cc-func)
1304 (monkey (gnugo-get :monkey))
1305 (mem (aref monkey 0))
1307 (tree (gnugo-get :sgf-gametree))
1308 (ends (gnugo--tree-ends tree))
1309 (mnum (gnugo--tree-mnum tree))
1310 (count (length ends))
1311 (tip-move-num (gethash tip mnum))
1312 (bidx (aref monkey 1)))
1313 ;; Detect déjà-vu. That is, when placing "A", avoid:
1319 ;; (such "variations" do not actually vary!) in favor of:
1325 ;; This linear search loses for multiple ‘old’ w/ "A",
1326 ;; a very unusual (but not invalid, sigh) situation.
1330 ;; Start with latest / highest likelihood for hit.
1331 ;; (See "to the right" comment, below.)
1332 from (if (gnugo--no-regrets monkey ends)
1336 if (setq bx (mod (+ bidx i) count)
1339 for m on (aref ends bx)
1340 while (< tip-move-num
1341 (gethash (setq node (car m))
1345 (when (equal pair (assq property node))
1353 (rotatef (aref ends bidx)
1355 (setq mem previous))
1359 (unless (gnugo--no-regrets monkey ends)
1360 (setq ends (gnugo--set-tree-ends
1361 tree (let ((ls (append ends nil)))
1362 ;; copy old to the right of new
1363 (push mem (nthcdr bidx ls))
1365 (puthash fruit (1+ (gethash tip mnum)) mnum)
1367 (aset ends bidx mem)))
1368 (setf (aref monkey 0) mem))
1370 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1372 (gnugo-close-game now resignp))
1373 (gnugo-put :waiting-start (and (not donep) now))
1376 (defun gnugo-venerate (yin yang)
1377 (let* ((fg-yy (gnugo-yy yin yang))
1378 (fg-disp (or (get fg-yy 'display)
1379 (get fg-yy 'do-not-display)))
1380 (fg-data (plist-get (cdr fg-disp) :data))
1381 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1382 (bg-disp (or (get bg-yy 'display)
1383 (get bg-yy 'do-not-display)))
1384 (bg-data (plist-get (cdr bg-disp) :data))
1388 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1389 (setq start (match-end 0))
1390 (string-to-number (match-string 1 s)))))
1391 (while (and (not (cl-minusp ncolors))
1392 (string-match ",\n" s start))
1393 (setq start (match-end 0)
1394 ncolors (1- ncolors)))
1395 (string-match "\"" s start)
1397 (new (copy-sequence fg-data))
1398 (lx (length fg-data))
1399 (sx (funcall bop fg-data))
1400 (sb (funcall bop bg-data))
1401 (color-key (aref new sx))) ; blech, heuristic
1403 (when (and (not (= color-key (aref new sx)))
1404 (cl-plusp (random 4)))
1405 (aset new sx (aref bg-data sb)))
1408 (create-image new 'xpm t :ascent 'center)))
1410 (defun gnugo-refresh (&optional nocache)
1411 "Update GNUGO Board buffer display.
1412 While a game is in progress, parenthesize the last-played stone (no parens
1413 for pass). If the buffer is currently displayed in the selected window,
1414 recenter the board (presuming there is extra space in the window). Update
1415 the mode line. Lastly, move point to the last position played by the user,
1416 if that move was not a pass.
1418 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1419 be slow. (This should normally be unnecessary; specify it only if the display
1420 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1423 (let* ((last-mover (gnugo-get :last-mover))
1424 (other (gnugo-other last-mover))
1425 (move (gnugo-move-history 'car))
1426 (game-over (gnugo-get :game-over))
1427 (inhibit-read-only t)
1429 (when (and nocache (not (gnugo-get :waiting)))
1430 (gnugo-propertize-board-buffer))
1433 (destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1434 (if (member move '("PASS" "resign"))
1435 (mapc 'delete-overlay (list l-ov r-ov))
1436 (gnugo-goto-pos move)
1438 (hspec (gnugo-get :highlight-last-move-spec))
1439 (display-value (nth 0 hspec))
1440 (l-offset (nth 1 hspec))
1441 (l-new-pos (+ p l-offset))
1442 (r-action (nth 2 hspec)))
1443 (overlay-put l-ov 'display
1444 (if (functionp display-value)
1445 (funcall display-value p)
1447 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1449 (funcall r-action r-ov)
1450 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1452 (rename-buffer (concat (gnugo-get :diamond)
1454 (format "%s(game over)"
1455 (if (string= move "resign")
1456 (concat move "ation ")
1458 (format "%s(%s to play)"
1459 (if move (concat move " ") "")
1463 (let ((live (cdr (assq 'live game-over)))
1464 (dead (cdr (assq 'dead game-over)))
1466 (unless (eq game-over (get-text-property 1 'game-over))
1467 (dolist (group (append live dead))
1468 (dolist (pos (cdr group))
1469 (gnugo-goto-pos pos)
1471 (put-text-property p (1+ p) 'group group)))
1472 (put-text-property 1 2 'game-over game-over))
1473 (dolist (group live)
1474 (when (setq pall (cdar group))
1475 (mapc 'delete-overlay pall)
1476 (setcdr (car group) nil)))
1477 (dolist (group dead)
1478 (unless (cdar group)
1479 (let (ov pall c (color (caar group)))
1480 (setq c (if (gnugo--blackp color) "x" "o"))
1481 (dolist (pos (cdr group))
1482 (gnugo-goto-pos pos)
1483 (setq p (point) ov (make-overlay p (1+ p)))
1486 (if (gnugo-get :display-using-images)
1487 ;; respect the dead individually; it takes more time
1488 ;; but that's not a problem (for them)
1489 (gnugo-venerate (get-text-property p 'gnugo-yin)
1490 (gnugo-yang (aref (upcase c) 0)))
1491 (propertize c 'face 'font-lock-warning-face)))
1493 (setcdr (car group) pall))))))
1495 (when (setq window (get-buffer-window (current-buffer)))
1496 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1497 (size (gnugo-get :SZ))
1498 (under10p (< size 10))
1499 (mul (gnugo-get :mul))
1500 (h (- (truncate (- (window-height window)
1505 (edges (window-edges window))
1506 (right-w-edge (nth 2 edges))
1507 (avail-width (- right-w-edge (nth 0 edges)))
1509 (imagesp (symbol-plist (gnugo-f 'ispc)))
1510 (w (/ (- avail-width
1515 2 ; between board and grid
1520 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1521 `(display ,(make-string h 10))
1522 '(invisible :nogrid)))
1527 (cond (imagesp (+ (* 0.5 wmul)
1533 (gspc . ,(when imagesp
1537 ;; DWR: image width alone => OBOE!
1539 ;; NB: ‘(* wmul cw)’ is the same
1540 ;; as ‘(car (image-size ... t))’.
1541 (let ((cw (frame-char-width)))
1542 (/ (+ 1.0 (* wmul cw))
1545 (lpad . ,(let ((d `(display (space :align-to ,w))))
1546 ;; We distinguish between these cases to
1547 ;; workaround a display bug whereby the
1548 ;; `before-string' is omitted entirely (not
1549 ;; rendered) when interacting w/ the text
1550 ;; mode last-move left-paren for moves in
1554 ,(apply 'propertize " " d))
1557 (space :align-to ,(1- avail-width))))))
1558 (setplist (gnugo-f (car pair)) (cdr pair)))))
1560 (let ((cur (gnugo-get :mode-line)))
1561 (unless (equal cur gnugo-mode-line)
1562 (setq cur gnugo-mode-line)
1563 (gnugo-put :mode-line cur)
1564 (gnugo-put :mode-line-form
1565 (cond ((stringp cur)
1566 (setq cur (copy-sequence cur))
1568 (while (setq cut (string-match "~[bwpmtu]" cur))
1570 (setq c (aref cur (incf cut)))
1573 `(,(intern (format "squig-%c" c))
1575 (?b '(or (gnugo-get :black-captures) 0))
1576 (?w '(or (gnugo-get :white-captures) 0))
1577 (?p '(gnugo-current-player))
1578 (?t '(let ((ws (gnugo-get :waiting-start)))
1580 (cadr (time-since ws))
1582 (?u '(or (gnugo-get :last-waiting) "-"))
1583 (?m '(let ((tree (gnugo-get :sgf-gametree))
1584 (monkey (gnugo-get :monkey)))
1585 (gethash (car (aref monkey 0))
1586 (gnugo--tree-mnum tree)
1587 ;; should be unnecessary
1590 `(let ,(delete-dups (copy-sequence acc))
1591 (format ,cur ,@(reverse (mapcar 'car acc))))))
1593 (let ((form (gnugo-get :mode-line-form)))
1594 (setq mode-line-process
1596 ;; this dynamicism is nice but excessive in its wantonness
1597 ;;- `(" [" (:eval ,form) "]")
1598 ;; this dynamicism is ok because the user triggers it
1599 (list (format " [%s]" (eval form))
1600 '(:eval (if (gnugo-get :abd)
1603 (force-mode-line-update))
1605 (when (setq last (gnugo-get :last-user-bpos))
1606 (gnugo-goto-pos last))))
1608 (defun gnugo--finish-move (buf)
1609 (run-hooks 'gnugo-post-move-hook)
1610 (with-current-buffer buf
1613 ;;;---------------------------------------------------------------------------
1614 ;;; Game play actions
1616 (defun gnugo--rename-buffer-portion (&optional back)
1617 (let ((old "to play")
1618 (new "waiting for suggestion"))
1621 (let ((name (buffer-name)))
1622 (when (string-match old name)
1623 (rename-buffer (replace-match new t t name))))))
1625 (defun gnugo-get-move-insertion-filter (proc string)
1626 (with-current-buffer (process-buffer proc)
1627 (let* ((so-far (gnugo-get :get-move-string))
1628 (full (gnugo-put :get-move-string (concat so-far string))))
1629 (when (string-match "^= \\(.+\\)\n\n" full)
1630 (destructuring-bind (pos-or-pass color . suggestion)
1631 (cons (match-string 1 full)
1632 (gnugo-get :waiting))
1633 (gnugo--forget :get-move-string
1637 (gnugo--rename-buffer-portion t)
1638 (unless (or (gnugo--passp full)
1639 (eq 'nowarp suggestion))
1640 (gnugo-goto-pos pos-or-pass))
1641 (message "%sSuggestion: %s"
1642 (gnugo-get :diamond)
1644 (let* ((donep (gnugo-push-move color pos-or-pass))
1645 (buf (current-buffer)))
1646 (gnugo--finish-move buf)
1647 (when (gnugo-get :abd)
1651 2 ;;; sec (frettoloso? dubioso!)
1652 nil (lambda (buf color)
1653 (with-current-buffer buf
1654 (gnugo-get-move color)))
1656 (gnugo-other color))))))))))))
1658 (defun gnugo-get-move (color &optional suggestion)
1659 (gnugo-put :waiting (cons color suggestion))
1660 (gnugo--begin-exchange
1661 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1662 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1663 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1664 (concat "reg_genmove " color))
1665 (accept-process-output))
1667 (defun gnugo-cleanup ()
1668 (when (gnugo-board-buffer-p)
1669 (unless (zerop (buffer-size))
1670 (message "Thank you for playing GNU Go."))
1672 (setplist sym nil) ; "...is next to fordliness." --Huxley
1673 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1674 ;; No worries, things will be Much Better w/ structs, RSN...
1676 (append (gnugo-get :all-yy)
1685 (setq gnugo-state nil)))
1687 (defun gnugo-position ()
1688 (or (get-text-property (point) 'gnugo-position)
1689 (user-error "Not a proper position point")))
1691 (defun gnugo-request-suggestion (&optional nowarp)
1692 "Request a move suggestion from GNU Go.
1693 After some time (during which you can do other stuff),
1694 Emacs displays the suggestion in the echo area and warps the
1695 cursor to the suggested position. Prefix arg inhibits warp."
1698 (gnugo--rename-buffer-portion)
1699 (gnugo-get-move (gnugo-get :user-color)
1704 (defun gnugo--user-play (pos-or-pass)
1706 (let ((donep (gnugo-push-move t pos-or-pass))
1707 (buf (current-buffer)))
1708 (gnugo--finish-move buf)
1710 (with-current-buffer buf
1711 (gnugo-get-move (gnugo-get :gnugo-color))))))
1713 (defun gnugo-move ()
1714 "Make a move on the GNUGO Board buffer.
1715 The position is computed from current point.
1716 Signal error if done out-of-turn or if game-over.
1717 To start a game try M-x gnugo."
1719 (gnugo--user-play (gnugo-position)))
1721 (defun gnugo-mouse-move (e)
1722 "Do `gnugo-move' at mouse location."
1725 (when (memq (following-char) '(?. ?+))
1728 (defun gnugo-pass ()
1729 "Make a pass on the GNUGO Board buffer.
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 "PASS"))
1735 (defun gnugo-mouse-pass (e)
1736 "Do `gnugo-pass' at mouse location."
1741 (defun gnugo-resign ()
1744 (if (not (y-or-n-p "Resign? "))
1745 (message "(not resigning)")
1746 (gnugo-push-move t "resign")
1749 (defun gnugo-animate-group (w/d)
1750 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1751 (let* ((pos (gnugo-position))
1752 (orig-b-m-p (buffer-modified-p))
1754 (unless (memq (following-char) '(?X ?O))
1755 (user-error "No stone at %s" pos))
1756 (setq blurb (message "Computing %s stones ..." w/d)
1757 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1758 (message "%s %s in group." blurb (length stones))
1759 (setplist (gnugo-f 'anim) nil)
1760 (let* ((spec (if (gnugo-get :display-using-images)
1761 (loop with yin = (get-text-property (point) 'gnugo-yin)
1762 with yang = (gnugo-yang (following-char))
1763 with up = (get (gnugo-yy yin yang t) 'display)
1764 with dn = (get (gnugo-yy yin yang) 'display)
1765 for n below (length gnugo-animation-string)
1766 collect (if (zerop (logand 1 n))
1768 (split-string gnugo-animation-string "" t)))
1770 (ovs (save-excursion
1771 (mapcar (lambda (pos)
1772 (gnugo-goto-pos pos)
1774 (ov (make-overlay p (1+ p))))
1775 (overlay-put ov 'category (gnugo-f 'anim))
1776 (overlay-put ov 'priority most-positive-fixnum)
1779 (setplist (gnugo-f 'anim) (cons 'display cell))
1780 (while (and (cdr spec) ; let last linger lest levity lost
1781 (sit-for 0.08675309)) ; jenny jenny i got your number...
1782 (setcar cell (setq spec (cdr spec)))
1783 ;; Force redisplay of overlays.
1784 (set-buffer-modified-p orig-b-m-p))
1786 (mapc 'delete-overlay ovs)
1789 (defun gnugo-display-group-data (command buffer-name)
1790 (message "Computing %s ..." command)
1791 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1792 (switch-to-buffer buffer-name)
1795 (message "Computing %s ... done." command))
1797 (defun gnugo-worm-stones ()
1798 "In the GNUGO Board buffer, animate \"worm\" at current position.
1799 Signal error if done out-of-turn or if game-over.
1800 See variable `gnugo-animation-string' for customization."
1803 (gnugo-animate-group 'worm))
1805 (defun gnugo-worm-data ()
1806 "Display in another buffer data from \"worm\" at current position.
1807 Signal error if done out-of-turn or if game-over."
1810 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1812 (defun gnugo-dragon-stones ()
1813 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1814 Signal error if done out-of-turn or if game-over.
1815 See variable `gnugo-animation-string' for customization."
1818 (gnugo-animate-group 'dragon))
1820 (defun gnugo-dragon-data ()
1821 "Display in another buffer data from \"dragon\" at current position.
1822 Signal error if done out-of-turn or if game-over."
1825 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1827 (defun gnugo-estimate-score ()
1828 "Display estimated score of a game of GNU Go.
1829 Output includes number of stones on the board and number of stones
1830 captured by each player, and the estimate of who has the advantage (and
1831 by how many stones)."
1833 (message "Est.score ...")
1834 (let ((black (gnugo--count-query "list_stones black"))
1835 (white (gnugo--count-query "list_stones white"))
1836 (black-captures (gnugo-query "captures black"))
1837 (white-captures (gnugo-query "captures white"))
1838 (est (gnugo-query "estimate_score")))
1839 ;; might as well update this
1840 (gnugo-put :black-captures black-captures)
1841 (gnugo-put :white-captures white-captures)
1842 (message "Est.score ... B %s %s | W %s %s | %s"
1843 black black-captures white white-captures est)))
1845 (defun gnugo-write-sgf-file (filename)
1846 "Save the game history to FILENAME (even if unfinished).
1847 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1848 (interactive "FWrite game as SGF file: ")
1849 (when (and (file-exists-p filename)
1850 (not (y-or-n-p "File exists. Continue? ")))
1851 (user-error "Not writing %s" filename))
1852 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1853 (set-buffer-modified-p nil))
1855 (defun gnugo--who-is-who (wait play samep)
1856 (message "GNU Go %splays as %s, you as %s (%s)"
1857 (if samep "" "now ")
1860 "NOTE: this is a switch!")))
1862 (defsubst gnugo--nodep (x)
1863 (keywordp (caar x)))
1865 (defun gnugo--SZ! (size)
1866 (gnugo-put :SZ size)
1867 (gnugo-put :center-position
1868 (funcall (gnugo--as-pos-func)
1869 (let ((c (+ -1 ?a (truncate (1+ size) 2))))
1872 (defun gnugo--plant-and-climb (collection &optional sel)
1873 (gnugo-put :sgf-collection collection)
1874 (let ((tree (nth (or sel 0) collection)))
1875 (gnugo-put :sgf-gametree tree)
1876 (gnugo-put :monkey (vector
1878 (aref (gnugo--tree-ends tree) 0)
1883 (defun gnugo-read-sgf-file (filename)
1884 "Load the first game tree from FILENAME, a file in SGF format."
1885 (interactive "fSGF file to load: ")
1886 (when (file-directory-p filename)
1887 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1888 (let (ans play wait samep coll tree game-over)
1889 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1890 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1891 (unless (= ?= (aref (setq ans (gnugo--q "loadsgf %s"
1892 (expand-file-name filename)))
1894 (user-error "%s" ans))
1895 (setq play (substring ans 2)
1896 wait (gnugo-other play)
1897 samep (string= (gnugo-get :user-color) play))
1898 (gnugo-put :last-mover wait)
1900 (gnugo-put :gnugo-color wait)
1901 (gnugo-put :user-color play))
1902 (setq coll (gnugo/sgf-create filename)
1903 tree (gnugo--plant-and-climb
1904 coll (let ((n (length coll)))
1908 ;; (let* ((q (format "Which game? (1-%d)" n))
1909 ;; (choice (1- (read-number q 1))))
1910 ;; (if (and (< -1 choice) (< choice n))
1912 ;; (message "(Selecting the first game)")
1914 ;; but this is what we use (for now) to accomodate
1915 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1917 (message "(Selecting the first game)"))
1919 ;; This is deliberately undocumented for now.
1920 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1921 (when (setq game-over (or (gnugo--root-prop :RE tree)
1922 (when (equal '("PASS" "PASS")
1923 (gnugo-move-history 'two))
1925 (gnugo-close-game nil game-over))
1926 (gnugo-put :last-user-bpos
1927 (gnugo-move-history 'bpos (gnugo-get :user-color)))
1929 (set-buffer-modified-p nil)
1930 (gnugo--who-is-who wait play samep)))
1932 (defun gnugo-magic-undo (spec &optional noalt keep)
1933 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1934 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1935 check that the position is occupied by a stone of the user's color,
1936 and if so, remove moves from the history until that position is clear.
1937 If SPEC is a positive number, remove exactly that many moves from the
1938 history, signaling an error if the history is exhausted before finishing.
1939 If SPEC Is 0 (zero), remove either one or two moves,
1940 so that you are to play next.
1941 If SPEC is not recognized, signal \"bad spec\" error.
1943 Refresh the board for each move undone. If (in the case where SPEC is
1944 a number) after finishing, the color to play is not the user's color,
1945 schedule a move by GNU Go.
1947 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1948 turn to play. Optional second arg NOALT non-nil inhibits this.
1950 Optional third arg KEEP non-nil means do not prune the undone moves
1951 from the gametree, such that they become a sub-gametree (variation)
1955 (user-color (gnugo-get :user-color))
1956 (monkey (gnugo-get :monkey))
1957 (tree (gnugo-get :sgf-gametree))
1958 (ends (gnugo--tree-ends tree))
1959 (remorseful (not (gnugo--no-regrets monkey ends)))
1961 (cond ((numberp spec)
1962 (setq n (if (zerop spec)
1963 (if (string= user-color (gnugo-get :last-mover))
1967 done (lambda () (zerop n))))
1968 ((string-match "^[a-z]" spec)
1969 (let ((pos (upcase spec)))
1970 (setq done `(lambda ()
1971 (gnugo-goto-pos ,pos)
1972 (memq (following-char) '(?. ?+))))
1973 (when (funcall done)
1974 (user-error "%s already clear" pos))
1975 (when (= (save-excursion
1976 (gnugo-goto-pos pos)
1978 (if (gnugo--blackp user-color)
1981 (user-error "%s not occupied by %s" pos user-color))))
1982 (t (user-error "Bad spec: %S" spec)))
1983 (when (gnugo-get :game-over)
1984 (gnugo--unclose-game))
1985 (while (not (funcall done))
1986 (setq ans (gnugo--q "undo"))
1987 (unless (= ?= (aref ans 0))
1988 (user-error "%s" ans))
1989 (pop (aref monkey 0))
1990 (gnugo-put :last-mover (gnugo-current-player))
1991 (gnugo-merge-showboard-results) ; all
1992 (gnugo-refresh) ; this
1994 (redisplay)) ; eye candy
1995 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1997 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1998 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
2000 (gnugo-get :center-position)))
2002 (unless (or keep remorseful)
2003 (aset ends (aref monkey 1) (aref monkey 0)))
2004 (when (and ulastp (not noalt))
2005 (gnugo-get-move (gnugo-get :gnugo-color))))))
2007 (defun gnugo-undo-one-move (&optional me-next)
2008 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
2009 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
2010 Prefix arg ME-NEXT means to arrange for you to play
2011 the color of the next move (and GNU Go the opposite).
2012 This is useful after loading an SGF file whose last
2013 move was done by the color you prefer to play:
2014 \\[gnugo-read-sgf-file] FILENAME RET
2015 C-u \\[gnugo-undo-one-move]
2017 See also `gnugo-undo-two-moves'."
2021 (let* ((play (gnugo-get :last-mover))
2022 (wait (gnugo-other play)))
2023 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
2024 (gnugo-put :user-color play)
2025 (gnugo-put :gnugo-color wait)))
2026 (gnugo-magic-undo 1 t))
2028 (defun gnugo-undo-two-moves ()
2029 "Undo a pair of moves (GNU Go's and yours).
2030 However, if you are the last mover, undo only one move.
2031 Regardless, after undoing, it is your turn to play again."
2034 (gnugo-magic-undo 0))
2036 (defun gnugo-oops (&optional position)
2037 "Like `gnugo-undo-two-moves', but keep the undone moves.
2038 The kept moves become a sub-gametree (variation) when play resumes.
2039 Prefix arg means, instead, undo repeatedly up to and including
2040 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2043 (gnugo-magic-undo (if position
2048 (defun gnugo-okay (&optional full)
2049 "Redo a pair of undone moves.
2050 Prefix arg means to redo all the undone moves."
2053 (let* ((tree (gnugo-get :sgf-gametree))
2054 (ends (gnugo--tree-ends tree))
2055 (monkey (gnugo-get :monkey)))
2056 (if (gnugo--no-regrets monkey ends)
2057 (message "Oop ack!")
2058 (let* ((as-pos (gnugo--as-pos-func))
2059 (mnum (gnugo--tree-mnum tree))
2060 (mem (aref monkey 0))
2061 (bidx (aref monkey 1))
2062 (end (aref ends bidx))
2063 (ucolor (gnugo-get :user-color))
2064 (uprop (gnugo--prop<-color ucolor)))
2065 (cl-flet ((mvno (node) (gethash node mnum)))
2069 (+ 2 (mvno (car mem))))
2070 with (node move todo)
2074 move (gnugo--move-prop node))
2075 (when (and move (>= ok (mvno node)))
2076 (let ((userp (eq uprop (car move))))
2078 (funcall as-pos (cdr move)))
2080 until (eq mem (cdr ls))
2083 for (userp pos) in todo
2085 (gnugo-push-move userp pos)
2089 (defun gnugo-display-final-score (&optional comment)
2090 "Display final score and other info in another buffer (when game over).
2091 If the game is still ongoing, Emacs asks if you wish to stop play (by
2092 making sure two \"pass\" moves are played consecutively, if necessary).
2093 Also, add the `:RE' SGF property to the root node of the game tree.
2094 Prefix arg COMMENT means to also attach the text (slightly compacted)
2095 to the last move, as a comment."
2097 (let ((game-over (gnugo-get :game-over)))
2098 (unless (or game-over
2099 (and (not (gnugo-get :waiting))
2100 (y-or-n-p "Game still in play. Stop play now? ")))
2101 (user-error "Sorry, game still in play"))
2105 (message "Playing PASS for %s ..."
2106 (gnugo-get (if userp :user-color :gnugo-color)))
2108 (gnugo-push-move userp "PASS")))
2113 (let ((b= " Black = ")
2115 (res (when (string= "resign" (gnugo-move-history 'car))
2116 (gnugo-get :last-mover)))
2120 (format "%s wins.\n"
2121 (substring (if (= ?b (aref res 0)) w= b=)
2123 "The game is over.\n"
2124 (format "Resignation by %s.\n" res))
2125 result (concat (upcase (substring (gnugo-other res) 0 1))
2127 (message "Computing final score ...")
2128 (let* ((g-over (gnugo-get :game-over))
2129 (live (cdr (assq 'live g-over)))
2130 (dead (cdr (assq 'dead g-over)))
2131 (seed (gnugo-get :scoring-seed))
2132 (terr-q (format "final_status_list %%s_territory %d" seed))
2135 (b-terr (gnugo--count-query terr-q "black"))
2136 (w-terr (gnugo--count-query terr-q "white"))
2137 (b-capt (string-to-number (gnugo-get :black-captures)))
2138 (w-capt (string-to-number (gnugo-get :white-captures)))
2139 (komi (gnugo--root-prop :KM)))
2140 (setq blurb (list "The game is over. Final score:\n")
2141 result (gnugo-query "final_score %d" seed))
2142 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2143 (dolist (group live)
2144 (incf (if (gnugo--blackp (caar group))
2147 (length (cdr group))))
2148 (dolist (group dead)
2149 (incf (if (gnugo--blackp (caar group))
2152 (length (cdr group))))
2153 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2154 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2155 w-terr terr komi 'komi (+ w-terr komi))
2158 (dolist (group dead)
2159 (incf (if (gnugo--blackp (caar group))
2162 (* 2 (length (cdr group)))))
2163 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2168 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2172 (+ w-terr w-capt komi))
2174 (push (if (string= "0" result)
2175 "The game is a draw.\n"
2176 (format "%s wins by %s.\n"
2177 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2178 (substring result 2)))
2180 (message "Computing final score ... done")))
2182 (let ((beg (gnugo-get :game-start-time))
2183 (end (gnugo-get :game-end-time)))
2187 ((yep (pretty moment)
2188 (push (format-time-string
2189 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2192 (yep "Game start" beg)
2194 (setq blurb (apply 'concat (nreverse blurb)))
2195 (gnugo--set-root-prop :RE result)
2197 (let ((node (car (aref (gnugo-get :monkey) 0))))
2199 (delq (assq :C node) node)
2200 (with-temp-buffer ; lame
2202 (when (search-backward "\n\nGame start:" nil t)
2203 (delete-region (point) (point-max)))
2204 (cl-flet ((rep (old new)
2205 (goto-char (point-min))
2206 (while (search-forward old nil t)
2207 (replace-match new))))
2208 (rep "The game is over. " "")
2209 (rep "territory" "T")
2210 (rep "captures" "C")
2212 `((:C . ,(buffer-string)))))))
2213 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2217 (defun gnugo-quit ()
2218 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2219 If the game is not over, ask for confirmation first."
2221 (if (or (gnugo-get :game-over)
2222 (y-or-n-p "Quit? "))
2224 (message "(not quitting)")))
2226 (defun gnugo-leave-me-alone ()
2227 "Kill the current buffer unconditionally."
2231 (defun gnugo-fancy-undo (count)
2232 "Rewind the game tree in various ways.
2233 Prefix arg COUNT means to undo that many moves.
2234 Otherwise, undo repeatedly up to and including the move
2235 which placed the stone at point."
2238 ;; TODO: Move this into `gnugo-magic-undo' proper.
2239 (cond ((numberp count) count)
2240 ((consp count) (car count))
2241 (t (gnugo-position)))))
2243 (defun gnugo-toggle-image-display-command () ; ugh
2244 "Toggle use of images to display the board, then refresh."
2246 (gnugo-toggle-image-display)
2247 (save-excursion (gnugo-refresh)))
2249 (defun gnugo--node-with-played-stone (pos)
2250 (let ((color (case (following-char)
2254 (loop with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
2255 for node in (aref (gnugo-get :monkey) 0)
2256 if (equal fruit (car node))
2258 finally return nil))))
2260 (defun gnugo-describe-position ()
2261 "Display the board position under cursor in the echo area.
2262 If there a stone at that position, also display its move number."
2264 (let* ((pos (gnugo-position)) ; do first (can throw)
2265 (node (gnugo--node-with-played-stone pos)))
2269 (let* ((tree (gnugo-get :sgf-gametree))
2270 (mnum (gnugo--tree-mnum tree))
2271 (move-num (gethash node mnum)))
2272 (format " (move %d)" move-num)))
2275 (defun gnugo-switch-to-another ()
2276 "Switch to another GNU Go game buffer (if any)."
2278 (loop for buf in (cdr (buffer-list))
2279 if (gnugo-board-buffer-p buf)
2282 (switch-to-buffer buf))
2283 finally do (message "(only one)")))
2285 (defun gnugo-comment (node comment)
2286 "Add to NODE a COMMENT (string) property.
2287 Called interactively, NODE is the one corresponding to the
2288 stone at point, and any previous comment is inserted as the
2289 initial-input (see `read-string').
2291 If COMMENT is nil or the empty string, remove the property entirely."
2293 (let* ((pos (gnugo-position))
2294 (node (or (gnugo--node-with-played-stone pos)
2295 (user-error "No stone at %s" pos))))
2297 (read-string (format "Comment for %s: "
2298 (gnugo-describe-position))
2299 (cdr (assq :C node))))))
2300 (setq node (delq (assq :C node) node))
2301 (unless (zerop (length comment))
2302 (gnugo--decorate node `((:C . ,comment)))))
2304 (defun gnugo-toggle-abdication ()
2305 "Toggle abdication, i.e., letting GNU Go play for you.
2306 When enabled, the mode line includes \"Abd\".
2307 Enabling signals error if the game is over.
2308 Disabling signals error if the color \"to play\" is the user color.
2309 This is to ensure that the user is the next to play after disabling."
2311 (let ((last-mover (gnugo-get :last-mover))
2312 (abd (gnugo-get :abd))
2316 (let ((gcolor (gnugo-get :gnugo-color)))
2317 (when (string= last-mover gcolor)
2318 (gnugo--ERR-wait gcolor "Sorry, too soon"))
2321 (gnugo--forget :abd)
2322 (unless (gnugo-get :waiting)
2323 (gnugo-get-move gcolor)))
2325 (gnugo--gate-game-over t)
2327 (gnugo-get-move (gnugo-other last-mover)))
2328 (message "Abdication %sabled%s"
2329 (if (gnugo-get :abd)
2334 ;;;---------------------------------------------------------------------------
2335 ;;; Command properties and gnugo-command
2337 ;; GTP commands entered by the user are never issued directly to GNU Go;
2338 ;; instead, their behavior and output are controlled by the property
2339 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2340 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2342 ;; :full -- completely interpret the command string; the value is a
2343 ;; func that takes the list of words derived from splitting the
2344 ;; command string (minus the command) and handles everything.
2346 ;; :output -- either a keyword specifying the preferred output method:
2347 ;; :message -- show output in minibuffer
2348 ;; :discard -- sometimes you just don't care;
2349 ;; or a function that takes one arg, the output string, and
2350 ;; handles it completely. default is to switch to buffer
2351 ;; "*gnugo command output*" if the output has a newline,
2352 ;; otherwise use `message'.
2354 ;; :post-thunk -- run after output processing (at the very end).
2356 (defun gnugo-command (command)
2357 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2358 Output and Emacs behavior depend on which command is given (some
2359 commands are handled completely by Emacs w/o using the subprocess;
2360 some commands have their output displayed in specially prepared
2361 buffers or in the echo area; some commands are instrumented to do
2362 gnugo.el-specific housekeeping).
2364 For example, for the command \"help\", Emacs visits the
2365 GTP command reference info page.
2367 NOTE: At this time, GTP command handling specification is still
2368 incomplete. Thus, some commands WILL confuse gnugo.el."
2369 (interactive "sCommand: ")
2370 (if (string= "" command)
2371 (message "(no command given)")
2372 (let* ((split (split-string command))
2373 (cmd (intern (car split)))
2374 (spec (get cmd :gnugo-gtp-command-spec))
2375 (full (plist-get spec :full)))
2377 (funcall full (cdr split))
2378 (message "Doing %s ..." command)
2379 (let* ((ans (gnugo--q command))
2380 (where (plist-get spec :output)))
2381 (if (string-match "unknown.command" ans)
2383 (cond ((functionp where) (funcall where ans))
2384 ((eq :discard where) (message ""))
2385 ((or (eq :message where)
2386 (not (string-match "\n" ans)))
2388 (t (switch-to-buffer "*gnugo command output*")
2391 (message "Doing %s ... done." command)))
2392 (let ((thunk (plist-get spec :post-thunk)))
2393 (when thunk (funcall thunk)))))))))
2395 ;;;---------------------------------------------------------------------------
2396 ;;; Major mode for interacting with a GNUGO subprocess
2398 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2399 "Major mode for playing GNU Go.
2400 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2401 In this mode, keys do not self insert.
2403 \\{gnugo-board-mode-map}"
2404 (buffer-disable-undo) ; todo: undo undo undoing
2405 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2407 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2408 (set (make-local-variable 'gnugo-state)
2409 (gnugo--mkht :size (1- 42)))
2410 (gnugo-put :highlight-last-move-spec
2411 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2412 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2413 (let ((ov (make-overlay 1 1)))
2414 (overlay-put ov 'display ")")
2416 (gnugo-put :mul '(1 . 1))
2417 (add-to-invisibility-spec :nogrid))
2419 ;;;---------------------------------------------------------------------------
2423 (defun gnugo (&optional new-game)
2424 "Run gnugo in a buffer, or resume a game in progress.
2425 If there is already a game in progress you may resume it instead
2426 of starting a new one. Prefix arg means skip the game-in-progress
2427 check and start a new game straight away.
2429 Before starting, Emacs queries you for additional command-line
2430 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2432 Note that specifying \"--infile FILENAME\" (or, \"-l FILENAME\")
2433 silently clobbers certain other options, such as \"--color\".
2434 For details, see info node `(gnugo) Invoking GNU Go'.
2436 \\<gnugo-board-mode-map>
2437 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2438 See `gnugo-board-mode' for a full list of commands."
2440 (let* ((all (let (acc)
2441 (dolist (buf (buffer-list))
2442 (when (gnugo-board-buffer-p buf)
2443 (push (cons (buffer-name buf) buf) acc)))
2446 (if (and (not new-game)
2448 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2449 (if (= 1 n) "" "s"))))
2454 (let ((sel (completing-read "Which one? " all nil t)))
2455 (if (string= "" sel)
2457 (assoc sel all))))))
2459 (unless (executable-find gnugo-program)
2460 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2461 ;; set up a new board
2462 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2464 (let* ((filename nil)
2465 (user-color "black")
2467 with ls = (split-string
2468 ;; todo: grok ‘gnugo --help’; completion
2471 (car gnugo-option-history)
2472 'gnugo-option-history))
2475 (let ((arg (pop ls)))
2479 (warn "%s %s ignored" opt fn)
2480 (setq filename fn))))
2482 ((string= "--color" arg)
2485 ;; Unfortunately, GTP does not provide
2486 ;; a way to query the user color, so
2487 ;; we must resort to this weirdness.
2491 ((string= "--infile" arg)
2492 (ex "--infile" (pop ls)))
2493 ((string-match "^-l" arg)
2494 (ex "-l" (if (< 2 (length arg))
2497 (t (push arg ok)))))
2498 finally return (nreverse ok)))
2499 (proc (apply 'start-process "gnugo"
2502 "--mode" "gtp" "--quiet"
2504 root board-size handicap komi)
2505 (gnugo-put :user-color user-color)
2506 (gnugo-put :proc proc)
2507 (set-process-sentinel proc 'gnugo-sentinel)
2508 ;; Emacs is too protective sometimes, blech.
2509 (set-process-query-on-exit-flag proc nil)
2510 (gnugo-put :diamond (substring (process-name proc) 5))
2511 (gnugo-put :gnugo-color (gnugo-other user-color))
2513 (gnugo-read-sgf-file (expand-file-name filename))
2517 root (loop ; hmm, available elsewhere?
2519 collect (let* ((k (pop plist))
2523 (setq root (gnugo--root-node
2524 (gnugo--plant-and-climb
2525 (gnugo/sgf-create "(;FF[4]GM[1])" t)))
2526 komi (gnugo--nquery "get_komi")
2527 handicap (gnugo--nquery "get_handicap")
2528 board-size (gnugo--nquery "query_boardsize")))
2530 :DT (format-time-string "%Y-%m-%d")
2531 :RU (if (member "--chinese-rules" args)
2534 :AP (cons "gnugo.el" gnugo-version)
2536 (let ((ub (gnugo--blackp user-color)))
2537 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2538 (if ub :PB :PW) (user-full-name)))
2539 (unless (zerop handicap)
2541 :AB (mapcar (gnugo--as-cc-func)
2542 (gnugo-lsquery "fixed_handicap %d"
2544 (gnugo-put :waiting-start (current-time))
2546 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2547 (gnugo-get :center-position)))
2549 (gnugo-put :game-start-time (current-time))
2550 (let ((g (gnugo-get :gnugo-color))
2551 (n (or (gnugo--root-prop :HA) 0))
2552 (u (gnugo-get :user-color)))
2553 (unless (gnugo-get :last-mover)
2554 (gnugo-put :last-mover
2555 (if (or (and (gnugo--blackp u) (< 1 n))
2556 (and (gnugo--blackp g) (< n 2)))
2559 (run-hooks 'gnugo-start-game-hook)
2560 (when (and (not (gnugo-get :game-over))
2561 (string= g (gnugo-current-player)))
2563 (gnugo-get-move g))))))
2565 ;;;---------------------------------------------------------------------------
2566 ;;; Load-time actions
2568 (unless gnugo-frolic-mode-map
2569 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2570 (suppress-keymap gnugo-frolic-mode-map)
2571 (mapc (lambda (pair)
2572 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2573 '(("q" . gnugo-frolic-quit)
2574 ("Q" . gnugo-frolic-quit)
2575 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2576 ("\C-b" . gnugo-frolic-backward-branch)
2577 ("\C-f" . gnugo-frolic-forward-branch)
2578 ("\C-p" . gnugo-frolic-previous-move)
2579 ("\C-n" . gnugo-frolic-next-move)
2580 ("j" . gnugo-frolic-exchange-left)
2581 ("J" . gnugo-frolic-rotate-left)
2582 ("k" . gnugo-frolic-exchange-right)
2583 ("K" . gnugo-frolic-rotate-right)
2584 ("\C-m" . gnugo-frolic-set-as-main-line)
2585 ("\C-\M-p" . gnugo-frolic-prune-branch)
2586 ("o" . gnugo-frolic-return-to-origin))))
2588 (unless gnugo-board-mode-map
2589 (setq gnugo-board-mode-map (make-sparse-keymap))
2590 (suppress-keymap gnugo-board-mode-map)
2591 (mapc (lambda (pair)
2592 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2593 '(("?" . describe-mode)
2594 ("S" . gnugo-request-suggestion)
2595 ("\C-m" . gnugo-move)
2598 ("R" . gnugo-resign)
2600 ("Q" . gnugo-leave-me-alone)
2601 ("U" . gnugo-fancy-undo)
2602 ("\M-u" . gnugo-undo-one-move)
2603 ("u" . gnugo-undo-two-moves)
2604 ("\C-?" . gnugo-undo-two-moves)
2607 ("\C-l" . gnugo-refresh)
2608 ("\M-_" . gnugo-boss-is-near)
2609 ("_" . gnugo-boss-is-near)
2610 ("h" . gnugo-move-history)
2611 ("L" . gnugo-frolic-in-the-leaves)
2612 ("i" . gnugo-toggle-image-display-command)
2613 ("w" . gnugo-worm-stones)
2614 ("W" . gnugo-worm-data)
2615 ("d" . gnugo-dragon-stones)
2616 ("D" . gnugo-dragon-data)
2617 ("g" . gnugo-toggle-grid)
2618 ("!" . gnugo-estimate-score)
2619 (":" . gnugo-command)
2620 (";" . gnugo-command)
2621 ("=" . gnugo-describe-position)
2622 ("s" . gnugo-write-sgf-file)
2623 ("\C-x\C-s" . gnugo-write-sgf-file)
2624 ("\C-x\C-w" . gnugo-write-sgf-file)
2625 ("l" . gnugo-read-sgf-file)
2626 ("F" . gnugo-display-final-score)
2627 ("A" . gnugo-switch-to-another)
2628 ("C" . gnugo-comment)
2629 ("\C-c\C-a" . gnugo-toggle-abdication)
2631 ([(down-mouse-1)] . gnugo-mouse-move)
2632 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2633 ([(down-mouse-3)] . gnugo-mouse-pass)
2634 ;; delving into the curiosities
2635 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2637 (unless (get 'help :gnugo-gtp-command-spec)
2639 ((sget (x) (get x :gnugo-gtp-command-spec))
2640 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2641 (plist-put (sget cmd) prop val)))
2642 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2645 (jam cmd (car ls) (cadr ls))
2646 (setq ls (cddr ls)))))))
2647 (cl-macrolet ((deffull (who &body body)
2648 (declare (indent 1))
2649 `(defgtp ',who :full (lambda (sel)
2653 (info "(gnugo)GTP command reference")
2654 (when sel (setq sel (intern (car sel))))
2655 (let (buffer-read-only pad cur spec output found)
2657 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2658 (goto-char (point-min))
2660 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2663 (setq pad (make-string (- (match-beginning 1)
2664 (match-beginning 0))
2668 (get (setq cur (intern (match-string 1)))
2669 :gnugo-gtp-command-spec))
2671 (note "handles this command completely"))
2672 (when (setq output (plist-get spec :output))
2673 (if (functionp output)
2674 (note "handles the output specially")
2676 (:discard (note "discards the output"))
2677 (:message (note "displays the output in the echo area")))))
2679 (setq found (match-beginning 0))))))
2680 (cond (found (goto-char found))
2682 (t (message "(no such command: %s)" sel)))))
2684 (deffull final_score
2685 ;; Explicit ignorance avoids byte-compiler warning.
2687 (gnugo-display-final-score))
2693 :post-thunk (lambda ()
2694 (gnugo--unclose-game)
2695 (gnugo--forget :last-mover)
2697 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2701 (gnugo-read-sgf-file (car sel)))
2703 (deffull (undo gg-undo)
2707 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2708 (t (car sel)))))))))
2713 ;;;---------------------------------------------------------------------------
2714 ;;; The remainder of this file defines a simplified SGF-handling library.
2715 ;;; When/if it should start to attain generality, it should be split off into
2716 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2717 ;;; "gnugo/" prefix.
2719 (defconst gnugo/sgf-*r4-properties*
2720 '((AB "Add Black" setup list stone)
2721 (AE "Add Empty" game list point)
2722 (AN "Annotation" game simpletext)
2723 (AP "Application" root (simpletext . simpletext))
2724 (AR "Arrow" - list (point . point))
2725 (AS "Who adds stones" - simpletext) ; (LOA)
2726 (AW "Add White" setup list stone)
2727 (B "Black" move move)
2728 (BL "Black time left" move real)
2729 (BM "Bad move" move double)
2730 (BR "Black rank" game simpletext)
2731 (BT "Black team" game simpletext)
2732 (C "Comment" - text)
2733 (CA "Charset" root simpletext)
2734 (CP "Copyright" game simpletext)
2735 (CR "Circle" - list point)
2736 (DD "Dim points" - elist point) ; (inherit)
2737 (DM "Even position" - double)
2738 (DO "Doubtful" move none)
2739 (DT "Date" game simpletext)
2740 (EV "Event" game simpletext)
2741 (FF "Fileformat" root [number (1 . 4)])
2742 (FG "Figure" - (or none (number . simpletext)))
2743 (GB "Good for Black" - double)
2744 (GC "Game comment" game text)
2745 (GM "Game" root [number (1 . 20)])
2746 (GN "Game name" game simpletext)
2747 (GW "Good for White" - double)
2748 (HA "Handicap" game number) ; (Go)
2749 (HO "Hotspot" - double)
2750 (IP "Initial pos." game simpletext) ; (LOA)
2751 (IT "Interesting" move none)
2752 (IY "Invert Y-axis" game simpletext) ; (LOA)
2753 (KM "Komi" game real) ; (Go)
2755 (LB "Label" - list (point . simpletext))
2756 (LN "Line" - list (point . point))
2757 (MA "Mark" - list point)
2758 (MN "set move number" move number)
2759 (N "Nodename" - simpletext)
2760 (OB "OtStones Black" move number)
2761 (ON "Opening" game text)
2762 (OT "Overtime" game simpletext)
2763 (OW "OtStones White" move number)
2764 (PB "Player Black" game simpletext)
2765 (PC "Place" game simpletext)
2766 (PL "Player to play" setup color)
2767 (PM "Print move mode" - number) ; (inherit)
2768 (PW "Player White" game simpletext)
2769 (RE "Result" game simpletext)
2770 (RO "Round" game simpletext)
2771 (RU "Rules" game simpletext)
2772 (SE "Markup" - point) ; (LOA)
2773 (SL "Selected" - list point)
2774 (SO "Source" game simpletext)
2775 (SQ "Square" - list point)
2776 (ST "Style" root [number (0 . 3)])
2777 (SU "Setup type" game simpletext) ; (LOA)
2778 (SZ "Size" root (or number (number . number)))
2779 (TB "Territory Black" - elist point) ; (Go)
2780 (TE "Tesuji" move double)
2781 (TM "Timelimit" game real)
2782 (TR "Triangle" - list point)
2783 (TW "Territory White" - elist point) ; (Go)
2784 (UC "Unclear pos" - double)
2785 (US "User" game simpletext)
2787 (VW "View" - elist point) ; (inherit)
2788 (W "White" move move)
2789 (WL "White time left" move real)
2790 (WR "White rank" game simpletext)
2791 (WT "White team" game simpletext)
2792 (LT "Lose on time" setup simpletext))
2793 ;; r4-specific notes
2794 ;; - changed: DT FG LB RE RU SZ
2795 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2796 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2798 (defun gnugo/sgf-create (file-or-data &optional data-p)
2799 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2800 FILE-OR-DATA is a file name or SGF[4] data.
2801 Optional arg DATA-P non-nil means FILE-OR-DATA is
2802 a string containing SGF[4] data.
2803 A collection is a list of gametrees, each a vector of four elements:
2805 ENDS -- a vector of node lists, with shared tails
2806 (last element of all the lists is the root node)
2808 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2809 have a move number of the previous \"move\" node (or zero)
2811 ROOT -- the root node"
2812 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2813 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2814 (put 'gnugo/sgf-*r4-properties* :keywords
2815 (mapcar (lambda (full)
2817 (intern (format ":%s" (car full)))))
2818 gnugo/sgf-*r4-properties*))))
2819 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2820 (put 'gnugo/sgf-*r4-properties* :specs
2821 (mapcar (lambda (full)
2822 (cons (car full) (cdddr full)))
2823 gnugo/sgf-*r4-properties*))))
2826 ((sw () (skip-chars-forward " \t\n"))
2827 (x (end preserve-whitespace)
2830 (:end (lambda (char) (= ?\] char)))
2831 (:mid (lambda (char) (= ?\: char)))
2832 (t (lambda (char) (or (= ?\: char)
2835 (while (not (funcall endp (setq c (following-char))))
2841 ((unless preserve-whitespace
2842 (looking-at "\\s-+"))
2843 (delete-region (point) (match-end 0))
2845 (t (forward-char 1))))
2846 (buffer-substring-no-properties beg (point))))
2847 (one (type end) (let ((s (progn
2849 (x end (eq 'text type)))))
2852 ;; blech, begone bu"tt"-ugly blatherings
2853 ;; (but bide brobdingnagian boards)...
2854 (if (and (string= "tt" s)
2859 ((simpletext color) s)
2860 ((number real double) (string-to-number s))
2863 (t (error "Unhandled type: %S" type)))))
2864 (val (spec) (cond ((symbolp spec)
2867 ;; todo: check range here.
2868 (one (aref spec 0) :end))
2869 ((eq 'or (car spec))
2870 (let ((v (one (cadr spec) t)))
2871 (if (= ?\] (following-char))
2874 ;; todo: this assumes `spec' has the form
2875 ;; (or foo (foo . bar))
2876 ;; i.e., foo is not rescanned. e.g., `SZ'.
2877 ;; probably this assumption is consistent
2878 ;; w/ the SGF authors' desire to make the
2879 ;; parsing easy, but you never know...
2880 (cons v (one (cdaddr spec) :end)))))
2881 (t (cons (one (car spec) :mid)
2882 (one (cdr spec) :end)))))
2883 (short (who) (when (eobp)
2884 (error "Unexpected EOF while reading %s" who)))
2885 (atvalp () (= ?\[ (following-char)))
2886 (PROP () (let (name spec ltype)
2887 (sw) (short 'property)
2888 (when (looking-at "[A-Z]")
2889 (setq name (read (current-buffer))
2890 spec (cdr (assq name specs)))
2893 (cdr (assq name keywords))
2894 (prog1 (if (= 1 (length spec))
2896 (unless (memq (setq ltype (car spec))
2898 (error "Bad spec: %S" spec))
2899 (if (and (eq 'elist ltype) (sw)
2902 (let ((type (cadr spec))
2904 (while (and (sw) (atvalp)
2905 (setq mo (val type)))
2910 (forward-char 1))))))
2911 (morep () (and (sw) (not (eobp))))
2912 (seek (c) (and (morep) (= c (following-char))))
2913 (seek-into (c) (when (seek c)
2916 (NODE () (when (seek-into ?\;)
2918 while (setq prop (PROP))
2920 (when (eq :SZ (car prop))
2921 (setq SZ (cdr prop)))
2930 (puthash node (+ (if (gnugo--move-prop node)
2933 (gethash prev mnum 0))
2938 (if (not (seek ?\())
2942 (loop while (seek ?\()
2943 append (TREE ls mnum)))
2947 (insert-file-contents file-or-data)
2948 (insert file-or-data)
2949 (goto-char (point-min)))
2951 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2952 (ends (TREE nil mnum))
2953 (root (car (last (car ends)))))
2954 (vector (apply 'vector ends)
2958 (defun gnugo/sgf-write-file (collection filename)
2959 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2960 (me (cons "gnugo.el" gnugo-version))
2961 (specs (mapcar (lambda (full)
2962 (cons (intern (format ":%s" (car full)))
2964 gnugo/sgf-*r4-properties*))
2967 ((esc (composed fmt arg)
2968 (mapconcat (lambda (c)
2970 ;; ‘?\[’ is not strictly required
2971 ;; but neither is it forbidden.
2972 ((?\[ ?\] ?\\) (format "\\%c" c))
2973 (?: (concat (if composed "\\" "") ":"))
2975 (string-to-list (format fmt arg))
2977 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2978 (>>two (v) (insert "["
2979 (esc t "%s" (car v))
2981 (esc t "%s" (cdr v))
2983 (>>nl () (cond ((memq name aft-newline-appreciated)
2985 ((< 60 (current-column))
2993 (insert (substring (symbol-name name) 1))
2996 (setq spec (cdr (assq name specs)))
3000 (let ((>> (if (consp (cadr spec))
3003 (dolist (little-v v)
3005 (funcall >> little-v)
3012 (loop initially (insert ";")
3016 (unless (zerop (current-column))
3020 (funcall (if (gnugo--nodep x)
3026 (dolist (tree collection)
3027 ;; take responsibility for our actions
3028 (gnugo--set-root-prop :AP me tree)
3030 (let ((ht (gnugo--mkht))
3031 (leaves (append (gnugo--tree-ends tree) nil)))
3035 with rh ; rectified history
3036 with bp ; branch point
3038 until (setq bp (gethash node ht))
3040 (push node rh) ; good for now: ½τ
3044 ;; first run: main line
3046 ;; subsequent runs: grafts (value discarded)
3048 ;; Maintain order of ‘leaves’.
3049 (let ((was (cdr bp)))
3050 (if (gnugo--nodep (car was))
3054 (setq tree (hang (pop leaves)))
3055 (mapc #'hang leaves)
3058 (write-file filename)))))
3060 ;;; gnugo.el ends here