1 ;;; gnugo.el --- play GNU Go in a buffer
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
7 ;; Package-Requires: ((ascii-art-to-unicode "1.5"))
9 ;; This program is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
14 ;; This program is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; This file provides the command `gnugo' which allows you to play the game of
28 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
29 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
30 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
31 ;; Go" to refer to the process object created by running the external program.
33 ;; At the start of a new game, you can pass additional command-line arguments
34 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
35 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
36 ;; both komi and handicap.
38 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
39 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
40 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
41 ;; back through an arbitrary stone that you played, place the cursor on a
42 ;; stone and type `U' (note: uppercase).
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 "Command to start an external program that speaks GTP, such as \"gnugo\".
98 The value may also be in the form \"PROGRAM OPTIONS...\" in which case the
99 the command `gnugo' will prefix OPTIONS in its default offering when it
100 queries you for additional options. It is an error for \"--mode\" to appear
103 For more information on GTP and GNU Go, feel free to visit:
104 http://www.gnu.org/software/gnugo")
106 (defvar gnugo-board-mode-map nil
107 "Keymap for GNUGO Board mode.")
109 (defvar gnugo-frolic-mode-map nil
110 "Keymap for GNUGO Frolic mode.")
112 (defvar gnugo-board-mode-hook nil
113 "Hook run when entering GNUGO Board mode.")
115 (defvar gnugo-start-game-hook nil
116 "Normal hook run immediately before the first move of the game.
117 To find out who is to move first, use `gnugo-current-player'.
118 See also `gnugo-board-mode'.")
120 (defvar gnugo-post-move-hook nil
121 "Normal hook run after a move and before the board is refreshed.
122 Initially, when `run-hooks' is called, the current buffer is the GNUGO
123 Board buffer of the game. Hook functions that switch buffers must take
124 care not to call (directly or indirectly through some other function)
125 `gnugo-put' or `gnugo-get' after the switch.")
127 (defvar gnugo-animation-string
128 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
129 (concat jam jam jam jam jam
130 ;; "SECRET MESSAGE HERE"
131 blink blink blink blink blink blink blink blink
132 ;; Playing go is like fighting ignorance: when you think you have
133 ;; surrounded something by knowing it very well it often turns
134 ;; out that in the time you spent deepening this understanding,
135 ;; other areas of ignorance have surrounded you.
136 spin spin spin spin spin spin spin spin spin
137 ;; Playing go is not like fighting ignorance: what one person
138 ;; knows many people may come to know; knowledge does not build
139 ;; solely move by move. Wisdom, on the other hand...
141 "String whose individual characters are used for animation.
142 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
143 render the stones in their respective result groups as the first character
144 in the string, then the next, and so on.")
146 (defvar gnugo-mode-line "~b ~w :~m :~u"
147 "A `mode-line-format'-compliant value for GNUGO Board mode.
148 If a single string, the following special escape sequences are
149 replaced with their associated information:
150 ~b,~w black,white captures (a number)
151 ~p current player (black or white)
153 ~t time waiting for the current move
154 ~u time taken for the Ultimate (most recent) move
155 The times are in seconds, or \"-\" if that information is not available.
156 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
158 (defvar gnugo-X-face 'font-lock-string-face
159 "Name of face to use for X (black) stones.")
161 (defvar gnugo-O-face 'font-lock-builtin-face
162 "Name of face to use for O (white) stones.")
164 (defvar gnugo-grid-face 'default
165 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
167 ;;;---------------------------------------------------------------------------
168 ;;; Variables for the inquisitive programmer
170 (defconst gnugo-font-lock-keywords
171 '(("X" . gnugo-X-face)
172 ("O" . gnugo-O-face))
173 "Font lock keywords for `gnugo-board-mode'.")
175 (defvar gnugo-option-history nil)
177 (defvar gnugo-state nil) ; hint: C-c C-p
180 (defvar gnugo-xpms nil))
182 (defvar gnugo-frolic-parent-buffer nil)
183 (defvar gnugo-frolic-origin nil)
185 ;;;---------------------------------------------------------------------------
186 ;;; Support functions
188 (defsubst gnugo--mkht (&rest etc)
189 (apply 'make-hash-table :test 'eq etc))
191 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
192 (compare-strings s1 beg1 nil s2 beg2 nil))
194 (defun gnugo-put (key value)
195 "Associate move/game/board-specific property KEY with VALUE.
197 There are many properties, each named by a keyword, that record and control
198 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
199 of properties, stored in the hash table `gnugo-state'. Here we document
200 some of the more stable properties. You may wish to use them as part of
201 a `gnugo-post-move-hook' function, for example. Be careful to preserve
202 the current buffer as `gnugo-state' is made into a buffer-local variable.
203 NOTE: In the following, \"see foo\" actually means \"see foo source or
204 you may never really understand to any degree of personal satisfaction\".
206 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
208 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
210 :game-over -- nil until game over at which time its value is set to
211 the alist `((live GROUP ...) (dead GROUP ...))'
213 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
214 a simple list of one or more gametrees, updated in
215 conjunction w/ :sgf-gametree and :monkey
217 :sgf-gametree -- one of the gametrees in :sgf-collection
219 :monkey -- vector of two elements:
220 MEM, a pointer to one of the branches in the gametree;
221 BIDX, the index of the \"current branch\"
223 :gnugo-color -- either \"black\" or \"white\"
227 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
230 :black-captures -- these are strings since gnugo.el doesn't do anything
231 :white-captures w/ the information besides display it in the mode line;
232 gory details in functions `gnugo-propertize-board-buffer'
233 and `gnugo-merge-showboard-results' (almost more effort
234 than they are worth!)
236 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
237 `gnugo-toggle-image-display' and `gnugo-refresh',
238 as well as gnugo-xpms.el (available elsewhere)
240 :all-yy -- list of 46 keywords used as the `category' text property
241 (so that their plists, typically w/ property `display' or
242 `do-not-display') are consulted by the Emacs display engine;
243 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
244 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
246 :paren-ov -- a pair (left and right) of overlays shuffled about to indicate
247 the last move; only one is used when displaying using images
249 :last-user-bpos -- board position; keep the hapless human happy
251 As things stabilize probably more info will be added to this docstring."
253 (puthash key value gnugo-state))
255 (defun gnugo-get (key)
256 "Return the move/game/board-specific value for KEY.
258 (gethash key gnugo-state))
260 (defun gnugo--forget (&rest keys)
262 (remhash key gnugo-state)))
264 (defsubst gnugo--tree-mnum (tree)
267 (defsubst gnugo--tree-ends (tree)
270 (defsubst gnugo--set-tree-ends (tree ls)
271 (aset tree 0 (apply 'vector ls))
272 (gnugo--tree-ends tree))
274 (defun gnugo--root-node (&optional tree)
275 (aref (or tree (gnugo-get :sgf-gametree))
278 (defun gnugo-describe-internal-properties ()
279 "Pretty-print `gnugo-state' properties in another buffer.
280 Handle the big, slow-to-render, and/or uninteresting ones specially."
282 (let ((buf (current-buffer))
283 (d (gnugo-get :diamond))
285 (loop for key being the hash-keys of gnugo-state
286 using (hash-values val)
290 (format "hash: %X (%d images)"
296 (list (hash-table-count
297 (gnugo--tree-mnum val))
298 (gnugo--root-node val)
299 (gnugo--tree-ends val)))
301 (let ((mem (aref val 0)))
306 (switch-to-buffer (get-buffer-create
307 (format "%s*GNUGO Board Properties*"
308 (gnugo-get :diamond))))
311 (setq truncate-lines t)
315 (goto-char (point-min))
316 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
320 (while (re-search-forward rx (point-max) t)
321 (let ((pos (get-text-property (string-to-number (match-string 1))
322 'gnugo-position buf)))
323 (delete-region (+ 2 (match-beginning 0)) (point))
324 (insert (format " %S" pos))))))
325 (message "%d properties" (length acc))))
327 (defun gnugo-board-buffer-p (&optional buffer)
328 "Return non-nil if BUFFER is a GNUGO Board buffer."
329 (eq 'gnugo-board-mode
332 (or buffer (current-buffer)))))
334 (defun gnugo-board-user-play-ok-p (&optional buffer)
335 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
336 (with-current-buffer (or buffer (current-buffer))
337 (and gnugo-state (not (gnugo-get :waiting)))))
339 (defsubst gnugo--blackp (string)
340 (string= "black" string))
342 (defun gnugo-other (color)
343 (if (gnugo--blackp color) "white" "black"))
345 (defun gnugo-current-player ()
346 "Return the current player, either \"black\" or \"white\"."
347 (gnugo-other (gnugo-get :last-mover)))
349 (defsubst gnugo--gate-game-over (enable)
350 (when (and enable (gnugo-get :game-over))
351 (user-error "Sorry, game over")))
353 (defun gnugo--ERR-wait (color why)
354 (user-error "%s -- please wait for \"(%s to play)\""
357 (defun gnugo-gate (&optional in-progress-p)
358 (unless (gnugo-board-buffer-p)
359 (user-error "Wrong buffer -- try M-x gnugo"))
360 (unless (gnugo-get :proc)
361 (user-error "No \"gnugo\" process!"))
362 (let ((slow (gnugo-get :waiting)))
364 (gnugo--ERR-wait (gnugo-get :user-color)
367 "Not your turn yet"))))
368 (gnugo--gate-game-over in-progress-p))
370 (defun gnugo-sentinel (proc string)
371 (let ((status (process-status proc)))
372 (when (memq status '(exit signal))
373 (let ((buf (process-buffer proc)))
374 (when (buffer-live-p buf)
375 (with-current-buffer buf
376 (setq mode-line-process
378 (propertize (car (split-string string))
379 'face 'font-lock-warning-face)
381 (when (eq proc (gnugo-get :proc))
382 (gnugo--forget :proc))))))))
384 (defun gnugo--begin-exchange (proc filter line)
385 (declare (indent 2)) ; good time, for a rime
386 ; nice style, for a wile...
387 (set-process-filter proc filter)
388 (process-send-string proc line)
389 (process-send-string proc "\n"))
391 (defun gnugo--q (fmt &rest args)
392 "Send formatted command \"FMT ARGS...\"; wait for / return response.
393 The response is a string whose first two characters indicate the
394 status of the command. See also `gnugo-query'."
395 (let ((slow (gnugo-get :waiting))
396 (proc (gnugo-get :proc)))
398 (user-error "Sorry, still waiting for %s to %s"
399 (car slow) (if (cdr slow)
400 "receive a suggestion"
402 (process-put proc :incomplete t)
403 (process-put proc :srs "") ; synchronous return stash
404 (gnugo--begin-exchange
405 proc (lambda (proc string)
406 (let ((full (concat (process-get proc :srs)
408 (process-put proc :srs full)
409 (unless (numberp (gnugo--compare-strings
410 full (max 0 (- (length full)
413 (process-put proc :incomplete nil))))
416 (apply #'format fmt args)))
417 (while (process-get proc :incomplete)
418 (accept-process-output proc 30))
419 (prog1 (substring (process-get proc :srs) 0 -2)
420 (process-put proc :srs ""))))
422 (defun gnugo-query (message-format &rest args)
423 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
424 Return a string that omits the first two characters (corresponding
425 to the status indicator in the Go Text Protocol). Use this function
426 when you are sure the command cannot fail."
427 (substring (apply 'gnugo--q message-format args)
430 (defun gnugo-lsquery (message-format &rest args)
431 (split-string (apply 'gnugo-query message-format args)))
433 (defsubst gnugo--count-query (fmt &rest args)
434 (length (apply 'gnugo-lsquery fmt args)))
436 (defsubst gnugo--root-prop (prop &optional tree)
437 (cdr (assq prop (gnugo--root-node tree))))
439 (defun gnugo--set-root-prop (prop value &optional tree)
440 (let* ((root (gnugo--root-node tree))
441 (cur (assq prop root)))
444 (push (cons prop value)
445 (cdr (last root))))))
447 (defun gnugo-goto-pos (pos)
448 "Move point to board position POS, a letter-number string."
449 (goto-char (point-min))
450 (forward-line (- (1+ (gnugo-get :SZ))
451 (string-to-number (substring pos 1))))
453 (forward-char (+ (if (= 32 (following-char)) 1 2)
454 (* 2 (- (let ((letter (aref pos 0)))
460 (defun gnugo-f (frag)
461 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
463 (defun gnugo-yang (c)
464 (cdr (assq c '((?+ . hoshi)
466 (?X . (bmoku . bpmoku))
467 (?O . (wmoku . wpmoku))))))
469 (defun gnugo-yy (yin yang &optional momentaryp)
470 (gnugo-f (format "%d-%s"
471 yin (cond ((and (consp yang) momentaryp) (cdr yang))
472 ((consp yang) (car yang))
475 (defun gnugo-toggle-image-display ()
476 (unless (and (fboundp 'display-images-p) (display-images-p))
477 (user-error "Display does not support images, sorry"))
478 (require 'gnugo-xpms)
479 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
480 (user-error "Could not load `gnugo-xpms', sorry"))
481 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
482 (unless (eq fresh (gnugo-get :xpms))
483 (gnugo-put :xpms fresh)
484 (gnugo--forget :all-yy)))
485 (let* ((new (not (gnugo-get :display-using-images)))
486 (act (if new 'display 'do-not-display)))
488 (setcar (symbol-plist yy) act))
489 (or (gnugo-get :all-yy)
491 (prog1 (mapcar (lambda (ent)
493 (yy (gnugo-yy (cdr k) (car k))))
494 (setplist yy `(not-yet ,(cdr ent)))
497 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
499 (gnugo-put :w-imul (car imul))
500 (gnugo-put :h-imul (cdr imul)))))))
501 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
502 (gnugo-put :highlight-last-move-spec
505 (get (gnugo-yy (get-text-property p 'gnugo-yin)
506 (get-text-property p 'gnugo-yang)
510 (gnugo-get :default-highlight-last-move-spec)))
511 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
512 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
513 (mapc 'delete-overlay (cdar group))
514 (setcdr (car group) nil))
515 (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
516 (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
517 (gnugo-put :display-using-images new)))
519 (defun gnugo-toggle-grid ()
520 "Turn the grid around the board on or off."
522 (funcall (if (memq :nogrid buffer-invisibility-spec)
523 'remove-from-invisibility-spec
524 'add-to-invisibility-spec)
526 (save-excursion (gnugo-refresh)))
528 (defun gnugo-propertize-board-buffer ()
530 (insert (substring (gnugo--q "showboard") 3))
531 (let* ((grid-props (list 'invisible :nogrid
532 'font-lock-face gnugo-grid-face))
533 (%gpad (gnugo-f 'gpad))
534 (%gspc (gnugo-f 'gspc))
535 (%lpad (gnugo-f 'lpad))
536 (%rpad (gnugo-f 'rpad))
537 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
538 (size (gnugo-get :SZ))
539 (size-string (number-to-string size)))
540 (goto-char (point-min))
541 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
542 (skip-chars-forward " ")
543 (put-text-property (1- (point)) (point) 'category %gpad)
544 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
546 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
547 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
548 (let* ((row (match-string-no-properties 1))
550 (other-edge (+ edge (* 2 size) -1))
551 (right-empty (+ other-edge (length row) 1))
552 (top-p (string= size-string row))
553 (bot-p (string= "1" row)))
554 (let* ((nL (- edge 1 (length size-string)))
556 (ov (make-overlay nL nR (current-buffer) t)))
557 (add-text-properties nL nR grid-props)
558 ;; We redundantly set `invisible' in the overlay to workaround
559 ;; a display bug whereby text *following* the overlaid text is
560 ;; displayed with the face of the overlaid text, but only when
561 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
562 ;; This has something to do w/ the bletcherous `before-string'.
563 (overlay-put ov 'invisible :nogrid)
564 (overlay-put ov 'category %lpad))
565 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
567 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
568 (truncate (- p edge) 2))
570 (yin (let ((A-p (= edge p))
571 (Z-p (= (1- other-edge) p)))
572 (cond ((and top-p A-p) 1)
581 (yang (gnugo-yang (char-after p))))
582 (add-text-properties p (1+ p)
592 (gnugo-position gnugo-yin))))
593 (unless (= (1- other-edge) p)
594 (add-text-properties (1+ p) (+ 2 p) ispc-props)
595 (put-text-property p (+ 2 p) 'intangible ival)))
596 (add-text-properties (1+ other-edge) right-empty grid-props)
597 (goto-char right-empty)
598 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
599 (let ((prop (if (string= "WH" (match-string 1))
602 (beg (match-beginning 2))
604 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
605 (gnugo-put prop (match-string-no-properties 2))))
607 (put-text-property right-empty (point) 'category %rpad)
609 (add-text-properties (1- (point)) (point-max) grid-props)
610 (skip-chars-forward " ")
611 (put-text-property (1- (point)) (point) 'category %gpad)
612 (put-text-property (point) (progn (end-of-line) (point))
615 (defun gnugo-merge-showboard-results ()
616 (let ((aft (substring (gnugo--q "showboard") 3))
617 (adj 1) ; string to buffer position adjustment
619 (sync "[0-9]* stones$")
620 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
621 ;; restrictive a condition that fails in the case of:
624 ;; ... WHITE has captured 1 stones
627 ;; ... WHITE has captured 14 stones
630 ;; where the after count has more digits than the before count,
631 ;; but shares the same leading digits. In this case, the result
632 ;; of `compare-strings' points to the SPC following the before
633 ;; count (indicated by caret in this example).
635 (bef (buffer-substring-no-properties (point-min) (point-max)))
636 (bef-start 0) (bef-idx 0)
637 (aft-start 0) (aft-idx 0)
638 aft-sync-backtrack mis inc cut new very-strange)
639 (while (numberp (setq mis (gnugo--compare-strings
642 (setq aft-sync-backtrack nil
643 inc (if (cl-minusp mis)
646 bef-idx (+ bef-start inc)
647 aft-idx (+ aft-start inc)
648 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
651 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
652 (let ((peek (1- aft-idx)))
653 (while (not (= 32 (aref aft peek)))
654 (setq peek (1- peek)))
655 (setq aft-sync-backtrack (1+ peek))))
659 (if aft-sync-backtrack
660 (- aft-sync-backtrack aft-idx)
663 (if aft-sync-backtrack
664 (let* ((asb aft-sync-backtrack)
665 (l-p (get-text-property cut :gnugo-cf))
668 (keep (text-properties-at cut)))
669 (setq new (substring aft asb (string-match " " aft asb)))
670 (plist-put keep :gnugo-cf (cons (length new) capprop))
671 (gnugo-put capprop new)
672 (delete-char old-len)
673 (insert (apply 'propertize new keep))
674 (incf adj (- (length new) old-len)))
675 (setq new (aref aft aft-idx))
676 (insert-and-inherit (char-to-string new))
677 (let ((yin (get-text-property cut 'gnugo-yin))
678 (yang (gnugo-yang new)))
679 (add-text-properties cut (1+ cut)
683 ,(gnugo-yy yin yang))))
685 ;; do this last to avoid complications w/ font lock
686 ;; (this also means we cannot include `intangible' in `front-sticky')
687 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
688 (put-text-property cut (1+ cut) 'intangible very-strange))))))
690 (defsubst gnugo--move-prop (node)
694 (defun gnugo--as-pos-func ()
695 (lexical-let ((size (gnugo-get :SZ)))
700 (let ((col (aref cc 0)))
702 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
703 (- size (- (aref cc 1) ?a))))))))
705 (defun gnugo-move-history (&optional rsel)
706 "Determine and return the game's move history.
707 Optional arg RSEL controls side effects and return value.
708 If nil, display the history in the echo area as \"(N moves)\"
709 followed by the space-separated list of moves. When called
710 interactively with a prefix arg (i.e., RSEL is `(4)'), display
711 similarly, but suffix with the mover (either \":B\" or \":W\").
712 RSEL may also be a symbol that selects what to return:
713 car -- the most-recent move
714 cadr -- the next-to-most-recent move
715 two -- the last two moves as a list, oldest last
716 For all other values of RSEL, do nothing and return nil."
718 (let* ((monkey (gnugo-get :monkey))
719 (mem (aref monkey 0))
720 (as-pos (gnugo--as-pos-func))
723 ((as-pos-maybe (x) (if (string= "resign" x)
726 (next (byp) (when (setq node (pop mem)
727 mprop (gnugo--move-prop node))
728 (setq move (as-pos-maybe (cdr mprop)))
730 (format "%s%s" move (car mprop))
734 (tell () (message "(%d moves) %s"
736 (mapconcat 'identity (nreverse acc) " ")))
737 (finish (byp) (while mem (next byp)) (tell)))
742 (`cadr (nn) (car (nn)))
746 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
747 "A special mode for manipulating a GNUGO gametree.
749 \\{gnugo-frolic-mode-map}"
750 (setq truncate-lines t)
751 (buffer-disable-undo))
753 (defun gnugo-frolic-quit ()
754 "Kill GNUGO Frolic buffer and switch to its parent buffer."
756 (let ((bye (current-buffer)))
757 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
758 gnugo-frolic-parent-buffer))
761 (defun gnugo-frolic-return-to-origin ()
762 "Move point to the board's current position."
764 (if (not gnugo-frolic-origin)
765 (message "No origin")
766 (goto-char gnugo-frolic-origin)
767 (recenter (- (count-lines (line-beginning-position)
770 (defun gnugo-frolic-in-the-leaves ()
771 "Display the game tree in a *GNUGO Frolic* buffer.
772 This looks something like:
775 2 W -- K10 K10 K10 K10
794 with 0, 1, ... N (in this case N is 3) in the header line
795 to indicate the branches. Branch 0 is the \"main line\".
796 Point (* in this example) indicates the current position,
797 \"!\" indicates comment properties (e.g., B8, branch 1),
798 and moves not actually on the game tree (e.g., E7, branch 3)
799 are dimmed. Type \\[describe-mode] in that buffer for details."
801 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
803 (from (or gnugo-frolic-parent-buffer
805 ;; todo: use defface once we finally succumb to ‘customize’
806 (dimmed-node-face (list :inherit 'default
807 :foreground "gray50"))
808 (tree (gnugo-get :sgf-gametree))
809 (ends (copy-sequence (gnugo--tree-ends tree)))
810 (mnum (gnugo--tree-mnum tree))
813 (width (length ends))
814 (lanes (number-sequence 0 (1- width)))
815 (monkey (gnugo-get :monkey))
816 (as-pos (gnugo--as-pos-func))
817 (at (car (aref monkey 0)))
818 (bidx (aref monkey 1))
819 (valid (map 'vector (lambda (end)
820 (gethash (car end) mnum))
822 (max-move-num (apply 'max (append valid nil)))
823 (inhibit-read-only t)
829 (propertize s 'face face))
830 (fsi (properties fmt &rest args)
831 (insert (apply 'propertize
832 (apply 'format fmt args)
839 for node in (aref ends bx)
840 do (if (setq fork (on node))
843 ;; todo: ignore non-"move" nodes
844 (eq node (car (aref ends bix))))
846 (pushnew other (gethash node soil))))
851 (puthash node bx seen))
854 (switch-to-buffer buf)
857 (setq header-line-format
858 (lexical-let ((full (concat
860 (mapconcat (lambda (n)
870 `(space :width ,w))))
872 (when (eq 'left scroll-bar-mode)
873 (let ((w (or scroll-bar-width
875 nil 'scroll-bar-width)))
876 (cw (frame-char-width)))
880 (let ((fc (fringe-columns 'left t)))
884 (substring full (window-hscroll))
886 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
887 (set (make-local-variable 'gnugo-state)
888 (buffer-local-value 'gnugo-state from))
892 from max-move-num downto 1
893 do (setq props (list 'n n))
898 (goto-char (point-min))
901 n (aref ["W" "B"] (logand 1 n))))
903 do (let* ((node (unless (< (aref valid bx) n)
904 ;; todo: ignore non-"move" nodes
905 (pop (aref ends bx))))
906 (zow (list* 'bx bx props))
910 (cdr (assq :C node))))
911 (s (cond ((not node) "")
912 ((not (setq move (gnugo--move-prop node))) "-")
913 (t (funcall as-pos (cdr move))))))
916 (push 'help-echo zow))
917 (when (and ok (setq br (gethash node soil)))
918 (push (cons bx (sort br '<))
923 (cond ((and (eq at node)
926 (setq finish (point-marker)))
927 (emph s (list :inherit 'default
928 :foreground (frame-parameter
929 nil 'cursor-color))))
931 (emph s dimmed-node-face))
934 (when (progn (fsi props "\n")
935 (setq forks (nreverse forks)))
936 (let* ((margin (make-string 11 ?\s))
937 (heads (mapcar #'car forks))
938 (tails (mapcar #'cdr forks)))
940 ((spaced (lanes func)
941 (mapconcat func lanes " "))
942 ;; live to play ~ ~ ()
943 ;; play to learn (+) (-) . o O
944 ;; learn to live --ttn .M. _____U
945 (dashed (lanes func) ;;; _____ ^^^^
946 (mapconcat func lanes "-----"))
948 (spaced lanes (lambda (bx)
952 (pad-unless (condition)
963 do (let* ((one (car ls))
966 (mapcar 'car (cdr ls))
968 (apply 'append (mapcar 'cdr bef))))
971 (end (car (last ord))))
973 ((also (b e) (cnxn (number-sequence b e)
978 (pad-unless (zerop beg))
979 (dashed (number-sequence beg end)
981 (cond ((memq bx ord) "+")
984 (pad-unless (>= end width))
985 (also (1+ end) (1- width))
988 (edge (apply 'append tails))
989 (aa2u (line-beginning-position
990 (- (1+ (length forks))))
993 (set (make-local-variable 'gnugo-frolic-origin) finish)
994 (gnugo-frolic-return-to-origin))))
996 (defun gnugo--awake (how)
997 ;; Valid HOW elements:
998 ;; require-valid-branch
1000 ;; (line . move-string)
1001 ;; Invalid elements blissfully ignored. :-D
1002 (let* ((tree (gnugo-get :sgf-gametree))
1003 (ends (gnugo--tree-ends tree))
1004 (width (length ends))
1005 (monkey (gnugo-get :monkey))
1006 (line (case (cdr (assq 'line how))
1008 (count-lines (point-min) (line-beginning-position)))
1011 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1014 (col (current-column))
1015 (a (unless (> 10 col)
1016 (let ((try (/ (- col 10)
1018 (unless (<= width try)
1021 (when (memq 'require-valid-branch how)
1023 (user-error "No branch here")))
1024 (loop with omit = (cdr (assq 'omit how))
1025 for (name . value) in `((line . ,line)
1026 (bidx . ,(aref monkey 1))
1031 do (unless (memq name omit)
1035 (defmacro gnugo--awakened (how &rest body)
1036 (declare (indent 1))
1037 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1039 for name in '(line bidx monkey
1042 do (unless (memq name omit)
1045 (gnugo--awake ',how)
1048 (defsubst gnugo--move-to-bcol (bidx)
1049 (move-to-column (+ 10 (* 6 bidx))))
1051 (defun gnugo--swiz (direction &optional blunt)
1052 (gnugo--awakened (require-valid-branch
1055 (let* ((b (cond ((numberp blunt)
1056 (unless (and (< -1 blunt)
1058 (user-error "No such branch: %s" blunt))
1060 (t (mod (+ direction a) width))))
1061 (flit (if blunt (lambda (n)
1066 (mod (+ direction n) width))))
1067 (was (copy-sequence ends))
1068 (new-bidx (funcall flit bidx)))
1069 (loop for bx below width
1070 do (aset ends (funcall flit bx)
1072 (unless (= new-bidx bidx)
1073 (aset monkey 1 new-bidx))
1074 (gnugo-frolic-in-the-leaves)
1075 (goto-char (point-min))
1077 (gnugo--move-to-bcol b))))
1079 (defun gnugo-frolic-exchange-left ()
1080 "Exchange the current branch with the one to its left."
1084 (defun gnugo-frolic-rotate-left ()
1085 "Rotate all branches left."
1089 (defun gnugo-frolic-exchange-right ()
1090 "Exchange the current branch with the one to its right."
1094 (defun gnugo-frolic-rotate-right ()
1095 "Rotate all branches right."
1099 (defun gnugo-frolic-set-as-main-line ()
1100 "Make the current branch the main line."
1102 (gnugo--swiz nil 0))
1104 (defun gnugo-frolic-prune-branch ()
1105 "Remove the current branch from the gametree.
1106 This fails if there is only one branch in the tree.
1107 This fails if the monkey is on the current branch
1108 \(a restriction that will probably be lifted Real Soon Now\)."
1110 (gnugo--awakened (require-valid-branch
1111 (line . move-string))
1112 ;; todo: define meaningful eviction semantics; remove restriction
1114 (user-error "Cannot prune with monkey on branch"))
1116 (user-error "Cannot prune last remaining branch"))
1117 (let ((new (append ends nil)))
1118 ;; Explicit ignorance avoids byte-compiler warning.
1119 (ignore (pop (nthcdr a new)))
1120 (gnugo--set-tree-ends tree new))
1122 (aset monkey 1 (decf bidx)))
1123 (gnugo-frolic-in-the-leaves)
1125 (goto-char (point-min))
1126 (search-forward line)
1127 (gnugo--move-to-bcol (min a (- width 2))))))
1129 (defun gnugo--sideways (backwards n)
1130 (gnugo--awakened ((omit tree ends monkey bidx line))
1131 (gnugo--move-to-bcol (mod (if backwards
1136 (defun gnugo-frolic-backward-branch (&optional n)
1137 "Move backward N (default 1) branches."
1139 (gnugo--sideways t n))
1141 (defun gnugo-frolic-forward-branch (&optional n)
1142 "Move forward N (default 1) branches."
1144 (gnugo--sideways nil n))
1146 (defun gnugo--vertical (n direction)
1149 direction (- direction)))
1150 (gnugo--awakened ((line . numeric)
1151 (omit tree ends width monkey bidx))
1152 (let ((stop (if (> 0 direction)
1154 (max 0 (1- (count-lines (point-min)
1158 (loop while (not (= line stop))
1160 (forward-line direction)
1161 (incf line direction))
1162 until (get-text-property (point) 'n))
1163 until (zerop (decf n)))
1165 (gnugo--move-to-bcol a)
1166 (move-to-column col)))))
1168 (defun gnugo-frolic-previous-move (&optional n)
1169 "Move to the Nth (default 1) previous move."
1171 (gnugo--vertical n -1))
1173 (defun gnugo-frolic-next-move (&optional n)
1174 "Move to the Nth (default 1) next move."
1176 (gnugo--vertical n 1))
1178 (defun gnugo-boss-is-near ()
1179 "Do `bury-buffer' until the current one is not a GNU Board."
1181 (while (gnugo-board-buffer-p)
1184 (defsubst gnugo--passp (string)
1185 (string= "PASS" string))
1187 (defsubst gnugo--no-regrets (monkey ends)
1188 (eq (aref ends (aref monkey 1))
1191 (defun gnugo--as-cc-func ()
1192 (lexical-let ((size (gnugo-get :SZ)))
1194 (let* ((col (aref pos 0))
1195 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1196 (two (+ ?a (- size (string-to-number
1197 (substring pos 1))))))
1198 (format "%c%c" one two)))))
1200 (defsubst gnugo--decorate (node alist)
1201 ;; NB: ALIST should not have :B or :W keys.
1202 (setcdr (last node) alist))
1204 (defun gnugo-close-game (end-time resign)
1205 (gnugo-put :game-end-time end-time)
1206 (let ((now (or end-time (current-time))))
1207 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1209 (gnugo-put :game-over
1210 (if (or (eq t resign)
1211 (and (stringp resign)
1212 (string-match "[BW][+][Rr]esign" resign)))
1214 ((ls (color) (mapcar
1219 (gnugo-query "worm_stones %s" color)
1221 (let ((live (append (ls "black") (ls "white"))))
1224 (let ((dd (gnugo-query "dragon_data"))
1225 (start 0) mem color ent live dead)
1226 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1228 (setq mem (match-string 1 dd)
1229 color (match-string 2 dd)
1231 ent (cons (list color)
1232 (sort (gnugo-lsquery "dragon_stones %s" mem)
1234 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1236 (if (match-string 2 dd)
1239 (setq start (match-end 0)))
1243 (defun gnugo--unclose-game ()
1244 (gnugo--forget :game-over ; all those in -close-game
1247 (let* ((root (gnugo--root-node))
1248 (cur (assq :RE root)))
1250 (assert (not (eq cur (car root))) nil
1251 ":RE at head of root node: %S"
1255 (defun gnugo-push-move (who move)
1256 (let* ((simple (booleanp who))
1257 (ucolor (gnugo-get :user-color))
1261 (gnugo-get :gnugo-color))
1263 (start (gnugo-get :waiting-start))
1264 (now (current-time))
1265 (resignp (string= "resign" move))
1266 (passp (gnugo--passp move))
1267 (head (gnugo-move-history 'car))
1268 (onep (and head (gnugo--passp head)))
1269 (donep (or resignp (and onep passp))))
1271 (let ((accept (gnugo--q (format "play %s %s" color move))))
1272 (unless (= ?= (aref accept 0))
1273 (user-error "%s" accept))))
1275 (gnugo-merge-showboard-results))
1276 (gnugo-put :last-mover color)
1279 (string= ucolor color))
1280 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1281 ;; update :sgf-gametree and :monkey
1282 (let* ((property (if (gnugo--blackp color)
1284 (pair (cons property (cond (resignp move)
1286 (t (funcall (gnugo--as-cc-func)
1289 (monkey (gnugo-get :monkey))
1290 (mem (aref monkey 0))
1292 (tree (gnugo-get :sgf-gametree))
1293 (ends (gnugo--tree-ends tree))
1294 (mnum (gnugo--tree-mnum tree))
1295 (count (length ends))
1296 (tip-move-num (gethash tip mnum))
1297 (bidx (aref monkey 1)))
1298 ;; Detect déjà-vu. That is, when placing "A", avoid:
1304 ;; (such "variations" do not actually vary!) in favor of:
1310 ;; This linear search loses for multiple ‘old’ w/ "A",
1311 ;; a very unusual (but not invalid, sigh) situation.
1315 ;; Start with latest / highest likelihood for hit.
1316 ;; (See "to the right" comment, below.)
1317 from (if (gnugo--no-regrets monkey ends)
1321 if (setq bx (mod (+ bidx i) count)
1324 for m on (aref ends bx)
1325 while (< tip-move-num
1326 (gethash (setq node (car m))
1330 (when (equal pair (assq property node))
1338 (rotatef (aref ends bidx)
1340 (setq mem previous))
1344 (unless (gnugo--no-regrets monkey ends)
1345 (setq ends (gnugo--set-tree-ends
1346 tree (let ((ls (append ends nil)))
1347 ;; copy old to the right of new
1348 (push mem (nthcdr bidx ls))
1350 (puthash fruit (1+ (gethash tip mnum)) mnum)
1352 (aset ends bidx mem)))
1353 (setf (aref monkey 0) mem))
1355 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1357 (gnugo-close-game now resignp))
1358 (gnugo-put :waiting-start (and (not donep) now))
1361 (defun gnugo-venerate (yin yang)
1362 (let* ((fg-yy (gnugo-yy yin yang))
1363 (fg-disp (or (get fg-yy 'display)
1364 (get fg-yy 'do-not-display)))
1365 (fg-data (plist-get (cdr fg-disp) :data))
1366 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1367 (bg-disp (or (get bg-yy 'display)
1368 (get bg-yy 'do-not-display)))
1369 (bg-data (plist-get (cdr bg-disp) :data))
1373 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1374 (setq start (match-end 0))
1375 (string-to-number (match-string 1 s)))))
1376 (while (and (not (cl-minusp ncolors))
1377 (string-match ",\n" s start))
1378 (setq start (match-end 0)
1379 ncolors (1- ncolors)))
1380 (string-match "\"" s start)
1382 (new (copy-sequence fg-data))
1383 (lx (length fg-data))
1384 (sx (funcall bop fg-data))
1385 (sb (funcall bop bg-data))
1386 (color-key (aref new sx))) ; blech, heuristic
1388 (when (and (not (= color-key (aref new sx)))
1389 (cl-plusp (random 4)))
1390 (aset new sx (aref bg-data sb)))
1393 (create-image new 'xpm t :ascent 'center)))
1395 (defun gnugo-refresh (&optional nocache)
1396 "Update GNUGO Board buffer display.
1397 While a game is in progress, parenthesize the last-played stone (no parens
1398 for pass). If the buffer is currently displayed in the selected window,
1399 recenter the board (presuming there is extra space in the window). Update
1400 the mode line. Lastly, move point to the last position played by the user,
1401 if that move was not a pass.
1403 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1404 be slow. (This should normally be unnecessary; specify it only if the display
1405 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1408 (when (and nocache (not (gnugo-get :waiting)))
1409 (gnugo-propertize-board-buffer))
1410 (let* ((last-mover (gnugo-get :last-mover))
1411 (other (gnugo-other last-mover))
1412 (move (gnugo-move-history 'car))
1413 (game-over (gnugo-get :game-over))
1417 (destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1418 (if (member move '("PASS" "resign"))
1419 (mapc 'delete-overlay (list l-ov r-ov))
1420 (gnugo-goto-pos move)
1422 (hspec (gnugo-get :highlight-last-move-spec))
1423 (display-value (nth 0 hspec))
1424 (l-offset (nth 1 hspec))
1425 (l-new-pos (+ p l-offset))
1426 (r-action (nth 2 hspec)))
1427 (overlay-put l-ov 'display
1428 (if (functionp display-value)
1429 (funcall display-value p)
1431 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1433 (funcall r-action r-ov)
1434 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1436 (rename-buffer (concat (gnugo-get :diamond)
1438 (format "%s(game over)"
1439 (if (string= move "resign")
1440 (concat move "ation ")
1442 (format "%s(%s to play)"
1443 (if move (concat move " ") "")
1447 (let ((live (cdr (assq 'live game-over)))
1448 (dead (cdr (assq 'dead game-over)))
1450 (unless (eq game-over (get-text-property 1 'game-over))
1451 (dolist (group (append live dead))
1452 (dolist (pos (cdr group))
1453 (gnugo-goto-pos pos)
1455 (put-text-property p (1+ p) 'group group)))
1456 (put-text-property 1 2 'game-over game-over))
1457 (dolist (group live)
1458 (when (setq pall (cdar group))
1459 (mapc 'delete-overlay pall)
1460 (setcdr (car group) nil)))
1461 (dolist (group dead)
1462 (unless (cdar group)
1463 (let (ov pall c (color (caar group)))
1464 (setq c (if (gnugo--blackp color) "x" "o"))
1465 (dolist (pos (cdr group))
1466 (gnugo-goto-pos pos)
1467 (setq p (point) ov (make-overlay p (1+ p)))
1470 (if (gnugo-get :display-using-images)
1471 ;; respect the dead individually; it takes more time
1472 ;; but that's not a problem (for them)
1473 (gnugo-venerate (get-text-property p 'gnugo-yin)
1474 (gnugo-yang (aref (upcase c) 0)))
1475 (propertize c 'face 'font-lock-warning-face)))
1477 (setcdr (car group) pall))))))
1479 (when (setq window (get-buffer-window (current-buffer)))
1480 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1481 (size (gnugo-get :SZ))
1482 (under10p (< size 10))
1483 (h (- (truncate (- (window-height window)
1484 (* size (gnugo-get :hmul))
1488 (edges (window-edges window))
1489 (right-w-edge (nth 2 edges))
1490 (avail-width (- right-w-edge (nth 0 edges)))
1491 (wmul (gnugo-get :wmul))
1492 (imagesp (symbol-plist (gnugo-f 'ispc)))
1493 (w (/ (- avail-width
1498 2 ; between board and grid
1503 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1504 `(display ,(make-string h 10))
1505 '(invisible :nogrid)))
1510 (cond (imagesp (+ (* 0.5 wmul)
1516 (gspc . ,(when imagesp
1520 ;; DWR: image width alone => OBOE!
1522 ;; NB: ‘(* wmul cw)’ is the same
1523 ;; as ‘(car (image-size ... t))’.
1524 (let ((cw (frame-char-width)))
1525 (/ (+ 1.0 (* wmul cw))
1528 (lpad . ,(let ((d `(display (space :align-to ,w))))
1529 ;; We distinguish between these cases to
1530 ;; workaround a display bug whereby the
1531 ;; `before-string' is omitted entirely (not
1532 ;; rendered) when interacting w/ the text
1533 ;; mode last-move left-paren for moves in
1537 ,(apply 'propertize " " d))
1540 (space :align-to ,(1- avail-width))))))
1541 (setplist (gnugo-f (car pair)) (cdr pair)))))
1543 (let ((cur (gnugo-get :mode-line)))
1544 (unless (equal cur gnugo-mode-line)
1545 (setq cur gnugo-mode-line)
1546 (gnugo-put :mode-line cur)
1547 (gnugo-put :mode-line-form
1548 (cond ((stringp cur)
1549 (setq cur (copy-sequence cur))
1551 (while (setq cut (string-match "~[bwpmtu]" cur))
1553 (setq c (aref cur (incf cut)))
1556 `(,(intern (format "squig-%c" c))
1558 (?b '(or (gnugo-get :black-captures) 0))
1559 (?w '(or (gnugo-get :white-captures) 0))
1560 (?p '(gnugo-current-player))
1561 (?t '(let ((ws (gnugo-get :waiting-start)))
1563 (cadr (time-since ws))
1565 (?u '(or (gnugo-get :last-waiting) "-"))
1566 (?m '(let ((tree (gnugo-get :sgf-gametree))
1567 (monkey (gnugo-get :monkey)))
1568 (gethash (car (aref monkey 0))
1569 (gnugo--tree-mnum tree)
1570 ;; should be unnecessary
1573 `(let ,(delete-dups (copy-sequence acc))
1574 (format ,cur ,@(reverse (mapcar 'car acc))))))
1576 (let ((form (gnugo-get :mode-line-form)))
1577 (setq mode-line-process
1579 ;; this dynamicism is nice but excessive in its wantonness
1580 ;;- `(" [" (:eval ,form) "]")
1581 ;; this dynamicism is ok because the user triggers it
1582 (list (format " [%s]" (eval form))
1583 '(:eval (if (gnugo-get :abd)
1586 (force-mode-line-update))
1588 (when (setq last (gnugo-get :last-user-bpos))
1589 (gnugo-goto-pos last))))
1591 (defun gnugo--finish-move (buf)
1592 (run-hooks 'gnugo-post-move-hook)
1593 (with-current-buffer buf
1596 ;;;---------------------------------------------------------------------------
1597 ;;; Game play actions
1599 (defun gnugo--rename-buffer-portion (&optional back)
1600 (let ((old "to play")
1601 (new "waiting for suggestion"))
1604 (let ((name (buffer-name)))
1605 (when (string-match old name)
1606 (rename-buffer (replace-match new t t name))))))
1608 (defun gnugo-get-move-insertion-filter (proc string)
1609 (with-current-buffer (process-buffer proc)
1610 (let* ((so-far (gnugo-get :get-move-string))
1611 (full (gnugo-put :get-move-string (concat so-far string))))
1612 (when (string-match "^= \\(.+\\)\n\n" full)
1613 (destructuring-bind (pos-or-pass color . suggestion)
1614 (cons (match-string 1 full)
1615 (gnugo-get :waiting))
1616 (gnugo--forget :get-move-string
1620 (gnugo--rename-buffer-portion t)
1621 (unless (or (gnugo--passp full)
1622 (eq 'nowarp suggestion))
1623 (gnugo-goto-pos pos-or-pass))
1624 (message "%sSuggestion: %s"
1625 (gnugo-get :diamond)
1627 (let* ((donep (gnugo-push-move color pos-or-pass))
1628 (buf (current-buffer)))
1629 (gnugo--finish-move buf)
1630 (when (gnugo-get :abd)
1634 2 ;;; sec (frettoloso? dubioso!)
1635 nil (lambda (buf color)
1636 (with-current-buffer buf
1637 (gnugo-get-move color)))
1639 (gnugo-other color))))))))))))
1641 (defun gnugo-get-move (color &optional suggestion)
1642 (gnugo-put :waiting (cons color suggestion))
1643 (gnugo--begin-exchange
1644 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1645 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1646 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1647 (concat "reg_genmove " color))
1648 (accept-process-output))
1650 (defun gnugo-cleanup ()
1651 (when (gnugo-board-buffer-p)
1652 (unless (zerop (buffer-size))
1653 (message "Thank you for playing GNU Go."))
1655 (setplist sym nil) ; "...is next to fordliness." --Huxley
1656 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1657 ;; No worries, things will be Much Better w/ structs, RSN...
1659 (append (gnugo-get :all-yy)
1668 (setq gnugo-state nil)))
1670 (defun gnugo-position ()
1671 (or (get-text-property (point) 'gnugo-position)
1672 (user-error "Not a proper position point")))
1674 (defun gnugo-request-suggestion (&optional nowarp)
1675 "Request a move suggestion from GNU Go.
1676 After some time (during which you can do other stuff),
1677 Emacs displays the suggestion in the echo area and warps the
1678 cursor to the suggested position. Prefix arg inhibits warp."
1681 (gnugo--rename-buffer-portion)
1682 (gnugo-get-move (gnugo-get :user-color)
1687 (defun gnugo--user-play (pos-or-pass)
1689 (let ((donep (gnugo-push-move t pos-or-pass))
1690 (buf (current-buffer)))
1691 (gnugo--finish-move buf)
1693 (with-current-buffer buf
1694 (gnugo-get-move (gnugo-get :gnugo-color))))))
1696 (defun gnugo-move ()
1697 "Make a move on the GNUGO Board buffer.
1698 The position is computed from current point.
1699 Signal error if done out-of-turn or if game-over.
1700 To start a game try M-x gnugo."
1702 (gnugo--user-play (gnugo-position)))
1704 (defun gnugo-mouse-move (e)
1705 "Do `gnugo-move' at mouse location."
1708 (when (memq (following-char) '(?. ?+))
1711 (defun gnugo-pass ()
1712 "Make a pass on the GNUGO Board buffer.
1713 Signal error if done out-of-turn or if game-over.
1714 To start a game try M-x gnugo."
1716 (gnugo--user-play "PASS"))
1718 (defun gnugo-mouse-pass (e)
1719 "Do `gnugo-pass' at mouse location."
1724 (defun gnugo-resign ()
1727 (if (not (y-or-n-p "Resign? "))
1728 (message "(not resigning)")
1729 (gnugo-push-move t "resign")
1732 (defun gnugo-animate-group (w/d)
1733 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1734 (let* ((pos (gnugo-position))
1735 (orig-b-m-p (buffer-modified-p))
1737 (unless (memq (following-char) '(?X ?O))
1738 (user-error "No stone at %s" pos))
1739 (setq blurb (message "Computing %s stones ..." w/d)
1740 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1741 (message "%s %s in group." blurb (length stones))
1742 (setplist (gnugo-f 'anim) nil)
1743 (let* ((spec (if (gnugo-get :display-using-images)
1744 (loop with yin = (get-text-property (point) 'gnugo-yin)
1745 with yang = (gnugo-yang (following-char))
1746 with up = (get (gnugo-yy yin yang t) 'display)
1747 with dn = (get (gnugo-yy yin yang) 'display)
1748 for n below (length gnugo-animation-string)
1749 collect (if (zerop (logand 1 n))
1751 (split-string gnugo-animation-string "" t)))
1753 (ovs (save-excursion
1754 (mapcar (lambda (pos)
1755 (gnugo-goto-pos pos)
1757 (ov (make-overlay p (1+ p))))
1758 (overlay-put ov 'category (gnugo-f 'anim))
1759 (overlay-put ov 'priority most-positive-fixnum)
1762 (setplist (gnugo-f 'anim) (cons 'display cell))
1763 (while (and (cdr spec) ; let last linger lest levity lost
1764 (sit-for 0.08675309)) ; jenny jenny i got your number...
1765 (setcar cell (setq spec (cdr spec)))
1766 ;; Force redisplay of overlays.
1767 (set-buffer-modified-p orig-b-m-p))
1769 (mapc 'delete-overlay ovs)
1772 (defun gnugo-display-group-data (command buffer-name)
1773 (message "Computing %s ..." command)
1774 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1775 (switch-to-buffer buffer-name)
1778 (message "Computing %s ... done." command))
1780 (defun gnugo-worm-stones ()
1781 "In the GNUGO Board buffer, animate \"worm\" at current position.
1782 Signal error if done out-of-turn or if game-over.
1783 See variable `gnugo-animation-string' for customization."
1786 (gnugo-animate-group 'worm))
1788 (defun gnugo-worm-data ()
1789 "Display in another buffer data from \"worm\" at current position.
1790 Signal error if done out-of-turn or if game-over."
1793 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1795 (defun gnugo-dragon-stones ()
1796 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1797 Signal error if done out-of-turn or if game-over.
1798 See variable `gnugo-animation-string' for customization."
1801 (gnugo-animate-group 'dragon))
1803 (defun gnugo-dragon-data ()
1804 "Display in another buffer data from \"dragon\" at current position.
1805 Signal error if done out-of-turn or if game-over."
1808 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1810 (defun gnugo-estimate-score ()
1811 "Display estimated score of a game of GNU Go.
1812 Output includes number of stones on the board and number of stones
1813 captured by each player, and the estimate of who has the advantage (and
1814 by how many stones)."
1816 (message "Est.score ...")
1817 (let ((black (gnugo--count-query "list_stones black"))
1818 (white (gnugo--count-query "list_stones white"))
1819 (black-captures (gnugo-query "captures black"))
1820 (white-captures (gnugo-query "captures white"))
1821 (est (gnugo-query "estimate_score")))
1822 ;; might as well update this
1823 (gnugo-put :black-captures black-captures)
1824 (gnugo-put :white-captures white-captures)
1825 (message "Est.score ... B %s %s | W %s %s | %s"
1826 black black-captures white white-captures est)))
1828 (defun gnugo-write-sgf-file (filename)
1829 "Save the game history to FILENAME (even if unfinished).
1830 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1831 (interactive "FWrite game as SGF file: ")
1832 (when (and (file-exists-p filename)
1833 (not (y-or-n-p "File exists. Continue? ")))
1834 (user-error "Not writing %s" filename))
1835 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1836 (set-buffer-modified-p nil))
1838 (defun gnugo--who-is-who (wait play samep)
1839 (message "GNU Go %splays as %s, you as %s (%s)"
1840 (if samep "" "now ")
1843 "NOTE: this is a switch!")))
1845 (defsubst gnugo--nodep (x)
1846 (keywordp (caar x)))
1848 (defsubst gnugo--SZ! (size)
1849 (gnugo-put :SZ size))
1851 (defun gnugo--plant-and-climb (collection &optional sel)
1852 (gnugo-put :sgf-collection collection)
1853 (let ((tree (nth (or sel 0) collection)))
1854 (gnugo-put :sgf-gametree tree)
1855 (gnugo-put :monkey (vector
1857 (aref (gnugo--tree-ends tree) 0)
1862 (defun gnugo-read-sgf-file (filename)
1863 "Load the first game tree from FILENAME, a file in SGF format."
1864 (interactive "fSGF file to load: ")
1865 (when (file-directory-p filename)
1866 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1867 (let (ans play wait samep coll tree)
1868 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1869 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1870 (unless (= ?= (aref (setq ans (gnugo--q "loadsgf %s"
1871 (expand-file-name filename)))
1873 (user-error "%s" ans))
1874 (setq play (substring ans 2)
1875 wait (gnugo-other play)
1876 samep (string= (gnugo-get :user-color) play))
1877 (gnugo-put :last-mover wait)
1879 (gnugo-put :gnugo-color wait)
1880 (gnugo-put :user-color play))
1881 (setq coll (gnugo/sgf-create filename)
1882 tree (gnugo--plant-and-climb
1883 coll (let ((n (length coll)))
1887 ;; (let* ((q (format "Which game? (1-%d)" n))
1888 ;; (choice (1- (read-number q 1))))
1889 ;; (if (and (< -1 choice) (< choice n))
1891 ;; (message "(Selecting the first game)")
1893 ;; but this is what we use (for now) to accomodate
1894 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1896 (message "(Selecting the first game)"))
1898 ;; This is deliberately undocumented for now.
1899 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1901 (gnugo-put :game-over
1903 (or (gnugo--root-prop :RE tree)
1904 (and (equal '("PASS" "PASS") (gnugo-move-history 'two))
1906 (when (and game-over
1907 ;; (maybe) todo: user var to inhibit (can be slow)
1909 (gnugo-close-game nil game-over)))
1911 (set-buffer-modified-p nil)
1912 (gnugo--who-is-who wait play samep)))
1914 (defun gnugo-magic-undo (spec &optional noalt keep)
1915 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1916 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1917 check that the position is occupied by a stone of the user's color,
1918 and if so, remove moves from the history until that position is clear.
1919 If SPEC is a positive number, remove exactly that many moves from the
1920 history, signaling an error if the history is exhausted before finishing.
1921 If SPEC Is 0 (zero), remove either one or two moves,
1922 so that you are to play next.
1923 If SPEC is not recognized, signal \"bad spec\" error.
1925 Refresh the board for each move undone. If (in the case where SPEC is
1926 a number) after finishing, the color to play is not the user's color,
1927 schedule a move by GNU Go.
1929 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1930 turn to play. Optional second arg NOALT non-nil inhibits this.
1932 Optional third arg KEEP non-nil means do not prune the undone moves
1933 from the gametree, such that they become a sub-gametree (variation)
1937 (user-color (gnugo-get :user-color))
1938 (monkey (gnugo-get :monkey))
1939 (tree (gnugo-get :sgf-gametree))
1940 (ends (gnugo--tree-ends tree))
1941 (remorseful (not (gnugo--no-regrets monkey ends)))
1943 (cond ((numberp spec)
1944 (setq n (if (zerop spec)
1945 (if (string= user-color (gnugo-get :last-mover))
1949 done (lambda () (zerop n))))
1950 ((string-match "^[a-z]" spec)
1951 (let ((pos (upcase spec)))
1952 (setq done `(lambda ()
1953 (gnugo-goto-pos ,pos)
1954 (memq (following-char) '(?. ?+))))
1955 (when (funcall done)
1956 (user-error "%s already clear" pos))
1957 (when (= (save-excursion
1958 (gnugo-goto-pos pos)
1960 (if (gnugo--blackp user-color)
1963 (user-error "%s not occupied by %s" pos user-color))))
1964 (t (user-error "Bad spec: %S" spec)))
1965 (when (gnugo-get :game-over)
1966 (gnugo--unclose-game))
1967 (while (not (funcall done))
1968 (setq ans (gnugo--q "undo"))
1969 (unless (= ?= (aref ans 0))
1970 (user-error "%s" ans))
1971 (pop (aref monkey 0))
1972 (gnugo-put :last-mover (gnugo-current-player))
1973 (gnugo-merge-showboard-results) ; all
1974 (gnugo-refresh) ; this
1976 (redisplay)) ; eye candy
1977 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1979 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1980 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1982 (gnugo-get :center-position)))
1984 (unless (or keep remorseful)
1985 (aset ends (aref monkey 1) (aref monkey 0)))
1986 (when (and ulastp (not noalt))
1987 (gnugo-get-move (gnugo-get :gnugo-color))))))
1989 (defun gnugo-undo-one-move (&optional me-next)
1990 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1991 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1992 Prefix arg ME-NEXT means to arrange for you to play
1993 the color of the next move (and GNU Go the opposite).
1994 This is useful after loading an SGF file whose last
1995 move was done by the color you prefer to play:
1996 \\[gnugo-read-sgf-file] FILENAME RET
1997 C-u \\[gnugo-undo-one-move]
1999 See also `gnugo-undo-two-moves'."
2002 (gnugo-magic-undo 1 t)
2004 (let* ((wait (gnugo-get :last-mover))
2005 (play (gnugo-other wait)))
2006 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
2007 (gnugo-put :user-color play)
2008 (gnugo-put :gnugo-color wait))))
2010 (defun gnugo-undo-two-moves ()
2011 "Undo a pair of moves (GNU Go's and yours).
2012 However, if you are the last mover, undo only one move.
2013 Regardless, after undoing, it is your turn to play again."
2016 (gnugo-magic-undo 0))
2018 (defun gnugo-oops (&optional position)
2019 "Like `gnugo-undo-two-moves', but keep the undone moves.
2020 The kept moves become a sub-gametree (variation) when play resumes.
2021 Prefix arg means, instead, undo repeatedly up to and including
2022 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2025 (gnugo-magic-undo (if position
2030 (defun gnugo-okay (&optional full)
2031 "Redo a pair of undone moves.
2032 Prefix arg means to redo all the undone moves."
2035 (let* ((tree (gnugo-get :sgf-gametree))
2036 (ends (gnugo--tree-ends tree))
2037 (monkey (gnugo-get :monkey)))
2038 (if (gnugo--no-regrets monkey ends)
2039 (message "Oop ack!")
2040 (let* ((as-pos (gnugo--as-pos-func))
2041 (mnum (gnugo--tree-mnum tree))
2042 (mem (aref monkey 0))
2043 (bidx (aref monkey 1))
2044 (end (aref ends bidx))
2045 (ucolor (gnugo-get :user-color))
2046 (uprop (if (gnugo--blackp ucolor)
2048 (cl-flet ((mvno (node) (gethash node mnum)))
2052 (+ 2 (mvno (car mem))))
2053 with (node move todo)
2057 move (gnugo--move-prop node))
2058 (when (and move (>= ok (mvno node)))
2059 (let ((userp (eq uprop (car move))))
2061 (funcall as-pos (cdr move)))
2063 until (eq mem (cdr ls))
2066 for (userp pos) in todo
2068 (gnugo-push-move userp pos)
2072 (defun gnugo-display-final-score (&optional comment)
2073 "Display final score and other info in another buffer (when game over).
2074 If the game is still ongoing, Emacs asks if you wish to stop play (by
2075 making sure two \"pass\" moves are played consecutively, if necessary).
2076 Also, add the `:RE' SGF property to the root node of the game tree.
2077 Prefix arg COMMENT means to also attach the text (slightly compacted)
2078 to the last move, as a comment."
2080 (let ((game-over (gnugo-get :game-over)))
2081 (unless (or game-over
2082 (and (not (gnugo-get :waiting))
2083 (y-or-n-p "Game still in play. Stop play now? ")))
2084 (user-error "Sorry, game still in play"))
2088 (message "Playing PASS for %s ..."
2089 (gnugo-get (if userp :user-color :gnugo-color)))
2091 (gnugo-push-move userp "PASS")))
2096 (let ((b= " Black = ")
2098 (res (when (string= "resign" (gnugo-move-history 'car))
2099 (gnugo-get :last-mover)))
2103 (format "%s wins.\n"
2104 (substring (if (= ?b (aref res 0)) w= b=)
2106 "The game is over.\n"
2107 (format "Resignation by %s.\n" res))
2108 result (concat (upcase (substring (gnugo-other res) 0 1))
2110 (message "Computing final score ...")
2111 (let* ((g-over (gnugo-get :game-over))
2112 (live (cdr (assq 'live g-over)))
2113 (dead (cdr (assq 'dead g-over)))
2114 (seed (gnugo-get :scoring-seed))
2115 (terr-q (format "final_status_list %%s_territory %d" seed))
2118 (b-terr (gnugo--count-query terr-q "black"))
2119 (w-terr (gnugo--count-query terr-q "white"))
2120 (b-capt (string-to-number (gnugo-get :black-captures)))
2121 (w-capt (string-to-number (gnugo-get :white-captures)))
2122 (komi (gnugo--root-prop :KM)))
2123 (setq blurb (list "The game is over. Final score:\n")
2124 result (gnugo-query "final_score %d" seed))
2125 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2126 (dolist (group live)
2127 (incf (if (gnugo--blackp (caar group))
2130 (length (cdr group))))
2131 (dolist (group dead)
2132 (incf (if (gnugo--blackp (caar group))
2135 (length (cdr group))))
2136 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2137 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2138 w-terr terr komi 'komi (+ w-terr komi))
2141 (dolist (group dead)
2142 (incf (if (gnugo--blackp (caar group))
2145 (* 2 (length (cdr group)))))
2146 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2151 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2155 (+ w-terr w-capt komi))
2157 (push (if (string= "0" result)
2158 "The game is a draw.\n"
2159 (format "%s wins by %s.\n"
2160 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2161 (substring result 2)))
2163 (message "Computing final score ... done")))
2165 (let ((beg (gnugo-get :game-start-time))
2166 (end (gnugo-get :game-end-time)))
2170 ((yep (pretty moment)
2171 (push (format-time-string
2172 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2175 (yep "Game start" beg)
2177 (setq blurb (apply 'concat (nreverse blurb)))
2178 (gnugo--set-root-prop :RE result)
2180 (let ((node (car (aref (gnugo-get :monkey) 0))))
2182 (delq (assq :C node) node)
2183 (with-temp-buffer ; lame
2185 (when (search-backward "\n\nGame start:" nil t)
2186 (delete-region (point) (point-max)))
2187 (cl-flet ((rep (old new)
2188 (goto-char (point-min))
2189 (while (search-forward old nil t)
2190 (replace-match new))))
2191 (rep "The game is over. " "")
2192 (rep "territory" "T")
2193 (rep "captures" "C")
2195 `((:C . ,(buffer-string)))))))
2196 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2200 (defun gnugo-quit ()
2201 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2202 If the game is not over, ask for confirmation first."
2204 (if (or (gnugo-get :game-over)
2205 (y-or-n-p "Quit? "))
2207 (message "(not quitting)")))
2209 (defun gnugo-leave-me-alone ()
2210 "Kill the current buffer unconditionally."
2214 (defun gnugo-fancy-undo (count)
2215 "Rewind the game tree in various ways.
2216 Prefix arg COUNT means to undo that many moves.
2217 Otherwise, undo repeatedly up to and including the move
2218 which placed the stone at point."
2221 ;; TODO: Move this into `gnugo-magic-undo' proper.
2222 (cond ((numberp count) count)
2223 ((consp count) (car count))
2224 (t (gnugo-position)))))
2226 (defun gnugo-toggle-image-display-command () ; ugh
2227 "Toggle use of images to display the board, then refresh."
2229 (gnugo-toggle-image-display)
2230 (save-excursion (gnugo-refresh)))
2232 (defun gnugo--node-with-played-stone (pos)
2233 (let ((color (case (following-char)
2237 (loop with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
2238 for node in (aref (gnugo-get :monkey) 0)
2239 if (equal fruit (car node))
2241 finally return nil))))
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)))
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 (or (gnugo--node-with-played-stone pos)
2278 (user-error "No stone at %s" pos))))
2280 (read-string (format "Comment for %s: "
2281 (gnugo-describe-position))
2282 (cdr (assq :C node))))))
2283 (setq node (delq (assq :C node) node))
2284 (unless (zerop (length comment))
2285 (gnugo--decorate node `((:C . ,comment)))))
2287 (defun gnugo-toggle-abdication ()
2288 "Toggle abdication, i.e., letting GNU Go play for you.
2289 When enabled, the mode line includes \"Abd\".
2290 Enabling signals error if the game is over.
2291 Disabling signals error if the color \"to play\" is the user color.
2292 This is to ensure that the user is the next to play after disabling."
2294 (let ((last-mover (gnugo-get :last-mover))
2295 (abd (gnugo-get :abd))
2299 (destructuring-bind (gcolor ucolor &optional color . suggestion)
2300 (list* (gnugo-get :gnugo-color)
2301 (gnugo-get :user-color)
2302 (gnugo-get :waiting))
2303 (assert (not suggestion))
2304 (when (string= last-mover gcolor)
2305 (gnugo--ERR-wait gcolor "Sorry, too soon"))
2308 (gnugo--forget :abd)
2310 (gnugo-get-move gcolor)))
2312 (gnugo--gate-game-over t)
2314 (gnugo-get-move (gnugo-other last-mover)))
2315 (message "Abdication %sabled%s"
2316 (if (gnugo-get :abd)
2321 ;;;---------------------------------------------------------------------------
2322 ;;; Command properties and gnugo-command
2324 ;; GTP commands entered by the user are never issued directly to GNU Go;
2325 ;; instead, their behavior and output are controlled by the property
2326 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2327 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2329 ;; :full -- completely interpret the command string; the value is a
2330 ;; func that takes the list of words derived from splitting the
2331 ;; command string (minus the command) and handles everything.
2333 ;; :output -- either a keyword specifying the preferred output method:
2334 ;; :message -- show output in minibuffer
2335 ;; :discard -- sometimes you just don't care;
2336 ;; or a function that takes one arg, the output string, and
2337 ;; handles it completely. default is to switch to buffer
2338 ;; "*gnugo command output*" if the output has a newline,
2339 ;; otherwise use `message'.
2341 ;; :post-thunk -- run after output processing (at the very end).
2343 (defun gnugo-command (command)
2344 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2345 Output and Emacs behavior depend on which command is given (some
2346 commands are handled completely by Emacs w/o using the subprocess;
2347 some commands have their output displayed in specially prepared
2348 buffers or in the echo area; some commands are instrumented to do
2349 gnugo.el-specific housekeeping).
2351 For example, for the command \"help\", Emacs visits the
2352 GTP command reference info page.
2354 NOTE: At this time, GTP command handling specification is still
2355 incomplete. Thus, some commands WILL confuse gnugo.el."
2356 (interactive "sCommand: ")
2357 (if (string= "" command)
2358 (message "(no command given)")
2359 (let* ((split (split-string command))
2360 (cmd (intern (car split)))
2361 (spec (get cmd :gnugo-gtp-command-spec))
2362 (full (plist-get spec :full)))
2364 (funcall full (cdr split))
2365 (message "Doing %s ..." command)
2366 (let* ((ans (gnugo--q command))
2367 (where (plist-get spec :output)))
2368 (if (string-match "unknown.command" ans)
2370 (cond ((functionp where) (funcall where ans))
2371 ((eq :discard where) (message ""))
2372 ((or (eq :message where)
2373 (not (string-match "\n" ans)))
2375 (t (switch-to-buffer "*gnugo command output*")
2378 (message "Doing %s ... done." command)))
2379 (let ((thunk (plist-get spec :post-thunk)))
2380 (when thunk (funcall thunk)))))))))
2382 ;;;---------------------------------------------------------------------------
2383 ;;; Major mode for interacting with a GNUGO subprocess
2385 (put 'gnugo-board-mode 'mode-class 'special)
2386 (defun gnugo-board-mode ()
2387 "Major mode for playing GNU Go.
2388 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2389 In this mode, keys do not self insert.
2391 \\{gnugo-board-mode-map}"
2392 (buffer-disable-undo) ; todo: undo undo undoing
2393 (kill-all-local-variables)
2394 (use-local-map gnugo-board-mode-map)
2395 (set (make-local-variable 'font-lock-defaults)
2396 '(gnugo-font-lock-keywords t))
2397 (setq major-mode 'gnugo-board-mode
2398 mode-name "GNUGO Board"
2400 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2401 (set (make-local-variable 'gnugo-state)
2402 (gnugo--mkht :size (1- 42)))
2403 (add-to-invisibility-spec :nogrid)
2404 (run-hooks 'gnugo-board-mode-hook))
2406 ;;;---------------------------------------------------------------------------
2410 (defun gnugo (&optional new-game)
2411 "Run gnugo in a buffer, or resume a game in progress.
2412 Prefix arg means skip the game-in-progress check and start a new
2414 \\<gnugo-board-mode-map>
2415 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2417 You are queried for additional command-line options (Emacs supplies
2418 \"--mode gtp --quiet\" automatically). Here is a list of options
2419 that gnugo.el understands and handles specially:
2421 --boardsize num Set the board size to use (5--19)
2422 --color <color> Choose your color ('black' or 'white')
2423 --handicap <num> Set the number of handicap stones (0--9)
2425 If there is already a game in progress you may resume it instead of
2426 starting a new one. See `gnugo-board-mode' documentation for more info."
2428 (let* ((all (let (acc)
2429 (dolist (buf (buffer-list))
2430 (when (gnugo-board-buffer-p buf)
2431 (push (cons (buffer-name buf) buf) acc)))
2434 (if (and (not new-game)
2436 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2437 (if (= 1 n) "" "s"))))
2442 (let ((sel (completing-read "Which one? " all nil t)))
2443 (if (string= "" sel)
2445 (assoc sel all))))))
2446 ;; set up a new board
2447 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2449 (let ((name (if (string-match "[ ]" gnugo-program)
2450 (let ((p (substring gnugo-program 0 (match-beginning 0)))
2451 (o (substring gnugo-program (match-end 0)))
2452 (h (or (car gnugo-option-history) "")))
2453 (when (string-match "--mode" o)
2454 (user-error "Found \"--mode\" in `gnugo-program'"))
2455 (when (and o (cl-plusp (length o))
2456 h (cl-plusp (length o))
2457 (or (< (length h) (length o))
2458 (not (string= (substring h 0 (length o))
2460 (push (concat o " " h) gnugo-option-history))
2463 (args (read-string "GNU Go options: "
2464 (car gnugo-option-history)
2465 'gnugo-option-history))
2467 board-size user-color handicap komi minus-l infile)
2468 (loop for (var default opt rx)
2469 in '((board-size 19 "--boardsize")
2470 (user-color "black" "--color" "\\(black\\|white\\)")
2471 (handicap 0 "--handicap")
2473 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
2474 (infile nil "--infile" "[ ]*[^ ]+"))
2476 (or (when (string-match opt args)
2477 (let ((start (match-end 0)) s)
2478 (string-match (or rx "[0-9.]+") args start)
2479 (setq s (match-string 0 args))
2480 (if rx s (string-to-number s))))
2482 (gnugo-put :user-color user-color)
2483 (let ((proc-args (split-string args)))
2484 (gnugo-put :proc-args proc-args)
2485 (gnugo-put :proc (setq proc (apply 'start-process "gnugo"
2486 (current-buffer) name
2487 "--mode" "gtp" "--quiet"
2489 (set-process-sentinel proc 'gnugo-sentinel)
2490 ;; Emacs is too protective sometimes, blech.
2491 (set-process-query-on-exit-flag proc nil)
2492 (when (or minus-l infile)
2494 in '((board-size "query_boardsize")
2496 (handicap "get_handicap"))
2497 do (set prop (string-to-number (gnugo-query q)))))
2498 (gnugo-put :diamond (substring (process-name proc) 5))
2499 (gnugo-put :gnugo-color (gnugo-other user-color))
2500 (gnugo-put :highlight-last-move-spec
2501 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2502 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2503 (let ((ov (make-overlay 1 1)))
2504 (overlay-put ov 'display ")")
2506 (gnugo--plant-and-climb
2507 (gnugo/sgf-create "(;FF[4]GM[1])" t))
2508 (gnugo--SZ! board-size)
2509 (let ((root (gnugo--root-node)))
2513 root (loop ; hmm, available elsewhere?
2515 collect (let* ((k (pop plist))
2519 :DT (format-time-string "%Y-%m-%d")
2520 :RU (if (string-match "--chinese-rules" args)
2523 :AP (cons "gnugo.el" gnugo-version)
2525 (let ((ub (gnugo--blackp user-color)))
2526 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2527 (if ub :PB :PW) (user-full-name)))
2528 (unless (zerop handicap)
2530 :AB (mapcar (gnugo--as-cc-func)
2531 (gnugo-lsquery "fixed_handicap %d"
2533 (gnugo-put :waiting-start (current-time))
2537 (let ((half (truncate (1+ (gnugo-get :SZ)) 2)))
2538 (gnugo-goto-pos (format "A%d" half))
2539 (forward-char (* 2 (1- half)))
2540 (gnugo-put :last-user-bpos
2541 (gnugo-put :center-position
2542 (get-text-property (point) 'gnugo-position))))
2544 (gnugo-put :game-start-time (current-time))
2545 (let ((g (gnugo-get :gnugo-color))
2546 (n (or (gnugo--root-prop :HA) 0))
2547 (u (gnugo-get :user-color)))
2548 (gnugo-put :last-mover
2549 (if (or (and (gnugo--blackp u) (< 1 n))
2550 (and (gnugo--blackp g) (< n 2)))
2553 (run-hooks 'gnugo-start-game-hook)
2554 (when (string= g (gnugo-current-player))
2556 (gnugo-get-move g))))))
2558 ;;;---------------------------------------------------------------------------
2559 ;;; Load-time actions
2561 (unless gnugo-frolic-mode-map
2562 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2563 (suppress-keymap gnugo-frolic-mode-map)
2564 (mapc (lambda (pair)
2565 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2566 '(("q" . gnugo-frolic-quit)
2567 ("Q" . gnugo-frolic-quit)
2568 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2569 ("\C-b" . gnugo-frolic-backward-branch)
2570 ("\C-f" . gnugo-frolic-forward-branch)
2571 ("\C-p" . gnugo-frolic-previous-move)
2572 ("\C-n" . gnugo-frolic-next-move)
2573 ("j" . gnugo-frolic-exchange-left)
2574 ("J" . gnugo-frolic-rotate-left)
2575 ("k" . gnugo-frolic-exchange-right)
2576 ("K" . gnugo-frolic-rotate-right)
2577 ("\C-m" . gnugo-frolic-set-as-main-line)
2578 ("\C-\M-p" . gnugo-frolic-prune-branch)
2579 ("o" . gnugo-frolic-return-to-origin))))
2581 (unless gnugo-board-mode-map
2582 (setq gnugo-board-mode-map (make-sparse-keymap))
2583 (suppress-keymap gnugo-board-mode-map)
2584 (mapc (lambda (pair)
2585 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2586 '(("?" . describe-mode)
2587 ("S" . gnugo-request-suggestion)
2588 ("\C-m" . gnugo-move)
2591 ("R" . gnugo-resign)
2593 ("Q" . gnugo-leave-me-alone)
2594 ("U" . gnugo-fancy-undo)
2595 ("\M-u" . gnugo-undo-one-move)
2596 ("u" . gnugo-undo-two-moves)
2597 ("\C-?" . gnugo-undo-two-moves)
2600 ("\C-l" . gnugo-refresh)
2601 ("\M-_" . gnugo-boss-is-near)
2602 ("_" . gnugo-boss-is-near)
2603 ("h" . gnugo-move-history)
2604 ("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 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2638 (jam cmd (car ls) (cadr ls))
2639 (setq ls (cddr ls)))))))
2640 (cl-macrolet ((deffull (who &body body)
2641 (declare (indent 1))
2642 `(defgtp ',who :full (lambda (sel)
2646 (info "(gnugo)GTP command reference")
2647 (when sel (setq sel (intern (car sel))))
2648 (let (buffer-read-only pad cur spec output found)
2650 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2651 (goto-char (point-min))
2653 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2656 (setq pad (make-string (- (match-beginning 1)
2657 (match-beginning 0))
2661 (get (setq cur (intern (match-string 1)))
2662 :gnugo-gtp-command-spec))
2664 (note "handles this command completely"))
2665 (when (setq output (plist-get spec :output))
2666 (if (functionp output)
2667 (note "handles the output specially")
2669 (:discard (note "discards the output"))
2670 (:message (note "displays the output in the echo area")))))
2672 (setq found (match-beginning 0))))))
2673 (cond (found (goto-char found))
2675 (t (message "(no such command: %s)" sel)))))
2677 (deffull final_score
2678 ;; Explicit ignorance avoids byte-compiler warning.
2680 (gnugo-display-final-score))
2686 :post-thunk (lambda ()
2687 (gnugo--unclose-game)
2688 (gnugo--forget :last-mover)
2690 (gnugo--SZ! (string-to-number
2692 "query_boardsize")))
2696 (gnugo-read-sgf-file (car sel)))
2698 (deffull (undo gg-undo)
2702 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2703 (t (car sel)))))))))
2708 ;;;---------------------------------------------------------------------------
2709 ;;; The remainder of this file defines a simplified SGF-handling library.
2710 ;;; When/if it should start to attain generality, it should be split off into
2711 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2712 ;;; "gnugo/" prefix.
2714 (defconst gnugo/sgf-*r4-properties*
2715 '((AB "Add Black" setup list stone)
2716 (AE "Add Empty" game list point)
2717 (AN "Annotation" game simpletext)
2718 (AP "Application" root (simpletext . simpletext))
2719 (AR "Arrow" - list (point . point))
2720 (AS "Who adds stones" - simpletext) ; (LOA)
2721 (AW "Add White" setup list stone)
2722 (B "Black" move move)
2723 (BL "Black time left" move real)
2724 (BM "Bad move" move double)
2725 (BR "Black rank" game simpletext)
2726 (BT "Black team" game simpletext)
2727 (C "Comment" - text)
2728 (CA "Charset" root simpletext)
2729 (CP "Copyright" game simpletext)
2730 (CR "Circle" - list point)
2731 (DD "Dim points" - elist point) ; (inherit)
2732 (DM "Even position" - double)
2733 (DO "Doubtful" move none)
2734 (DT "Date" game simpletext)
2735 (EV "Event" game simpletext)
2736 (FF "Fileformat" root [number (1 . 4)])
2737 (FG "Figure" - (or none (number . simpletext)))
2738 (GB "Good for Black" - double)
2739 (GC "Game comment" game text)
2740 (GM "Game" root [number (1 . 20)])
2741 (GN "Game name" game simpletext)
2742 (GW "Good for White" - double)
2743 (HA "Handicap" game number) ; (Go)
2744 (HO "Hotspot" - double)
2745 (IP "Initial pos." game simpletext) ; (LOA)
2746 (IT "Interesting" move none)
2747 (IY "Invert Y-axis" game simpletext) ; (LOA)
2748 (KM "Komi" game real) ; (Go)
2750 (LB "Label" - list (point . simpletext))
2751 (LN "Line" - list (point . point))
2752 (MA "Mark" - list point)
2753 (MN "set move number" move number)
2754 (N "Nodename" - simpletext)
2755 (OB "OtStones Black" move number)
2756 (ON "Opening" game text)
2757 (OT "Overtime" game simpletext)
2758 (OW "OtStones White" move number)
2759 (PB "Player Black" game simpletext)
2760 (PC "Place" game simpletext)
2761 (PL "Player to play" setup color)
2762 (PM "Print move mode" - number) ; (inherit)
2763 (PW "Player White" game simpletext)
2764 (RE "Result" game simpletext)
2765 (RO "Round" game simpletext)
2766 (RU "Rules" game simpletext)
2767 (SE "Markup" - point) ; (LOA)
2768 (SL "Selected" - list point)
2769 (SO "Source" game simpletext)
2770 (SQ "Square" - list point)
2771 (ST "Style" root [number (0 . 3)])
2772 (SU "Setup type" game simpletext) ; (LOA)
2773 (SZ "Size" root (or number (number . number)))
2774 (TB "Territory Black" - elist point) ; (Go)
2775 (TE "Tesuji" move double)
2776 (TM "Timelimit" game real)
2777 (TR "Triangle" - list point)
2778 (TW "Territory White" - elist point) ; (Go)
2779 (UC "Unclear pos" - double)
2780 (US "User" game simpletext)
2782 (VW "View" - elist point) ; (inherit)
2783 (W "White" move move)
2784 (WL "White time left" move real)
2785 (WR "White rank" game simpletext)
2786 (WT "White team" game simpletext)
2787 (LT "Lose on time" setup simpletext))
2788 ;; r4-specific notes
2789 ;; - changed: DT FG LB RE RU SZ
2790 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2791 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2793 (defun gnugo/sgf-create (file-or-data &optional data-p)
2794 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2795 FILE-OR-DATA is a file name or SGF[4] data.
2796 Optional arg DATA-P non-nil means FILE-OR-DATA is
2797 a string containing SGF[4] data.
2798 A collection is a list of gametrees, each a vector of four elements:
2800 ENDS -- a vector of node lists, with shared tails
2801 (last element of all the lists is the root node)
2803 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2804 have a move number of the previous \"move\" node (or zero)
2806 ROOT -- the root node"
2807 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2808 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2809 (put 'gnugo/sgf-*r4-properties* :keywords
2810 (mapcar (lambda (full)
2812 (intern (format ":%s" (car full)))))
2813 gnugo/sgf-*r4-properties*))))
2814 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2815 (put 'gnugo/sgf-*r4-properties* :specs
2816 (mapcar (lambda (full)
2817 (cons (car full) (cdddr full)))
2818 gnugo/sgf-*r4-properties*))))
2821 ((sw () (skip-chars-forward " \t\n"))
2822 (x (end preserve-whitespace)
2825 (:end (lambda (char) (= ?\] char)))
2826 (:mid (lambda (char) (= ?\: char)))
2827 (t (lambda (char) (or (= ?\: char)
2830 (while (not (funcall endp (setq c (following-char))))
2836 ((unless preserve-whitespace
2837 (looking-at "\\s-+"))
2838 (delete-region (point) (match-end 0))
2840 (t (forward-char 1))))
2841 (buffer-substring-no-properties beg (point))))
2842 (one (type end) (let ((s (progn
2844 (x end (eq 'text type)))))
2847 ;; blech, begone bu"tt"-ugly blatherings
2848 ;; (but bide brobdingnagian boards)...
2849 (if (and (string= "tt" s)
2854 ((simpletext color) s)
2855 ((number real double) (string-to-number s))
2858 (t (error "Unhandled type: %S" type)))))
2859 (val (spec) (cond ((symbolp spec)
2862 ;; todo: check range here.
2863 (one (aref spec 0) :end))
2864 ((eq 'or (car spec))
2865 (let ((v (one (cadr spec) t)))
2866 (if (= ?\] (following-char))
2869 ;; todo: this assumes `spec' has the form
2870 ;; (or foo (foo . bar))
2871 ;; i.e., foo is not rescanned. e.g., `SZ'.
2872 ;; probably this assumption is consistent
2873 ;; w/ the SGF authors' desire to make the
2874 ;; parsing easy, but you never know...
2875 (cons v (one (cdaddr spec) :end)))))
2876 (t (cons (one (car spec) :mid)
2877 (one (cdr spec) :end)))))
2878 (short (who) (when (eobp)
2879 (error "Unexpected EOF while reading %s" who)))
2880 (atvalp () (= ?\[ (following-char)))
2881 (PROP () (let (name spec ltype)
2882 (sw) (short 'property)
2883 (when (looking-at "[A-Z]")
2884 (setq name (read (current-buffer))
2885 spec (cdr (assq name specs)))
2888 (cdr (assq name keywords))
2889 (prog1 (if (= 1 (length spec))
2891 (unless (memq (setq ltype (car spec))
2893 (error "Bad spec: %S" spec))
2894 (if (and (eq 'elist ltype) (sw)
2897 (let ((type (cadr spec))
2899 (while (and (sw) (atvalp)
2900 (setq mo (val type)))
2905 (forward-char 1))))))
2906 (morep () (and (sw) (not (eobp))))
2907 (seek (c) (and (morep) (= c (following-char))))
2908 (seek-into (c) (when (seek c)
2911 (NODE () (when (seek-into ?\;)
2913 while (setq prop (PROP))
2915 (when (eq :SZ (car prop))
2916 (setq SZ (cdr prop)))
2925 (puthash node (+ (if (gnugo--move-prop node)
2928 (gethash prev mnum 0))
2933 (if (not (seek ?\())
2937 (loop while (seek ?\()
2938 append (TREE ls mnum)))
2942 (insert-file-contents file-or-data)
2943 (insert file-or-data)
2944 (goto-char (point-min)))
2946 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2947 (ends (TREE nil mnum))
2948 (root (car (last (car ends)))))
2949 (vector (apply 'vector ends)
2953 (defun gnugo/sgf-write-file (collection filename)
2954 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2955 (me (cons "gnugo.el" gnugo-version))
2956 (specs (mapcar (lambda (full)
2957 (cons (intern (format ":%s" (car full)))
2959 gnugo/sgf-*r4-properties*))
2962 ((esc (composed fmt arg)
2963 (mapconcat (lambda (c)
2965 ;; ‘?\[’ is not strictly required
2966 ;; but neither is it forbidden.
2967 ((?\[ ?\] ?\\) (format "\\%c" c))
2968 (?: (concat (if composed "\\" "") ":"))
2970 (string-to-list (format fmt arg))
2972 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2973 (>>two (v) (insert "["
2974 (esc t "%s" (car v))
2976 (esc t "%s" (cdr v))
2978 (>>nl () (cond ((memq name aft-newline-appreciated)
2980 ((< 60 (current-column))
2988 (insert (substring (symbol-name name) 1))
2991 (setq spec (cdr (assq name specs)))
2995 (let ((>> (if (consp (cadr spec))
2998 (dolist (little-v v)
3000 (funcall >> little-v)
3007 (loop initially (insert ";")
3011 (unless (zerop (current-column))
3015 (funcall (if (gnugo--nodep x)
3021 (dolist (tree collection)
3022 ;; take responsibility for our actions
3023 (gnugo--set-root-prop :AP me tree)
3025 (let ((ht (gnugo--mkht))
3026 (leaves (append (gnugo--tree-ends tree) nil)))
3030 with rh ; rectified history
3031 with bp ; branch point
3033 until (setq bp (gethash node ht))
3035 (push node rh) ; good for now: ½τ
3039 ;; first run: main line
3041 ;; subsequent runs: grafts (value discarded)
3043 ;; Maintain order of ‘leaves’.
3044 (let ((was (cdr bp)))
3045 (if (gnugo--nodep (car was))
3049 (setq tree (hang (pop leaves)))
3050 (mapc #'hang leaves)
3053 (write-file filename)))))
3055 ;;; gnugo.el ends here