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>
8 ;; This program is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation, either version 3 of the License, or
11 ;; (at your option) any later version.
13 ;; This program is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
26 ;; This file provides the command `gnugo' which allows you to play the game of
27 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
28 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
29 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
30 ;; Go" to refer to the process object created by running the external program.
32 ;; At the start of a new game, you can pass additional command-line arguments
33 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
34 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
35 ;; both komi and handicap.
37 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
38 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
39 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
40 ;; back through an arbitrary stone that you played, place the cursor on a
41 ;; stone and type `U' (note: uppercase). Other keybindings are described in
42 ;; the `gnugo-board-mode' documentation, which you may view with the command
43 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
44 ;; the last move and who is currently to play. Capture counts and other info
45 ;; are shown on the mode line immediately following the major mode name.
47 ;; While GNU Go is pondering its next move, certain commands that rely on its
48 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
49 ;; is normal. When it is your turn again you may retry the command. In the
50 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
51 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
53 ;; If GNU Go should crash during a game the mode line will show "no process".
54 ;; Please report the event to the GNU Go maintainers so that they can improve
58 ;; Meta-Playing (aka Customizing)
59 ;; ------------------------------
61 ;; Customization is presently limited to
62 ;; vars: `gnugo-program'
63 ;; `gnugo-animation-string'
65 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
67 ;; normal hooks: `gnugo-board-mode-hook'
68 ;; `gnugo-post-move-hook'
69 ;; and the keymap: `gnugo-board-mode-map'
71 ;; The variable `gnugo-xpms' is a special case. To set it you need to load
72 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
77 (require 'cl-lib) ; use the source luke!
78 (require 'time-date) ; for `time-subtract'
80 ;;;---------------------------------------------------------------------------
83 (defconst gnugo-version "2.2.14"
84 "Version of gnugo.el currently loaded.
85 This follows a MAJOR.MINOR.PATCH scheme.")
87 ;;;---------------------------------------------------------------------------
88 ;;; Variables for the uninquisitive programmer
90 (defvar gnugo-program "gnugo"
91 "Command to start an external program that speaks GTP, such as \"gnugo\".
92 The value may also be in the form \"PROGRAM OPTIONS...\" in which case the
93 the command `gnugo' will prefix OPTIONS in its default offering when it
94 queries you for additional options. It is an error for \"--mode\" to appear
97 For more information on GTP and GNU Go, feel free to visit:
98 http://www.gnu.org/software/gnugo")
100 (defvar gnugo-board-mode-map nil
101 "Keymap for GNUGO Board mode.")
103 (defvar gnugo-board-mode-hook nil
104 "Hook run when entering GNUGO Board mode.")
106 (defvar gnugo-post-move-hook nil
107 "Normal hook run after a move and before the board is refreshed.
108 Hook functions can prevent the call to `gnugo-refresh' by evaluating:
109 (setq inhibit-gnugo-refresh t)
110 Initially, when `run-hooks' is called, the current buffer is the GNUGO
111 Board buffer of the game. Hook functions that switch buffers must take
112 care not to call (directly or indirectly through some other function)
113 `gnugo-put' or `gnugo-get' after the switch.")
115 (defvar gnugo-animation-string
116 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
117 (concat jam jam jam jam jam
118 ;; "SECRET MESSAGE HERE"
119 blink blink blink blink blink blink blink blink
120 ;; Playing go is like fighting ignorance: when you think you have
121 ;; surrounded something by knowing it very well it often turns
122 ;; out that in the time you spent deepening this understanding,
123 ;; other areas of ignorance have surrounded you.
124 spin spin spin spin spin spin spin spin spin
125 ;; Playing go is not like fighting ignorance: what one person
126 ;; knows many people may come to know; knowledge does not build
127 ;; solely move by move. Wisdom, on the other hand...
129 "String whose individual characters are used for animation.
130 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
131 render the stones in their respective result groups as the first character
132 in the string, then the next, and so on.")
134 (defvar gnugo-mode-line "~b ~w :~m :~u"
135 "A `mode-line-format'-compliant value for GNUGO Board mode.
136 If a single string, the following special escape sequences are
137 replaced with their associated information:
138 ~b,~w black,white captures (a number)
139 ~p current player (black or white)
141 ~t time waiting for the current move
142 ~u time taken for the Ultimate (most recent) move
143 The times are in seconds, or \"-\" if that information is not available.
144 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
146 (defvar gnugo-X-face 'font-lock-string-face
147 "Name of face to use for X (black) stones.")
149 (defvar gnugo-O-face 'font-lock-builtin-face
150 "Name of face to use for O (white) stones.")
152 (defvar gnugo-grid-face 'default
153 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
155 ;;;---------------------------------------------------------------------------
156 ;;; Variables for the inquisitive programmer
158 (defconst gnugo-font-lock-keywords
159 '(("X" . gnugo-X-face)
160 ("O" . gnugo-O-face))
161 "Font lock keywords for `gnugo-board-mode'.")
163 (defvar gnugo-option-history nil)
165 (defvar gnugo-state nil) ; hint: C-c C-p
168 (defvar gnugo-xpms nil))
170 ;;;---------------------------------------------------------------------------
171 ;;; Support functions
173 (defun gnugo-put (key value)
174 "Associate move/game/board-specific property KEY with VALUE.
176 There are many properties, each named by a keyword, that record and control
177 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
178 of properties, stored in the hash table `gnugo-state'. Here we document
179 some of the more stable properties. You may wish to use them as part of
180 a `gnugo-post-move-hook' function, for example. Be careful to preserve
181 the current buffer as `gnugo-state' is made into a buffer-local variable.
182 NOTE: In the following, \"see foo\" actually means \"see foo source or
183 you may never really understand to any degree of personal satisfaction\".
185 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
187 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
189 :game-over -- nil until game over at which time its value is set to
190 the alist `((live GROUP ...) (dead GROUP ...))'
192 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
193 a simple list of one or more gametrees, updated in
194 conjunction w/ :sgf-gametree and :monkey
196 :sgf-gametree -- one of the gametrees in :sgf-collection
198 :monkey -- vector of three elements: LOC, a pointer to a node on the
199 :sgf-gametree representing the most recently-played move
200 (the next move modifies the cdr of LOC); MEM, the simple
201 reverse-chronological list of previous LOC pointers; and
202 COUNT, the number of moves from the beginning of the game
204 :gnugo-color -- either \"black\" or \"white\"
208 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
211 :black-captures -- these are strings since gnugo.el doesn't do anything
212 :white-captures w/ the information besides display it in the mode line;
213 gory details in functions `gnugo-propertize-board-buffer'
214 and `gnugo-merge-showboard-results' (almost more effort
215 than they are worth!)
217 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
218 `gnugo-toggle-image-display' and `gnugo-refresh',
219 as well as gnugo-xpms.el (available elsewhere)
221 :all-yy -- list of 46 keywords used as the `category' text property
222 (so that their plists, typically w/ property `display' or
223 `do-not-display') are consulted by the Emacs display engine;
224 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
225 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
227 :lparen-ov -- overlays shuffled about to indicate the last move; only
228 :rparen-ov one is used when displaying using images
230 :last-user-bpos -- board position; keep the hapless human happy
232 As things stabilize probably more info will be added to this docstring."
234 (puthash key value gnugo-state))
236 (defun gnugo-get (key)
237 "Return the move/game/board-specific value for KEY.
239 (gethash key gnugo-state))
241 (defun gnugo-describe-internal-properties ()
242 "Pretty-print `gnugo-state' properties in another buffer.
243 Handle the big, slow-to-render, and/or uninteresting ones specially."
245 (let ((buf (current-buffer))
246 (d (gnugo-get :diamond))
248 (maphash (lambda (&rest args)
251 (setcdr args (format "hash: %X (%d images)"
253 (length (cadr args)))))
255 (setcdr args (length (cadr args))))
257 (let* ((value (cadr args))
258 (loc (aref value 0)))
260 (length (aref value 1))
263 (setq acc (cons args acc)))
265 (switch-to-buffer (get-buffer-create
266 (format "%s*GNUGO Board Properties*"
267 (gnugo-get :diamond))))
270 (setq truncate-lines t)
272 (let ((standard-output (current-buffer)))
274 (goto-char (point-min))
275 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
279 (while (re-search-forward rx (point-max) t)
280 (let ((pos (get-text-property (string-to-number (match-string 1))
281 'gnugo-position buf)))
282 (delete-region (+ 2 (match-beginning 0)) (point))
283 (insert (format " %S" pos))))))
284 (message "%d properties" (length acc))))
286 (defun gnugo-board-buffer-p (&optional buffer)
287 "Return non-nil if BUFFER is a GNUGO Board buffer."
288 (with-current-buffer (or buffer (current-buffer)) gnugo-state))
290 (defun gnugo-board-user-play-ok-p (&optional buffer)
291 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
292 (with-current-buffer (or buffer (current-buffer))
293 (and gnugo-state (not (gnugo-get :waitingp)))))
295 (defun gnugo-other (color)
296 (if (string= "black" color) "white" "black"))
298 (defun gnugo-gate (&optional in-progress-p)
299 (unless (gnugo-board-buffer-p)
300 (user-error "Wrong buffer -- try M-x gnugo"))
301 (unless (gnugo-get :proc)
302 (user-error "No \"gnugo\" process!"))
303 (when (gnugo-get :waitingp)
304 (user-error "Not your turn yet -- please wait for \"\(%s to play\)\""
305 (gnugo-get :user-color)))
306 (when (and (gnugo-get :game-over) in-progress-p)
307 (user-error "Sorry, game over")))
309 (defun gnugo-sentinel (proc string)
310 (let ((status (process-status proc)))
311 (when (or (eq status 'exit)
313 (let ((buf (process-buffer proc)))
314 (when (buffer-live-p buf)
315 (with-current-buffer buf
316 (setq mode-line-process '( " [%s]"))
317 (when (eq proc (gnugo-get :proc))
318 (gnugo-put :proc nil))))))))
320 (defun gnugo-send-line (line)
321 (let ((proc (gnugo-get :proc)))
322 (process-send-string proc line)
323 (process-send-string proc "\n")))
325 (defun gnugo-synchronous-send/return (message)
326 "Return (TIME . STRING) where TIME is that returned by `current-time' and
327 STRING omits the two trailing newlines. See also `gnugo-query'."
328 (when (gnugo-get :waitingp)
329 (user-error "Sorry, still waiting for %s to play"
330 (gnugo-get :gnugo-color)))
331 (let ((proc (gnugo-get :proc)))
332 (process-put proc :srs "") ; synchronous return stash
334 proc (lambda (proc string)
335 (let* ((so-far (process-get proc :srs))
336 (start (max 0 (- (length so-far) 2))) ; backtrack a little
337 (full (concat so-far string)))
338 (process-put proc :srs full)
339 (when (string-match "\n\n" full start)
340 (process-put proc :srs (cons (current-time)
341 (substring full 0 -2)))))))
342 (gnugo-send-line message)
344 ;; type change => break
345 (while (stringp (setq rv (process-get proc :srs)))
346 (accept-process-output proc 30))
347 (process-put proc :srs "")
350 (defun gnugo-query (message-format &rest args)
351 "Return cleaned-up value of a call to `gnugo-synchronous-send/return'.
352 The TIME portion is omitted as well as the first two characters of the STRING
353 portion (corresponding to the status indicator in the Go Text Protocol). Use
354 this function when you are sure the command cannot fail. The first arg is
355 a format string applied to the rest of the args."
356 (substring (cdr (gnugo-synchronous-send/return
357 (apply 'format message-format args)))
360 (defun gnugo-lsquery (message-format &rest args)
361 (split-string (apply 'gnugo-query message-format args)))
363 (defsubst gnugo-treeroot (prop)
364 (cdr (assq prop (car (gnugo-get :sgf-gametree)))))
366 (defun gnugo-goto-pos (pos)
367 "Move point to board position POS, a letter-number string."
368 (goto-char (point-min))
369 (forward-line (- (1+ (gnugo-treeroot :SZ))
370 (string-to-number (substring pos 1))))
372 (forward-char (+ (if (= 32 (following-char)) 1 2)
373 (* 2 (- (let ((letter (aref pos 0)))
379 (defun gnugo-f (frag)
380 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
382 (defun gnugo-yang (c)
383 (cdr (assq c '((?+ . hoshi)
385 (?X . (bmoku . bpmoku))
386 (?O . (wmoku . wpmoku))))))
388 (defun gnugo-yy (yin yang &optional momentaryp)
389 (gnugo-f (format "%d-%s"
390 yin (cond ((and (consp yang) momentaryp) (cdr yang))
391 ((consp yang) (car yang))
394 (defun gnugo-toggle-image-display ()
395 (unless (and (fboundp 'display-images-p) (display-images-p))
396 (user-error "Display does not support images, sorry"))
397 (require 'gnugo-xpms)
398 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
399 (user-error "Could not load `gnugo-xpms', sorry"))
400 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
401 (unless (eq fresh (gnugo-get :xpms))
402 (gnugo-put :xpms fresh)
403 (gnugo-put :all-yy nil)))
404 (let* ((new (not (gnugo-get :display-using-images)))
405 (act (if new 'display 'do-not-display)))
407 (setcar (symbol-plist yy) act))
408 (or (gnugo-get :all-yy)
410 (prog1 (mapcar (lambda (ent)
412 (yy (gnugo-yy (cdr k) (car k))))
413 (setplist yy `(not-yet ,(cdr ent)))
416 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
418 (gnugo-put :w-imul (car imul))
419 (gnugo-put :h-imul (cdr imul)))))))
420 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
421 (gnugo-put :highlight-last-move-spec
424 (get (gnugo-yy (get-text-property p 'gnugo-yin)
425 (get-text-property p 'gnugo-yang)
429 (gnugo-get :default-highlight-last-move-spec)))
430 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
431 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
432 (mapc 'delete-overlay (cdar group))
433 (setcdr (car group) nil))
434 (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
435 (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
436 (gnugo-put :display-using-images new)))
438 (defun gnugo-toggle-grid ()
439 "Turn the grid around the board on or off."
441 (funcall (if (memq :nogrid buffer-invisibility-spec)
442 'remove-from-invisibility-spec
443 'add-to-invisibility-spec)
445 (save-excursion (gnugo-refresh)))
447 (defun gnugo-propertize-board-buffer ()
449 (insert (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
450 (let* ((grid-props (list 'invisible :nogrid
451 'font-lock-face gnugo-grid-face))
452 (%gpad (gnugo-f 'gpad))
453 (%gspc (gnugo-f 'gspc))
454 (%lpad (gnugo-f 'lpad))
455 (%rpad (gnugo-f 'rpad))
456 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
457 (size (gnugo-treeroot :SZ))
458 (size-string (number-to-string size)))
459 (goto-char (point-min))
460 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
461 (skip-chars-forward " ")
462 (put-text-property (1- (point)) (point) 'category %gpad)
463 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
465 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
466 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
467 (let* ((row (match-string-no-properties 1))
469 (other-edge (+ edge (* 2 size) -1))
470 (right-empty (+ other-edge (length row) 1))
471 (top-p (string= size-string row))
472 (bot-p (string= "1" row)))
473 (let* ((nL (- edge 1 (length size-string)))
475 (ov (make-overlay nL nR (current-buffer) t)))
476 (add-text-properties nL nR grid-props)
477 ;; We redundantly set `invisible' in the overlay to workaround
478 ;; a display bug whereby text *following* the overlaid text is
479 ;; displayed with the face of the overlaid text, but only when
480 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
481 ;; This has something to do w/ the bletcherous `before-string'.
482 (overlay-put ov 'invisible :nogrid)
483 (overlay-put ov 'category %lpad))
484 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
486 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
487 (truncate (- p edge) 2))
489 (yin (let ((A-p (= edge p))
490 (Z-p (= (1- other-edge) p)))
491 (cond ((and top-p A-p) 1)
500 (yang (gnugo-yang (char-after p))))
501 (add-text-properties p (1+ p)
511 (gnugo-position gnugo-yin))))
512 (unless (= (1- other-edge) p)
513 (add-text-properties (1+ p) (+ 2 p) ispc-props)
514 (put-text-property p (+ 2 p) 'intangible ival)))
515 (add-text-properties (1+ other-edge) right-empty grid-props)
516 (goto-char right-empty)
517 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
518 (let ((prop (if (string= "WH" (match-string 1))
521 (beg (match-beginning 2))
523 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
524 (gnugo-put prop (match-string-no-properties 2))))
526 (put-text-property right-empty (point) 'category %rpad)
528 (add-text-properties (1- (point)) (point-max) grid-props)
529 (skip-chars-forward " ")
530 (put-text-property (1- (point)) (point) 'category %gpad)
531 (put-text-property (point) (progn (end-of-line) (point))
534 (defun gnugo-merge-showboard-results ()
535 (let ((aft (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
536 (adj 1) ; string to buffer position adjustment
538 (sync "[0-9]* stones$")
539 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
540 ;; restrictive a condition that fails in the case of:
543 ;; ... WHITE has captured 1 stones
546 ;; ... WHITE has captured 14 stones
549 ;; where the after count has more digits than the before count,
550 ;; but shares the same leading digits. In this case, the result
551 ;; of `compare-strings' points to the SPC following the before
552 ;; count (indicated by caret in this example).
554 (bef (buffer-substring-no-properties (point-min) (point-max)))
555 (bef-start 0) (bef-idx 0)
556 (aft-start 0) (aft-idx 0)
557 aft-sync-backtrack mis inc cut new very-strange)
558 (while (numberp (setq mis (compare-strings bef bef-start nil
560 (setq aft-sync-backtrack nil
561 inc (if (cl-minusp mis)
564 bef-idx (+ bef-start inc)
565 aft-idx (+ aft-start inc)
566 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
569 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
570 (let ((peek (1- aft-idx)))
571 (while (not (= 32 (aref aft peek)))
572 (setq peek (1- peek)))
573 (setq aft-sync-backtrack (1+ peek))))
577 (if aft-sync-backtrack
578 (- aft-sync-backtrack aft-idx)
581 (if aft-sync-backtrack
582 (let* ((asb aft-sync-backtrack)
583 (l-p (get-text-property cut :gnugo-cf))
586 (keep (text-properties-at cut)))
587 (setq new (substring aft asb (string-match " " aft asb)))
588 (plist-put keep :gnugo-cf (cons (length new) capprop))
589 (gnugo-put capprop new)
590 (delete-char old-len)
591 (insert (apply 'propertize new keep))
592 (setq adj (+ adj (- (length new) old-len))))
593 (setq new (aref aft aft-idx))
594 (insert-and-inherit (char-to-string new))
595 (let ((yin (get-text-property cut 'gnugo-yin))
596 (yang (gnugo-yang new)))
597 (add-text-properties cut (1+ cut)
601 ,(gnugo-yy yin yang))))
603 ;; do this last to avoid complications w/ font lock
604 ;; (this also means we cannot include `intangible' in `front-sticky')
605 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
606 (put-text-property cut (1+ cut) 'intangible very-strange))))))
608 (defun gnugo-move-history (&optional rsel)
609 "Determine and return the game's move history.
610 Optional arg RSEL controls side effects and return value.
611 If nil, display the history in the echo area as \"(N moves)\"
612 followed by the space-separated list of moves. When called
613 interactively with a prefix arg (i.e., RSEL is `(4)'), display
614 similarly, but suffix with the mover (either \":B\" or \":W\").
615 If RSEL is the symbol `car' return the most-recent move; if
616 `cadr', the next-to-most-recent move; if `count' the number of
619 For all other values of RSEL, do nothing and return nil."
621 (let ((size (gnugo-treeroot :SZ))
623 (mem (aref (gnugo-get :monkey) 1))
626 ((as-pos (cc) (if (string= "tt" cc)
628 (setq col (aref cc 0))
630 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
631 (- size (- (aref cc 1) ?a)))))
632 (next (byp) (when (setq node (caar mem)
633 mprop (or (assq :B node)
635 (setq move (as-pos (cdr mprop))
638 (format "%s%s" move (car mprop))
641 (tell () (message "(%d moves) %s"
643 (mapconcat 'identity (nreverse acc) " "))))
645 ((not rsel) (while (next nil)) (tell))
646 ((equal '(4) rsel) (while (next t)) (tell))
647 ((eq 'car rsel) (car (next nil)))
648 ((eq 'cadr rsel) (next nil) (car (next nil)))
649 ((eq 'count rsel) (aref (gnugo-get :monkey) 2))))))
651 (defun gnugo-note (property value &optional movep mogrifyp)
653 (let ((sz (gnugo-treeroot :SZ)))
655 ((mog (pos) (if (string= "PASS" pos)
657 (let* ((col (aref pos 0))
658 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
659 (two (+ ?a (- sz (string-to-number
660 (substring pos 1))))))
661 (format "%c%c" one two)))))
662 (setq value (if (consp value)
665 (let* ((fruit (list (cons property value)))
666 (monkey (gnugo-get :monkey))
667 (loc (aref monkey 0)))
669 (let ((mem (aref monkey 1)))
670 ;; todo: do variation check/merge/branch here.
671 (setcdr loc (list fruit))
672 (aset monkey 0 (setq loc (cdr loc)))
673 (aset monkey 1 (cons loc mem))
674 (aset monkey 2 (1+ (aref monkey 2))))
675 (setcdr (last (car loc)) fruit))))
677 (defun gnugo-close-game (end-time resign)
678 (gnugo-put :game-end-time end-time)
679 (let ((now (or end-time (current-time))))
680 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
682 (gnugo-put :game-over
683 (if (or (eq t resign)
684 (and (stringp resign)
685 (string-match "[BW][+][Rr]esign" resign)))
692 (gnugo-query "worm_stones %s" color)
694 (let ((live (append (ls "black") (ls "white"))))
697 (let ((dd (gnugo-query "dragon_data"))
698 (start 0) mem color ent live dead)
699 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
701 (setq mem (match-string 1 dd)
702 color (match-string 2 dd)
704 ent (cons (list color)
705 (sort (gnugo-lsquery "dragon_stones %s" mem)
707 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
709 (if (match-string 2 dd)
712 (setq start (match-end 0)))
716 (defun gnugo--unclose-game ()
717 (dolist (prop '(:game-over ; all those in -close-game
720 (gnugo-put prop nil))
721 (let* ((root (car (gnugo-get :sgf-gametree)))
722 (cur (assq :RE root)))
724 (assert (not (eq cur (car root))) nil
725 ":RE at head of root node: %S"
729 (defun gnugo-push-move (userp move)
730 (let* ((color (gnugo-get (if userp :user-color :gnugo-color)))
731 (start (gnugo-get :waiting-start))
733 (resignp (string= "resign" move))
734 (passp (string= "PASS" move))
735 (head (gnugo-move-history 'car))
736 (onep (and head (string= "PASS" head)))
737 (donep (or resignp (and onep passp))))
739 (gnugo-merge-showboard-results))
740 (gnugo-put :last-mover color)
742 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
743 (gnugo-note (if (string= "black" color) :B :W) move t (not resignp))
745 (gnugo-note :EV "resignation"))
747 (gnugo-put :last-waiting (cadr (time-subtract now start))))
749 (gnugo-close-game now resignp))
750 (gnugo-put :waiting-start (and (not donep) now))
753 (defun gnugo-venerate (yin yang)
754 (let* ((fg-yy (gnugo-yy yin yang))
755 (fg-disp (or (get fg-yy 'display)
756 (get fg-yy 'do-not-display)))
757 (fg-data (plist-get (cdr fg-disp) :data))
758 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
759 (bg-disp (or (get bg-yy 'display)
760 (get bg-yy 'do-not-display)))
761 (bg-data (plist-get (cdr bg-disp) :data))
765 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
766 (setq start (match-end 0))
767 (string-to-number (match-string 1 s)))))
768 (while (and (not (cl-minusp ncolors))
769 (string-match ",\n" s start))
770 (setq start (match-end 0)
771 ncolors (1- ncolors)))
772 (string-match "\"" s start)
774 (new (copy-sequence fg-data))
775 (lx (length fg-data))
776 (sx (funcall bop fg-data))
777 (sb (funcall bop bg-data))
778 (color-key (aref new sx))) ; blech, heuristic
780 (when (and (not (= color-key (aref new sx)))
781 (cl-plusp (random 4)))
782 (aset new sx (aref bg-data sb)))
785 (create-image new 'xpm t :ascent 'center)))
787 (defun gnugo-refresh (&optional nocache)
788 "Update GNUGO Board buffer display.
789 While a game is in progress, parenthesize the last-played stone (no parens
790 for pass). If the buffer is currently displayed in the selected window,
791 recenter the board (presuming there is extra space in the window). Update
792 the mode line. Lastly, move point to the last position played by the user,
793 if that move was not a pass.
795 Prefix arg NOCACHE requests complete reconstruction of the display, which may
796 be slow. (This should normally be unnecessary; specify it only if the display
797 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
800 (when (and nocache (not (gnugo-get :waitingp)))
801 (gnugo-propertize-board-buffer))
802 (let* ((last-mover (gnugo-get :last-mover))
803 (other (gnugo-other last-mover))
804 (move (gnugo-move-history 'car))
805 (game-over (gnugo-get :game-over))
809 (let ((l-ov (gnugo-get :lparen-ov))
810 (r-ov (gnugo-get :rparen-ov)))
811 (if (member move '("PASS" "resign"))
812 (mapc 'delete-overlay (list l-ov r-ov))
813 (gnugo-goto-pos move)
815 (hspec (gnugo-get :highlight-last-move-spec))
816 (display-value (nth 0 hspec))
817 (l-offset (nth 1 hspec))
818 (l-new-pos (+ p l-offset))
819 (r-action (nth 2 hspec)))
820 (overlay-put l-ov 'display
821 (if (functionp display-value)
822 (funcall display-value p)
824 (move-overlay l-ov l-new-pos (1+ l-new-pos))
826 (funcall r-action r-ov)
827 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
829 (rename-buffer (concat (gnugo-get :diamond)
831 (format "%s(game over)"
832 (if (string= move "resign")
833 (concat move "ation ")
835 (format "%s(%s to play)"
836 (if move (concat move " ") "")
840 (let ((live (cdr (assq 'live game-over)))
841 (dead (cdr (assq 'dead game-over)))
843 (unless (eq game-over (get-text-property 1 'game-over))
844 (dolist (group (append live dead))
845 (dolist (pos (cdr group))
848 (put-text-property p (1+ p) 'group group)))
849 (put-text-property 1 2 'game-over game-over))
851 (when (setq pall (cdar group))
852 (mapc 'delete-overlay pall)
853 (setcdr (car group) nil)))
856 (let (ov pall c (color (caar group)))
857 (setq c (if (string= "black" color) "x" "o"))
858 (dolist (pos (cdr group))
860 (setq p (point) ov (make-overlay p (1+ p)))
863 (if (gnugo-get :display-using-images)
864 ;; respect the dead individually; it takes more time
865 ;; but that's not a problem (for them)
866 (gnugo-venerate (get-text-property p 'gnugo-yin)
867 (gnugo-yang (aref (upcase c) 0)))
868 (propertize c 'face 'font-lock-warning-face)))
870 (setcdr (car group) pall))))))
872 (when (setq window (get-buffer-window (current-buffer)))
873 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
874 (size (gnugo-treeroot :SZ))
875 (under10p (< size 10))
876 (h (- (truncate (- (window-height window)
877 (* size (gnugo-get :hmul))
881 (edges (window-edges window))
882 (right-w-edge (nth 2 edges))
883 (avail-width (- right-w-edge (nth 0 edges)))
884 (wmul (gnugo-get :wmul))
885 (imagesp (symbol-plist (gnugo-f 'ispc)))
891 2 ; between board and grid
896 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
897 `(display ,(make-string h 10))
898 '(invisible :nogrid)))
903 (cond (imagesp (+ (* 0.5 wmul)
909 (gspc . ,(when imagesp
910 `(display (space-width ,(- wmul 1.0)))))
911 (lpad . ,(let ((d `(display (space :align-to ,w))))
912 ;; We distinguish between these cases to
913 ;; workaround a display bug whereby the
914 ;; `before-string' is omitted entirely (not
915 ;; rendered) when interacting w/ the text
916 ;; mode last-move left-paren for moves in
920 ,(apply 'propertize " " d))
923 (space :align-to ,(1- avail-width))))))
924 (setplist (gnugo-f (car pair)) (cdr pair)))))
926 (let ((cur (gnugo-get :mode-line)))
927 (unless (equal cur gnugo-mode-line)
928 (setq cur gnugo-mode-line)
929 (gnugo-put :mode-line cur)
930 (gnugo-put :mode-line-form
932 (setq cur (copy-sequence cur))
934 (while (setq cut (string-match "~[bwpmtu]" cur))
936 (setq cut (1+ cut) c (aref cur cut))
939 `(,(intern (format "squig-%c" c))
941 (?b '(or (gnugo-get :black-captures) 0))
942 (?w '(or (gnugo-get :white-captures) 0))
943 (?p '(gnugo-other (gnugo-get :last-mover)))
944 (?t '(let ((ws (gnugo-get :waiting-start)))
946 (cadr (time-since ws))
948 (?u '(or (gnugo-get :last-waiting) "-"))
949 (?m '(gnugo-move-history 'count))))
951 `(let ,(delete-dups (copy-sequence acc))
952 (format ,cur ,@(reverse (mapcar 'car acc))))))
954 (let ((form (gnugo-get :mode-line-form)))
955 (setq mode-line-process
957 ;; this dynamicism is nice but excessive in its wantonness
958 ;;- `(" [" (:eval ,form) "]")
959 ;; this dynamicism is ok because the user triggers it
960 (list (format " [%s]" (eval form))))))
961 (force-mode-line-update))
963 (when (setq last (gnugo-get :last-user-bpos))
964 (gnugo-goto-pos last))))
966 ;;;---------------------------------------------------------------------------
967 ;;; Game play actions
969 (defun gnugo-get-move-insertion-filter (proc string)
970 (with-current-buffer (process-buffer proc)
971 (let* ((so-far (gnugo-get :get-move-string))
972 (full (gnugo-put :get-move-string (concat so-far string))))
973 (when (string-match "^= \\(.+\\)\n\n" full)
974 (let ((pos-or-pass (match-string 1 full)))
975 (gnugo-put :get-move-string nil)
976 (gnugo-put :waitingp nil)
977 (gnugo-push-move nil pos-or-pass)
978 (let ((buf (current-buffer)))
979 (let (inhibit-gnugo-refresh)
980 (run-hooks 'gnugo-post-move-hook)
981 (unless inhibit-gnugo-refresh
982 (with-current-buffer buf
983 (gnugo-refresh))))))))))
985 (defun gnugo-get-move (color)
986 (gnugo-put :waitingp t)
987 (set-process-filter (gnugo-get :proc) 'gnugo-get-move-insertion-filter)
988 (gnugo-send-line (concat "genmove " color))
989 (accept-process-output))
991 (defun gnugo-cleanup ()
992 (when (gnugo-board-buffer-p)
993 (unless (zerop (buffer-size))
994 (message "Thank you for playing GNU Go."))
996 (setplist sym nil) ; "...is next to fordliness." --Huxley
998 (append (gnugo-get :all-yy)
1007 (setq gnugo-state nil)))
1009 (defun gnugo-position ()
1010 (or (get-text-property (point) 'gnugo-position)
1011 (user-error "Not a proper position point")))
1013 (defun gnugo-move ()
1014 "Make a move on the GNUGO Board buffer.
1015 The position is computed from current point.
1016 Signal error if done out-of-turn or if game-over.
1017 To start a game try M-x gnugo."
1020 (let* ((buf (current-buffer))
1021 (pos (gnugo-position))
1022 (move (format "play %s %s" (gnugo-get :user-color) pos))
1023 (accept (cdr (gnugo-synchronous-send/return move))))
1024 (unless (= ?= (aref accept 0))
1025 (user-error "%s" accept))
1026 (gnugo-push-move t pos) ; value always nil for non-pass move
1027 (let (inhibit-gnugo-refresh)
1028 (run-hooks 'gnugo-post-move-hook)
1029 (unless inhibit-gnugo-refresh
1030 (with-current-buffer buf
1032 (with-current-buffer buf
1033 (gnugo-get-move (gnugo-get :gnugo-color)))))
1035 (defun gnugo-mouse-move (e)
1036 "Do `gnugo-move' at mouse location."
1039 (when (looking-at "[.+]")
1042 (defun gnugo-pass ()
1043 "Make a pass on the GNUGO Board buffer.
1044 Signal error if done out-of-turn or if game-over.
1045 To start a game try M-x gnugo."
1048 (let ((accept (cdr (gnugo-synchronous-send/return
1049 (format "play %s PASS" (gnugo-get :user-color))))))
1050 (unless (= ?= (aref accept 0))
1051 (user-error "%s" accept)))
1052 (let ((donep (gnugo-push-move t "PASS"))
1053 (buf (current-buffer)))
1054 (let (inhibit-gnugo-refresh)
1055 (run-hooks 'gnugo-post-move-hook)
1056 (unless inhibit-gnugo-refresh
1057 (with-current-buffer buf
1060 (with-current-buffer buf
1061 (gnugo-get-move (gnugo-get :gnugo-color))))))
1063 (defun gnugo-mouse-pass (e)
1064 "Do `gnugo-pass' at mouse location."
1069 (defun gnugo-resign ()
1072 (if (not (y-or-n-p "Resign? "))
1073 (message "(not resigning)")
1074 (gnugo-push-move t "resign")
1077 (defun gnugo-animate-group (command)
1078 (message "Computing %s ..." command)
1079 (let* ((pos (gnugo-position))
1080 (orig-b-m-p (buffer-modified-p))
1081 (stones (if (memq (char-after) '(?X ?O))
1082 (gnugo-lsquery "%s %s" command pos)
1083 (user-error "No stone at %s" pos))))
1084 (message "Computing %s ... %s in group." command (length stones))
1085 (setplist (gnugo-f 'anim) nil)
1086 (let* ((spec (let ((spec (split-string gnugo-animation-string "" t)))
1087 (cond ((gnugo-get :display-using-images)
1088 (let* ((yin (get-text-property (point) 'gnugo-yin))
1089 (yang (gnugo-yang (char-after)))
1090 (up (get (gnugo-yy yin yang t) 'display))
1091 (dn (get (gnugo-yy yin yang) 'display)))
1095 (number-sequence 1 (length spec)))))
1098 (ovs (save-excursion
1099 (mapcar (lambda (pos)
1100 (gnugo-goto-pos pos)
1102 (ov (make-overlay p (1+ p))))
1103 (overlay-put ov 'category (gnugo-f 'anim))
1104 (overlay-put ov 'priority most-positive-fixnum)
1107 (setplist (gnugo-f 'anim) (cons 'display cell))
1108 (while (and (cdr spec) ; let last linger lest levity lost
1109 (sit-for 0.08675309)) ; jenny jenny i got your number...
1110 (setcar cell (setq spec (cdr spec)))
1111 ;; Force redisplay of overlays.
1112 (set-buffer-modified-p orig-b-m-p))
1114 (mapc 'delete-overlay ovs)
1117 (defun gnugo-display-group-data (command buffer-name)
1118 (message "Computing %s ..." command)
1119 (let ((data (cdr (gnugo-synchronous-send/return
1120 (format "%s %s" command (gnugo-position))))))
1121 (switch-to-buffer buffer-name)
1124 (message "Computing %s ... done." command))
1126 (defun gnugo-worm-stones ()
1127 "In the GNUGO Board buffer, animate \"worm\" at current position.
1128 Signal error if done out-of-turn or if game-over.
1129 See variable `gnugo-animation-string' for customization."
1132 (gnugo-animate-group "worm_stones"))
1134 (defun gnugo-worm-data ()
1135 "Display in another buffer data from \"worm\" at current position.
1136 Signal error if done out-of-turn or if game-over."
1139 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1141 (defun gnugo-dragon-stones ()
1142 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1143 Signal error if done out-of-turn or if game-over.
1144 See variable `gnugo-animation-string' for customization."
1147 (gnugo-animate-group "dragon_stones"))
1149 (defun gnugo-dragon-data ()
1150 "Display in another buffer data from \"dragon\" at current position.
1151 Signal error if done out-of-turn or if game-over."
1154 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1156 (defun gnugo-toggle-dead-group ()
1157 "In a GNUGO Board buffer, during game-over, toggle a group as dead.
1158 The group is selected from current position (point). Signal error if
1159 not in game-over or if there is no group at that position.
1161 In the context of GNU Go, a group is called a \"dragon\" and may be
1162 composed of more than one \"worm\" (set of directly-connected stones).
1163 It is unclear to the gnugo.el author whether or not GNU Go supports
1164 - considering worms as groups in their own right; and
1165 - toggling group aliveness via GTP.
1166 Due to these uncertainties, this command is only half complete; the
1167 changes you may see in Emacs are not propagated to the gnugo subprocess.
1168 Thus, GTP commands like `final_score' may give unexpected results.
1170 If you are able to expose via GTP `change_dragon_status' in utils.c,
1171 you may consider modifying the `gnugo-toggle-dead-group' source code
1172 to enable full functionality."
1174 (let ((game-over (or (gnugo-get :game-over)
1175 (user-error "Sorry, game still in play")))
1176 (group (or (get-text-property (point) 'group)
1177 (user-error "No stone at that position")))
1178 (now (current-time)))
1179 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1181 (let ((live (assq 'live game-over))
1182 (dead (assq 'dead game-over))
1184 (if (memq group live)
1185 (setq bef live now dead)
1186 (setq bef dead now live))
1187 (setcdr bef (delq group (cdr bef)))
1188 (setcdr now (cons group (cdr now)))
1189 ;; disabled permanently -- too wrong
1193 (let ((color (caar group)))
1194 (dolist (stone (cdr group))
1195 (gnugo-query "play %s %s" color stone)))))
1198 ;; drastic (and wrong -- clobbers capture info, etc)
1199 (gnugo-query "clear_board")
1200 (mapc #'populate (cdr live)))))
1201 ;; here is the desired interface (to be enabled Some Day)
1203 (gnugo-query "change_dragon_status %s %s"
1204 (cadr group) (if (eq now live)
1210 (defun gnugo-estimate-score ()
1211 "Display estimated score of a game of GNU Go.
1212 Output includes number of stones on the board and number of stones
1213 captured by each player, and the estimate of who has the advantage (and
1214 by how many stones)."
1216 (message "Est.score ...")
1217 (let ((black (length (gnugo-lsquery "list_stones black")))
1218 (white (length (gnugo-lsquery "list_stones white")))
1219 (black-captures (gnugo-query "captures black"))
1220 (white-captures (gnugo-query "captures white"))
1221 (est (gnugo-query "estimate_score")))
1222 ;; might as well update this
1223 (gnugo-put :black-captures black-captures)
1224 (gnugo-put :white-captures white-captures)
1225 (message "Est.score ... B %s %s | W %s %s | %s"
1226 black black-captures white white-captures est)))
1228 (defun gnugo-write-sgf-file (filename)
1229 "Save the game history to FILENAME (even if unfinished).
1230 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1231 (interactive "FWrite game as SGF file: ")
1232 (when (and (file-exists-p filename)
1233 (not (y-or-n-p "File exists. Continue? ")))
1234 (user-error "Not writing %s" filename))
1235 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1236 (set-buffer-modified-p nil))
1238 (defun gnugo-read-sgf-file (filename)
1239 "Load the first game tree from FILENAME, a file in SGF format."
1240 (interactive "fSGF file to load: ")
1241 (when (file-directory-p filename)
1242 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1243 (let (ans play wait samep coll)
1244 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1245 ;; todo: skip it altogether when confident about `gnugo/sgf-read-file'
1246 (unless (= ?= (aref (setq ans (cdr (gnugo-synchronous-send/return
1247 (format "loadsgf %s"
1248 (expand-file-name filename)))))
1250 (user-error "%s" ans))
1251 (setq play (substring ans 2)
1252 wait (gnugo-other play)
1253 samep (string= (gnugo-get :user-color) play))
1254 (gnugo-put :last-mover wait)
1256 (gnugo-put :gnugo-color wait)
1257 (gnugo-put :user-color play))
1258 (gnugo-put :sgf-collection (setq coll (gnugo/sgf-read-file filename)))
1259 (gnugo-put :sgf-gametree
1260 (nth (let ((n (length coll)))
1264 ;; (let* ((q (format "Which game? (1-%d)" n))
1265 ;; (choice (1- (read-number q 1))))
1266 ;; (if (and (< -1 choice) (< choice n))
1268 ;; (message "(Selecting the first game)")
1270 ;; but this is what we use (for now) to accomodate
1271 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1273 (message "(Selecting the first game)"))
1276 (let* ((tree (gnugo-get :sgf-gametree))
1279 mem node play game-over)
1280 (while (setq node (car loc))
1281 (when (setq play (or (assq :B node)
1283 ;; SGF[4] allows "" to mean PASS. For now,
1284 ;; we normalize here instead of at the lower layer.
1285 (when (string= "" (cdr play))
1289 (setq loc (cdr loc)))
1290 (gnugo-put :game-over
1292 (or (cdr (assq :RE (car tree)))
1295 (let ((order (if (string= "black" wait)
1298 (mapcar (lambda (pk)
1299 (cdr (assq (funcall pk order)
1300 (car (funcall pk mem)))))
1304 (vector (or (car mem) (gnugo-get :sgf-gametree))
1307 (when (and game-over
1308 ;; (maybe) todo: user var to inhibit (can be slow)
1310 (gnugo-close-game nil game-over)))
1312 (set-buffer-modified-p nil)
1313 (message "GNU Go %splays as %s, you as %s (%s)"
1314 (if samep "" "now ")
1317 "NOTE: this is a switch!"))))
1319 (defun gnugo-magic-undo (spec &optional noalt)
1320 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1321 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1322 check that the position is occupied by a stone of the user's color,
1323 and if so, remove moves from the history until that position is clear.
1324 If SPEC is a positive number, remove exactly that many moves from the
1325 history, signaling an error if the history is exhausted before finishing.
1326 If SPEC is not recognized, signal \"bad spec\" error.
1328 Refresh the board for each move undone. If (in the case where SPEC is
1329 a number) after finishing, the color to play is not the user's color,
1330 schedule a move by GNU Go.
1332 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1333 turn to play. Optional second arg NOALT non-nil inhibits this."
1336 (monkey (gnugo-get :monkey))
1337 (mem (aref monkey 1))
1338 (count (aref monkey 2))
1340 (cond ((and (numberp spec) (cl-plusp spec))
1341 (setq n spec done (lambda () (zerop n))))
1342 ((string-match "^[a-z]" spec)
1343 (let ((pos (upcase spec)))
1344 (setq done `(lambda ()
1345 (gnugo-goto-pos ,pos)
1346 (memq (char-after) '(?. ?+))))
1347 (when (funcall done)
1348 (user-error "%s already clear" pos))
1349 (let ((u (gnugo-get :user-color)))
1350 (when (= (save-excursion
1351 (gnugo-goto-pos pos)
1353 (if (string= "black" u)
1356 (user-error "%s not occupied by %s" pos u)))))
1357 (t (user-error "Bad spec: %S" spec)))
1358 (when (gnugo-get :game-over)
1359 (gnugo--unclose-game))
1360 (while (not (funcall done))
1361 (setq ans (cdr (gnugo-synchronous-send/return "undo")))
1362 (unless (= ?= (aref ans 0))
1363 (user-error "%s" ans))
1364 (aset monkey 2 (decf count))
1365 (aset monkey 1 (setq mem (cdr mem)))
1366 (aset monkey 0 (or (car mem) (gnugo-get :sgf-gametree)))
1367 (gnugo-put :last-mover (gnugo-other (gnugo-get :last-mover)))
1368 (gnugo-merge-showboard-results) ; all
1369 (gnugo-refresh) ; this
1371 (redisplay))) ; eye candy
1372 (let* ((ulastp (string= (gnugo-get :last-mover) (gnugo-get :user-color)))
1374 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1375 (gnugo-put :last-user-bpos (if (and ubpos (not (string= "PASS" ubpos)))
1377 (gnugo-get :center-position)))
1379 ;; preserve restricted-functionality semantics (todo: remove restriction)
1380 (setcdr (aref (gnugo-get :monkey) 0) nil)
1381 (when (and ulastp (not noalt))
1382 (gnugo-get-move (gnugo-get :gnugo-color)))))
1384 (defun gnugo-undo-one-move ()
1385 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1386 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1387 See also `gnugo-undo-two-moves'."
1390 (gnugo-magic-undo 1 t))
1392 (defun gnugo-undo-two-moves ()
1393 "Undo a pair of moves (GNU Go's and yours).
1394 However, if you are the last mover, undo only one move.
1395 Regardless, after undoing, it is your turn to play again."
1398 (gnugo-magic-undo (if (string= (gnugo-get :user-color)
1399 (gnugo-get :last-mover))
1403 (defun gnugo-display-final-score ()
1404 "Display final score and other info in another buffer (when game over).
1405 If the game is still ongoing, Emacs asks if you wish to stop play (by
1406 making sure two \"pass\" moves are played consecutively, if necessary).
1407 Also, add the `:RE' SGF property to the root node of the game tree."
1409 (unless (or (gnugo-get :game-over)
1410 (and (not (gnugo-get :waitingp))
1411 (y-or-n-p "Game still in play. Stop play now? ")))
1412 (user-error "Sorry, game still in play"))
1413 (unless (gnugo-get :game-over)
1416 (message "Playing PASS for %s ..."
1417 (gnugo-get (if userp :user-color :gnugo-color)))
1419 (gnugo-push-move userp "PASS")))
1424 (let ((b= " Black = ")
1426 (res (let* ((node (car (aref (gnugo-get :monkey) 0)))
1427 (event (and node (cdr (assq :EV node)))))
1428 (and event (string= "resignation" event)
1429 (if (assq :B node) "black" "white"))))
1433 (format "%s wins.\n"
1434 (substring (if (= ?b (aref res 0)) w= b=)
1436 "The game is over.\n"
1437 (format "Resignation by %s.\n" res))
1438 result (concat (upcase (substring (gnugo-other res) 0 1))
1440 (message "Computing final score ...")
1441 (let* ((live (cdr (assq 'live (gnugo-get :game-over))))
1442 (dead (cdr (assq 'dead (gnugo-get :game-over))))
1443 (seed (gnugo-get :scoring-seed))
1444 (terr-q (format "final_status_list %%s_territory %d" seed))
1447 (b-terr (length (gnugo-lsquery terr-q "black")))
1448 (w-terr (length (gnugo-lsquery terr-q "white")))
1449 (b-capt (string-to-number (gnugo-get :black-captures)))
1450 (w-capt (string-to-number (gnugo-get :white-captures)))
1451 (komi (gnugo-treeroot :KM)))
1452 (setq blurb (list "The game is over. Final score:\n")
1453 result (gnugo-query "final_score %d" seed))
1454 (cond ((string= "Chinese" (gnugo-treeroot :RU))
1455 (dolist (group live)
1456 (let ((count (length (cdr group))))
1457 (if (string= "black" (caar group))
1458 (setq b-terr (+ b-terr count))
1459 (setq w-terr (+ w-terr count)))))
1460 (dolist (group dead)
1461 (let* ((color (caar group))
1462 (count (length (cdr group))))
1463 (if (string= "black" color)
1464 (setq w-terr (+ count w-terr))
1465 (setq b-terr (+ count b-terr)))))
1466 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1467 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1468 w-terr terr komi 'komi (+ w-terr komi))
1471 (dolist (group dead)
1472 (let* ((color (caar group))
1473 (adjust (* 2 (length (cdr group)))))
1474 (if (string= "black" color)
1475 (setq w-terr (+ adjust w-terr))
1476 (setq b-terr (+ adjust b-terr)))))
1477 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1482 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1486 (+ w-terr w-capt komi))
1488 (push (if (string= "0" result)
1489 "The game is a draw.\n"
1490 (format "%s wins by %s.\n"
1491 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1492 (substring result 2)))
1494 (message "Computing final score ... done")))
1496 (when (gnugo-get :game-end-time)
1498 (dolist (spec '(("Game start" . :game-start-time)
1499 (" end" . :game-end-time)))
1500 (push (format-time-string
1501 (concat (car spec) ": %Y-%m-%d %H:%M:%S %z\n")
1502 (gnugo-get (cdr spec)))
1504 (setq blurb (apply 'concat (nreverse blurb)))
1505 (let* ((root (car (gnugo-get :sgf-gametree)))
1506 (cur (assq :RE root)))
1509 (setcdr (last root) (list (cons :RE result)))))
1510 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
1514 (defun gnugo-quit ()
1515 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
1516 If the game is not over, ask for confirmation first."
1518 (if (or (gnugo-get :game-over)
1519 (y-or-n-p "Quit? "))
1521 (message "(not quitting)")))
1523 (defun gnugo-leave-me-alone ()
1524 "Kill the current buffer unconditionally."
1528 (defun gnugo-fancy-undo (count)
1529 "Rewind the game tree in various ways.
1530 Prefix arg COUNT means to undo that many moves.
1531 Otherwise, undo repeatedly up to and including the move
1532 which placed the stone at point."
1535 ;; TODO: Move this into `gnugo-magic-undo' proper.
1536 (cond ((numberp count) count)
1537 ((consp count) (car count))
1538 (t (gnugo-position)))))
1540 (defun gnugo-toggle-image-display-command () ; ugh
1541 "Toggle use of images to display the board, then refresh."
1543 (gnugo-toggle-image-display)
1544 (save-excursion (gnugo-refresh)))
1546 (defun gnugo-describe-position ()
1547 "Display the board position under cursor in the echo area."
1549 (message "%s" (gnugo-position)))
1551 ;;;---------------------------------------------------------------------------
1552 ;;; Command properties and gnugo-command
1554 ;; GTP commands entered by the user are never issued directly to GNU Go;
1555 ;; instead, their behavior and output are controlled by the property
1556 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
1557 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
1559 ;; :full -- completely interpret the command string; the value is a
1560 ;; func that takes the list of words derived from splitting the
1561 ;; command string (minus the command) and handles everything.
1563 ;; :output -- either a keyword specifying the preferred output method:
1564 ;; :message -- show output in minibuffer
1565 ;; :discard -- sometimes you just don't care;
1566 ;; or a function that takes one arg, the output string, and
1567 ;; handles it completely. default is to switch to buffer
1568 ;; "*gnugo command output*" if the output has a newline,
1569 ;; otherwise use `message'.
1571 ;; :post-thunk -- run after output processing (at the very end).
1573 (defun gnugo-command (command)
1574 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
1575 Output and Emacs behavior depend on which command is given (some
1576 commands are handled completely by Emacs w/o using the subprocess;
1577 some commands have their output displayed in specially prepared
1578 buffers or in the echo area; some commands are instrumented to do
1579 gnugo.el-specific housekeeping).
1581 For example, for the command \"help\", Emacs visits the
1582 GTP command reference info page.
1584 NOTE: At this time, GTP command handling specification is still
1585 incomplete. Thus, some commands WILL confuse gnugo.el."
1586 (interactive "sCommand: ")
1587 (if (string= "" command)
1588 (message "(no command given)")
1589 (let* ((split (split-string command))
1590 (cmd (intern (car split)))
1591 (spec (get cmd :gnugo-gtp-command-spec))
1592 (full (plist-get spec :full)))
1594 (funcall full (cdr split))
1595 (message "Doing %s ..." command)
1596 (let* ((ans (cdr (gnugo-synchronous-send/return command)))
1597 (where (plist-get spec :output)))
1598 (if (string-match "unknown.command" ans)
1600 (cond ((functionp where) (funcall where ans))
1601 ((eq :discard where) (message ""))
1602 ((or (eq :message where)
1603 (not (string-match "\n" ans)))
1605 (t (switch-to-buffer "*gnugo command output*")
1608 (message "Doing %s ... done." command)))
1609 (let ((thunk (plist-get spec :post-thunk)))
1610 (when thunk (funcall thunk)))))))))
1612 ;;;---------------------------------------------------------------------------
1613 ;;; Major mode for interacting with a GNUGO subprocess
1615 (put 'gnugo-board-mode 'mode-class 'special)
1616 (defun gnugo-board-mode ()
1617 "Major mode for playing GNU Go.
1618 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
1619 In this mode, keys do not self insert. Default keybindings:
1623 RET or SPC Run `gnugo-move'.
1625 q or Q Quit (the latter without confirmation).
1629 u Run `gnugo-undo-two-moves'.
1631 U Pass to `gnugo-magic-undo' either the board position
1632 at point (if no prefix arg), or the prefix arg converted
1633 to a number. E.g., to undo 16 moves: `C-u C-u U' (see
1634 `universal-argument'); to undo 42 moves: `M-4 M-2 U'.
1636 C-l Run `gnugo-refresh'.
1638 _ or M-_ Bury the Board buffer (when the boss is near).
1642 i Toggle display using XPM images (if supported).
1644 w Run `gnugo-worm-stones'.
1645 d Run `gnugo-dragon-stones'.
1647 W Run `gnugo-worm-data'.
1648 D Run `gnugo-dragon-data'.
1650 t Run `gnugo-toggle-dead-group'.
1652 ! Run `gnugo-estimate-score'.
1654 : or ; Run `gnugo-command' (for GTP commands to GNU Go).
1656 = Display board position under point (if valid).
1658 h Run `gnugo-move-history'.
1660 F Run `gnugo-display-final-score'.
1662 s Run `gnugo-write-sgf-file'.
1666 l Run `gnugo-read-sgf-file'."
1667 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
1668 (buffer-disable-undo) ; todo: undo undo undoing
1669 (kill-all-local-variables)
1670 (setq truncate-lines t)
1671 (use-local-map gnugo-board-mode-map)
1672 (set (make-local-variable 'font-lock-defaults)
1673 '(gnugo-font-lock-keywords t))
1674 (setq major-mode 'gnugo-board-mode)
1675 (setq mode-name "GNUGO Board")
1676 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
1677 (set (make-local-variable 'gnugo-state)
1678 (make-hash-table :size (1- 42) :test 'eq))
1679 (add-to-invisibility-spec :nogrid)
1680 (mapc (lambda (prop)
1681 (gnugo-put prop nil)) ; todo: separate display/game aspects;
1682 '(:game-over ; move latter to func `gnugo'
1689 :display-using-images
1693 (let ((name (if (string-match "[ ]" gnugo-program)
1694 (let ((p (substring gnugo-program 0 (match-beginning 0)))
1695 (o (substring gnugo-program (match-end 0)))
1696 (h (or (car gnugo-option-history) "")))
1697 (when (string-match "--mode" o)
1698 (user-error "Found \"--mode\" in `gnugo-program'"))
1699 (when (and o (cl-plusp (length o))
1700 h (cl-plusp (length o))
1701 (or (< (length h) (length o))
1702 (not (string= (substring h 0 (length o))
1704 (push (concat o " " h) gnugo-option-history))
1707 (args (read-string "GNU Go options: "
1708 (car gnugo-option-history)
1709 'gnugo-option-history))
1711 board-size user-color handicap komi minus-l infile)
1712 (dolist (x '((board-size 19 "--boardsize")
1713 (user-color "black" "--color" "\\(black\\|white\\)")
1714 (handicap 0 "--handicap")
1716 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
1717 (infile nil "--infile" "[ ]*[^ ]+")))
1718 (destructuring-bind (var default opt &optional rx) x
1720 (or (when (string-match opt args)
1721 (let ((start (match-end 0)) s)
1722 (string-match (or rx "[0-9.]+") args start)
1723 (setq s (match-string 0 args))
1724 (if rx s (string-to-number s))))
1726 (gnugo-put :user-color user-color)
1727 (when (string-match "--chinese-rules" args)
1728 (setq rules "Chinese"))
1729 (let ((proc-args (split-string args)))
1730 (gnugo-put :proc-args proc-args)
1731 (gnugo-put :proc (apply 'start-process "gnugo" nil name
1732 "--mode" "gtp" "--quiet"
1734 ;; Emacs is too protective sometimes, blech.
1735 (set-process-query-on-exit-flag (gnugo-get :proc) nil)
1736 (when (or minus-l infile)
1738 (apply (lambda (prop q)
1739 (set prop (string-to-number (gnugo-query q))))
1741 '((board-size "query_boardsize")
1743 (handicap "get_handicap"))))
1744 (gnugo-put :diamond (substring (process-name (gnugo-get :proc)) 5))
1745 (gnugo-put :gnugo-color (gnugo-other (gnugo-get :user-color)))
1746 (gnugo-put :highlight-last-move-spec
1747 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
1748 (gnugo-put :lparen-ov (make-overlay 1 1))
1749 (gnugo-put :rparen-ov (let ((ov (make-overlay 1 1)))
1750 (overlay-put ov 'display ")")
1752 (gnugo-put :sgf-gametree (list (list '(:FF . 4) '(:GM . 1))))
1753 (let ((tree (gnugo-get :sgf-gametree)))
1754 (gnugo-put :sgf-collection (list tree))
1755 (gnugo-put :monkey (vector tree nil 0)))
1756 (let ((g-blackp (string= "black" (gnugo-get :gnugo-color))))
1757 (mapc (lambda (x) (apply 'gnugo-note x))
1759 (:DT ,(format-time-string "%Y-%m-%d"))
1761 (:AP ("gnugo.el" . ,gnugo-version))
1763 (,(if g-blackp :PW :PB) ,(user-full-name))
1764 (,(if g-blackp :PB :PW) ,(concat "GNU Go "
1765 (gnugo-query "version")))
1766 ,@(when (not (zerop handicap))
1768 (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
1770 (set-process-sentinel (gnugo-get :proc) 'gnugo-sentinel)
1771 (set-process-buffer (gnugo-get :proc) (current-buffer))
1772 (gnugo-put :waiting-start (current-time))
1775 (run-hooks 'gnugo-board-mode-hook)
1778 ;;;---------------------------------------------------------------------------
1782 (defun gnugo (&optional new-game)
1783 "Run gnugo in a buffer, or resume a game in progress.
1784 Prefix arg means skip the game-in-progress check and start a new
1787 You are queried for additional command-line options (Emacs supplies
1788 \"--mode gtp --quiet\" automatically). Here is a list of options
1789 that gnugo.el understands and handles specially:
1791 --boardsize num Set the board size to use (5--19)
1792 --color <color> Choose your color ('black' or 'white')
1793 --handicap <num> Set the number of handicap stones (0--9)
1795 If there is already a game in progress you may resume it instead of
1796 starting a new one. See `gnugo-board-mode' documentation for more info."
1798 (let* ((all (let (acc)
1799 (dolist (buf (buffer-list))
1800 (when (gnugo-board-buffer-p buf)
1801 (push (cons (buffer-name buf) buf) acc)))
1804 (if (and (not new-game)
1806 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
1807 (if (= 1 n) "" "s"))))
1812 (let ((sel (completing-read "Which one? " all nil t)))
1813 (if (string= "" sel)
1815 (assoc sel all))))))
1816 ;; set up a new board
1818 (let ((half (truncate (1+ (gnugo-treeroot :SZ)) 2)))
1819 (gnugo-goto-pos (format "A%d" half))
1820 (forward-char (* 2 (1- half)))
1821 (gnugo-put :last-user-bpos
1822 (gnugo-put :center-position
1823 (get-text-property (point) 'gnugo-position))))
1825 (gnugo-put :game-start-time (current-time))
1826 (let ((g (gnugo-get :gnugo-color))
1827 (n (or (gnugo-treeroot :HA) 0))
1828 (u (gnugo-get :user-color)))
1829 (gnugo-put :last-mover g)
1830 (when (or (and (string= "black" u) (< 1 n))
1831 (and (string= "black" g) (< n 2)))
1832 (gnugo-put :last-mover u)
1834 (gnugo-get-move g))))))
1836 ;;;---------------------------------------------------------------------------
1837 ;;; Load-time actions
1839 (unless gnugo-board-mode-map
1840 (setq gnugo-board-mode-map (make-sparse-keymap))
1841 (suppress-keymap gnugo-board-mode-map)
1842 (mapc (lambda (pair)
1843 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
1844 '(("?" . describe-mode)
1845 ("\C-m" . gnugo-move)
1848 ("R" . gnugo-resign)
1850 ("Q" . gnugo-leave-me-alone)
1851 ("U" . gnugo-fancy-undo)
1852 ("u" . gnugo-undo-two-moves)
1853 ("\C-l" . gnugo-refresh)
1854 ("\M-_" . bury-buffer)
1856 ("h" . gnugo-move-history)
1857 ("i" . gnugo-toggle-image-display-command)
1858 ("w" . gnugo-worm-stones)
1859 ("W" . gnugo-worm-data)
1860 ("d" . gnugo-dragon-stones)
1861 ("D" . gnugo-dragon-data)
1862 ("t" . gnugo-toggle-dead-group)
1863 ("g" . gnugo-toggle-grid)
1864 ("!" . gnugo-estimate-score)
1865 (":" . gnugo-command)
1866 (";" . gnugo-command)
1867 ("=" . gnugo-describe-position)
1868 ("s" . gnugo-write-sgf-file)
1869 ("\C-x\C-s" . gnugo-write-sgf-file)
1870 ("\C-x\C-w" . gnugo-write-sgf-file)
1871 ("l" . gnugo-read-sgf-file)
1872 ("F" . gnugo-display-final-score)
1874 ([(down-mouse-1)] . gnugo-mouse-move)
1875 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
1876 ([(down-mouse-3)] . gnugo-mouse-pass)
1877 ;; delving into the curiosities
1878 ("\C-c\C-p" . gnugo-describe-internal-properties))))
1880 (unless (get 'help :gnugo-gtp-command-spec)
1882 ((sget (x) (get x :gnugo-gtp-command-spec))
1883 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
1884 (plist-put (sget cmd) prop val)))
1885 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
1888 (jam cmd (car ls) (cadr ls))
1889 (setq ls (cddr ls)))))))
1893 (info "(gnugo)GTP command reference")
1894 (when sel (setq sel (intern (car sel))))
1895 (let (buffer-read-only pad cur spec output found)
1897 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
1898 (goto-char (point-min))
1900 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
1903 (setq pad (make-string (- (match-beginning 1)
1904 (match-beginning 0))
1908 (get (setq cur (intern (match-string 1)))
1909 :gnugo-gtp-command-spec))
1911 (note "handles this command completely"))
1912 (when (setq output (plist-get spec :output))
1913 (cond ((functionp output)
1914 (note "handles the output specially"))
1915 ((eq :discard output)
1916 (note "discards the output"))
1917 ((eq :message output)
1918 (note "displays the output in the echo area"))))
1920 (setq found (match-beginning 0))))))
1921 (cond (found (goto-char found))
1923 (t (message "(no such command: %s)" sel))))))
1925 (defgtp 'final_score :full
1926 (lambda (sel) (gnugo-display-final-score)))
1932 :post-thunk (lambda ()
1933 (gnugo--unclose-game)
1934 (gnugo-put :last-mover nil)
1937 (defgtp 'loadsgf :full
1938 (lambda (sel) (gnugo-read-sgf-file (car sel))))
1940 (defgtp '(undo gg-undo) :full
1941 (lambda (sel) (gnugo-magic-undo
1944 ((cl-plusp (setq n (string-to-number (car sel)))) n)
1945 (t (car sel)))))))))
1950 ;;;---------------------------------------------------------------------------
1951 ;;; The remainder of this file defines a simplified SGF-handling library.
1952 ;;; When/if it should start to attain generality, it should be split off into
1953 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
1954 ;;; "gnugo/" prefix.
1956 (defconst gnugo/sgf-*r4-properties*
1957 '((AB "Add Black" setup list stone)
1958 (AE "Add Empty" game list point)
1959 (AN "Annotation" game simpletext)
1960 (AP "Application" root (simpletext . simpletext))
1961 (AR "Arrow" - list (point . point))
1962 (AS "Who adds stones" - simpletext) ; (LOA)
1963 (AW "Add White" setup list stone)
1964 (B "Black" move move)
1965 (BL "Black time left" move real)
1966 (BM "Bad move" move double)
1967 (BR "Black rank" game simpletext)
1968 (BT "Black team" game simpletext)
1969 (C "Comment" - text)
1970 (CA "Charset" root simpletext)
1971 (CP "Copyright" game simpletext)
1972 (CR "Circle" - list point)
1973 (DD "Dim points" - elist point) ; (inherit)
1974 (DM "Even position" - double)
1975 (DO "Doubtful" move none)
1976 (DT "Date" game simpletext)
1977 (EV "Event" game simpletext)
1978 (FF "Fileformat" root [number (1 . 4)])
1979 (FG "Figure" - (or none (number . simpletext)))
1980 (GB "Good for Black" - double)
1981 (GC "Game comment" game text)
1982 (GM "Game" root [number (1 . 20)])
1983 (GN "Game name" game simpletext)
1984 (GW "Good for White" - double)
1985 (HA "Handicap" game number) ; (Go)
1986 (HO "Hotspot" - double)
1987 (IP "Initial pos." game simpletext) ; (LOA)
1988 (IT "Interesting" move none)
1989 (IY "Invert Y-axis" game simpletext) ; (LOA)
1990 (KM "Komi" game real) ; (Go)
1992 (LB "Label" - list (point . simpletext))
1993 (LN "Line" - list (point . point))
1994 (MA "Mark" - list point)
1995 (MN "set move number" move number)
1996 (N "Nodename" - simpletext)
1997 (OB "OtStones Black" move number)
1998 (ON "Opening" game text)
1999 (OT "Overtime" game simpletext)
2000 (OW "OtStones White" move number)
2001 (PB "Player Black" game simpletext)
2002 (PC "Place" game simpletext)
2003 (PL "Player to play" setup color)
2004 (PM "Print move mode" - number) ; (inherit)
2005 (PW "Player White" game simpletext)
2006 (RE "Result" game simpletext)
2007 (RO "Round" game simpletext)
2008 (RU "Rules" game simpletext)
2009 (SE "Markup" - point) ; (LOA)
2010 (SL "Selected" - list point)
2011 (SO "Source" game simpletext)
2012 (SQ "Square" - list point)
2013 (ST "Style" root [number (0 . 3)])
2014 (SU "Setup type" game simpletext) ; (LOA)
2015 (SZ "Size" root (or number (number . number)))
2016 (TB "Territory Black" - elist point) ; (Go)
2017 (TE "Tesuji" move double)
2018 (TM "Timelimit" game real)
2019 (TR "Triangle" - list point)
2020 (TW "Territory White" - elist point) ; (Go)
2021 (UC "Unclear pos" - double)
2022 (US "User" game simpletext)
2024 (VW "View" - elist point) ; (inherit)
2025 (W "White" move move)
2026 (WL "White time left" move real)
2027 (WR "White rank" game simpletext)
2028 (WT "White team" game simpletext)
2029 (LT "Lose on time" setup simpletext))
2030 ;; r4-specific notes
2031 ;; - changed: DT FG LB RE RU SZ
2032 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2033 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2035 (defun gnugo/sgf-read-file (filename)
2036 "Return the collection (list) of gametrees in SGF[4] file FILENAME."
2037 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2038 (put 'gnugo/sgf-*r4-properties* :keywords
2039 (mapcar (lambda (full)
2041 (intern (format ":%s" (car full)))))
2042 gnugo/sgf-*r4-properties*))))
2043 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2044 (put 'gnugo/sgf-*r4-properties* :specs
2045 (mapcar (lambda (full)
2046 (cons (car full) (cdddr full)))
2047 gnugo/sgf-*r4-properties*)))))
2049 ((sw () (skip-chars-forward " \t\n"))
2050 (x (end) (let ((beg (point))
2052 (:end (lambda (char) (= ?\] char)))
2053 (:mid (lambda (char) (= ?\: char)))
2054 (t (lambda (char) (or (= ?\: char)
2057 (while (not (funcall endp (setq c (char-after))))
2063 ((looking-at "\\s-+")
2064 (delete-region (point) (match-end 0))
2066 (t (forward-char 1))))
2067 (buffer-substring-no-properties beg (point))))
2068 (one (type end) (unless (eq 'none type)
2072 ((stone point move simpletext color) s)
2073 ((number real double) (string-to-number s))
2075 (t (error "Unhandled type: %S" type))))))
2076 (val (spec) (cond ((symbolp spec)
2079 ;; todo: check range here.
2080 (one (aref spec 0) :end))
2081 ((eq 'or (car spec))
2082 (let ((v (one (cadr spec) t)))
2083 (if (= ?\] (char-after))
2086 ;; todo: this assumes `spec' has the form
2087 ;; (or foo (foo . bar))
2088 ;; i.e., foo is not rescanned. e.g., `SZ'.
2089 ;; probably this assumption is consistent
2090 ;; w/ the SGF authors' desire to make the
2091 ;; parsing easy, but you never know...
2092 (cons v (one (cdaddr spec) :end)))))
2093 (t (cons (one (car spec) :mid)
2094 (one (cdr spec) :end)))))
2095 (short (who) (when (eobp)
2096 (error "Unexpected EOF while reading %s" who)))
2097 (atvalp () (= ?\[ (char-after)))
2098 (PROP () (let (name spec ltype)
2099 (sw) (short 'property)
2100 (when (looking-at "[A-Z]")
2101 (setq name (read (current-buffer))
2102 spec (cdr (assq name specs)))
2105 (cdr (assq name keywords))
2106 (prog1 (if (= 1 (length spec))
2108 (unless (memq (setq ltype (car spec))
2110 (error "Bad spec: %S" spec))
2111 (if (and (eq 'elist ltype) (sw)
2114 (let ((type (cadr spec))
2116 (while (and (sw) (atvalp)
2117 (setq mo (val type)))
2122 (forward-char 1))))))
2123 (NODE () (let (prop props)
2125 (when (= ?\; (char-after))
2127 (while (setq prop (PROP))
2130 (TREE () (let (nodes)
2131 (while (and (sw) (not (eobp)))
2133 (?\; (push (NODE) nodes))
2134 (?\( (forward-char 1)
2135 (push (TREE) nodes))
2136 (?\) (forward-char 1))))
2139 (insert-file-contents filename)
2141 (while (and (sw) (not (eobp)) (= 40 (char-after))) ; left paren
2143 (push (TREE) trees))
2144 (nreverse trees))))))
2146 (defun gnugo/sgf-write-file (collection filename)
2147 ;; take responsibility for our actions
2148 (dolist (tree collection)
2149 (let* ((root (car tree))
2150 (who (assq :AP root))
2151 (fruit (cons "gnugo.el" gnugo-version)))
2154 (setcdr (last root) (list (cons :AP fruit))))))
2156 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2157 (specs (mapcar (lambda (full)
2158 (cons (intern (format ":%s" (car full)))
2160 gnugo/sgf-*r4-properties*))
2162 ;; todo: escape special chars for `text' and `simpletext'.
2164 ((>>one (v) (insert (format "[%s]" v)))
2165 (>>two (v) (insert (format "[%s:%s]" (car v) (cdr v))))
2166 (>>nl () (cond ((memq name aft-newline-appreciated)
2168 ((< 60 (current-column))
2173 (dolist (tree collection)
2181 (insert (substring (symbol-name name) 1))
2184 (memq (car (setq spec (cdr (assq name specs))))
2187 (let ((>> (if (consp (cadr spec))
2190 (dolist (little-v v)
2191 (setq p (point)) (funcall >> little-v) (>>nl))))
2195 (>>one v) (>>nl)))))
2197 (write-file filename)))))
2199 ;;; gnugo.el ends here