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 (put 'gnugo-put 'lisp-indent-function 1)
174 (defun gnugo-put (key value) (puthash key value gnugo-state))
175 (defun gnugo-get (key) (gethash key gnugo-state))
177 (let ((docs "Put or get move/game/board-specific properties.
178 \(This docstring is shared by `gnugo-put' and `gnugo-get'.\)
180 There are many properties, each named by a keyword, that record and control
181 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
182 of properties, stored in the hash table `gnugo-state'. Here we document
183 some of the more stable properties. You may wish to use them as part of
184 a `gnugo-post-move-hook' function, for example. Be careful to preserve
185 the current buffer as `gnugo-state' is made into a buffer-local variable.
186 NOTE: In the following, \"see foo\" actually means \"see foo source or
187 you may never really understand to any degree of personal satisfaction\".
189 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
191 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
193 :game-over -- nil until game over at which time its value is set to
194 the alist `((live GROUP ...) (dead GROUP ...))'
196 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
197 a simple list of one or more gametrees, updated in
198 conjunction w/ :sgf-gametree and :monkey
200 :sgf-gametree -- one of the gametrees in :sgf-collection
202 :monkey -- vector of three elements: LOC, a pointer to a node on the
203 :sgf-gametree representing the most recently-played move
204 (the next move modifies the cdr of LOC); MEM, the simple
205 reverse-chronological list of previous LOC pointers; and
206 COUNT, the number of moves from the beginning of the game
208 :gnugo-color -- either \"black\" or \"white\"
212 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
215 :black-captures -- these are strings since gnugo.el doesn't do anything
216 :white-captures w/ the information besides display it in the mode line;
217 gory details in functions `gnugo-propertize-board-buffer'
218 and `gnugo-merge-showboard-results' (almost more effort
219 than they are worth!)
221 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
222 `gnugo-toggle-image-display' and `gnugo-refresh',
223 as well as gnugo-xpms.el (available elsewhere)
225 :all-yy -- list of 46 keywords used as the `category' text property
226 (so that their plists, typically w/ property `display' or
227 `do-not-display') are consulted by the Emacs display engine;
228 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
229 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
231 :lparen-ov -- overlays shuffled about to indicate the last move; only
232 :rparen-ov one is used when displaying using images
234 :last-user-bpos -- board position; keep the hapless human happy
236 As things stabilize probably more info will be added to this docstring."))
237 (put 'gnugo-put 'function-documentation docs)
238 (put 'gnugo-get 'function-documentation docs))
240 (defun gnugo-describe-internal-properties ()
241 "Pretty-print `gnugo-state' properties in another buffer.
242 Handle the big, slow-to-render, and/or uninteresting ones specially."
244 (let ((buf (current-buffer))
245 (d (gnugo-get :diamond))
247 (maphash (lambda (&rest args)
250 (setcdr args (format "hash: %X (%d images)"
252 (length (cadr args)))))
254 (setcdr args (length (cadr args))))
256 (let* ((value (cadr args))
257 (loc (aref value 0)))
259 (length (aref value 1))
262 (setq acc (cons args acc)))
264 (switch-to-buffer (get-buffer-create
265 (format "%s*GNUGO Board Properties*"
266 (gnugo-get :diamond))))
269 (setq truncate-lines t)
271 (let ((standard-output (current-buffer)))
273 (goto-char (point-min))
274 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
278 (while (re-search-forward rx (point-max) t)
279 (let ((pos (get-text-property (string-to-number (match-string 1))
280 'gnugo-position buf)))
281 (delete-region (+ 2 (match-beginning 0)) (point))
282 (insert (format " %S" pos))))))
283 (message "%d properties" (length acc))))
285 (defun gnugo-board-buffer-p (&optional buffer)
286 "Return non-nil if BUFFER is a GNUGO Board buffer."
287 (with-current-buffer (or buffer (current-buffer)) gnugo-state))
289 (defun gnugo-board-user-play-ok-p (&optional buffer)
290 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
291 (with-current-buffer (or buffer (current-buffer))
292 (and gnugo-state (not (gnugo-get :waitingp)))))
294 (defun gnugo-other (color)
295 (if (string= "black" color) "white" "black"))
297 (defun gnugo-gate (&optional in-progress-p)
298 (unless (gnugo-board-buffer-p)
299 (error "Wrong buffer -- try M-x gnugo"))
300 (unless (gnugo-get :proc)
301 (error "No \"gnugo\" process!"))
302 (when (gnugo-get :waitingp)
303 (error "Not your turn yet -- please wait for \"\(%s to play\)\""
304 (gnugo-get :user-color)))
305 (when (and (gnugo-get :game-over) in-progress-p)
306 (error "Sorry, game over")))
308 (defun gnugo-sentinel (proc string)
309 (let ((status (process-status proc)))
310 (when (or (eq status 'exit)
312 (let ((buf (process-buffer proc)))
313 (when (buffer-live-p buf)
314 (with-current-buffer buf
315 (setq mode-line-process '( " [%s]"))
316 (when (eq proc (gnugo-get :proc))
317 (gnugo-put :proc nil))))))))
319 (defun gnugo-send-line (line)
320 (let ((proc (gnugo-get :proc)))
321 (process-send-string proc line)
322 (process-send-string proc "\n")))
324 (defun gnugo-synchronous-send/return (message)
325 "Return (TIME . STRING) where TIME is that returned by `current-time' and
326 STRING omits the two trailing newlines. See also `gnugo-query'."
327 (when (gnugo-get :waitingp)
328 (error "Sorry, still waiting for %s to play" (gnugo-get :gnugo-color)))
329 (gnugo-put :sync-return "")
330 (let ((proc (gnugo-get :proc)))
332 proc (lambda (proc string)
333 (let* ((so-far (gnugo-get :sync-return))
334 (start (max 0 (- (length so-far) 2))) ; backtrack a little
335 (full (gnugo-put :sync-return (concat so-far string))))
336 (when (string-match "\n\n" full start)
337 (gnugo-put :sync-return
338 (cons (current-time) (substring full 0 -2)))))))
339 (gnugo-send-line message)
341 ;; type change => break
342 (while (stringp (setq rv (gnugo-get :sync-return)))
343 (accept-process-output proc 30))
344 (gnugo-put :sync-return "")
347 (defun gnugo-query (message-format &rest args)
348 "Return cleaned-up value of a call to `gnugo-synchronous-send/return'.
349 The TIME portion is omitted as well as the first two characters of the STRING
350 portion (corresponding to the status indicator in the Go Text Protocol). Use
351 this function when you are sure the command cannot fail. The first arg is
352 a format string applied to the rest of the args."
353 (substring (cdr (gnugo-synchronous-send/return
354 (apply 'format message-format args)))
357 (defun gnugo-lsquery (message-format &rest args)
358 (split-string (apply 'gnugo-query message-format args)))
360 (defsubst gnugo-treeroot (prop)
361 (cdr (assq prop (car (gnugo-get :sgf-gametree)))))
363 (defun gnugo-goto-pos (pos)
364 "Move point to board position POS, a letter-number string."
365 (goto-char (point-min))
366 (forward-line (- (1+ (gnugo-treeroot :SZ))
367 (string-to-number (substring pos 1))))
369 (forward-char (+ (if (= 32 (following-char)) 1 2)
370 (* 2 (- (let ((letter (aref pos 0)))
376 (defun gnugo-f (frag)
377 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
379 (defun gnugo-yang (c)
380 (cdr (assq c '((?+ . hoshi)
382 (?X . (bmoku . bpmoku))
383 (?O . (wmoku . wpmoku))))))
385 (defun gnugo-yy (yin yang &optional momentaryp)
386 (gnugo-f (format "%d-%s"
387 yin (cond ((and (consp yang) momentaryp) (cdr yang))
388 ((consp yang) (car yang))
391 (defun gnugo-toggle-image-display ()
392 (unless (and (fboundp 'display-images-p) (display-images-p))
393 (error "Display does not support images, sorry"))
394 (require 'gnugo-xpms)
395 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
396 (error "Could not load `gnugo-xpms', sorry"))
397 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
398 (unless (eq fresh (gnugo-get :xpms))
399 (gnugo-put :xpms fresh)
400 (gnugo-put :all-yy nil)))
401 (let* ((new (not (gnugo-get :display-using-images)))
402 (act (if new 'display 'do-not-display)))
404 (setcar (symbol-plist yy) act))
405 (or (gnugo-get :all-yy)
407 (prog1 (mapcar (lambda (ent)
409 (yy (gnugo-yy (cdr k) (car k))))
410 (setplist yy `(not-yet ,(cdr ent)))
413 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
415 (gnugo-put :w-imul (car imul))
416 (gnugo-put :h-imul (cdr imul)))))))
417 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
418 (gnugo-put :highlight-last-move-spec
421 (get (gnugo-yy (get-text-property p 'gnugo-yin)
422 (get-text-property p 'gnugo-yang)
426 (gnugo-get :default-highlight-last-move-spec)))
427 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
428 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
429 (mapc 'delete-overlay (cdar group))
430 (setcdr (car group) nil))
431 (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
432 (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
433 (gnugo-put :display-using-images new)))
435 (defun gnugo-toggle-grid ()
436 "Turn the grid around the board on or off."
438 (funcall (if (memq :nogrid buffer-invisibility-spec)
439 'remove-from-invisibility-spec
440 'add-to-invisibility-spec)
442 (save-excursion (gnugo-refresh)))
444 (defun gnugo-propertize-board-buffer ()
446 (insert (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
447 (let* ((grid-props (list 'invisible :nogrid
448 'font-lock-face gnugo-grid-face))
449 (%gpad (gnugo-f 'gpad))
450 (%gspc (gnugo-f 'gspc))
451 (%lpad (gnugo-f 'lpad))
452 (%rpad (gnugo-f 'rpad))
453 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
454 (size (gnugo-treeroot :SZ))
455 (size-string (number-to-string size)))
456 (goto-char (point-min))
457 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
458 (skip-chars-forward " ")
459 (put-text-property (1- (point)) (point) 'category %gpad)
460 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
462 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
463 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
464 (let* ((row (match-string-no-properties 1))
466 (other-edge (+ edge (* 2 size) -1))
467 (right-empty (+ other-edge (length row) 1))
468 (top-p (string= size-string row))
469 (bot-p (string= "1" row)))
470 (let* ((nL (- edge 1 (length size-string)))
472 (ov (make-overlay nL nR (current-buffer) t)))
473 (add-text-properties nL nR grid-props)
474 ;; We redundantly set `invisible' in the overlay to workaround
475 ;; a display bug whereby text *following* the overlaid text is
476 ;; displayed with the face of the overlaid text, but only when
477 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
478 ;; This has something to do w/ the bletcherous `before-string'.
479 (overlay-put ov 'invisible :nogrid)
480 (overlay-put ov 'category %lpad))
481 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
483 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
484 (truncate (- p edge) 2))
486 (yin (let ((A-p (= edge p))
487 (Z-p (= (1- other-edge) p)))
488 (cond ((and top-p A-p) 1)
497 (yang (gnugo-yang (char-after p))))
498 (add-text-properties p (1+ p)
508 (gnugo-position gnugo-yin))))
509 (unless (= (1- other-edge) p)
510 (add-text-properties (1+ p) (+ 2 p) ispc-props)
511 (put-text-property p (+ 2 p) 'intangible ival)))
512 (add-text-properties (1+ other-edge) right-empty grid-props)
513 (goto-char right-empty)
514 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
515 (let ((prop (if (string= "WH" (match-string 1))
518 (beg (match-beginning 2))
520 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
521 (gnugo-put prop (match-string-no-properties 2))))
523 (put-text-property right-empty (point) 'category %rpad)
525 (add-text-properties (1- (point)) (point-max) grid-props)
526 (skip-chars-forward " ")
527 (put-text-property (1- (point)) (point) 'category %gpad)
528 (put-text-property (point) (progn (end-of-line) (point))
531 (defun gnugo-merge-showboard-results ()
532 (let ((aft (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
533 (adj 1) ; string to buffer position adjustment
534 (sync "[0-9]+ stones$")
535 (bef (buffer-substring-no-properties (point-min) (point-max)))
536 (bef-start 0) (bef-idx 0)
537 (aft-start 0) (aft-idx 0)
538 aft-sync-backtrack mis inc cut new very-strange)
539 (while (numberp (setq mis (compare-strings bef bef-start nil
541 (setq aft-sync-backtrack nil
545 bef-idx (+ bef-start inc)
546 aft-idx (+ aft-start inc)
547 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
550 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
551 (let ((peek (1- aft-idx)))
552 (while (not (= 32 (aref aft peek)))
553 (setq peek (1- peek)))
554 (setq aft-sync-backtrack (1+ peek))))
558 (if aft-sync-backtrack
559 (- aft-sync-backtrack aft-idx)
562 (if aft-sync-backtrack
563 (let* ((asb aft-sync-backtrack)
564 (l-p (get-text-property cut :gnugo-cf))
567 (keep (text-properties-at cut)))
568 (setq new (substring aft asb (string-match " " aft asb)))
569 (plist-put keep :gnugo-cf (cons (length new) capprop))
570 (gnugo-put capprop new)
571 (delete-char old-len)
572 (insert (apply 'propertize new keep))
573 (setq adj (+ adj (- (length new) old-len))))
574 (setq new (aref aft aft-idx))
575 (insert-and-inherit (char-to-string new))
576 (let ((yin (get-text-property cut 'gnugo-yin))
577 (yang (gnugo-yang new)))
578 (add-text-properties cut (1+ cut)
582 ,(gnugo-yy yin yang))))
584 ;; do this last to avoid complications w/ font lock
585 ;; (this also means we cannot include `intangible' in `front-sticky')
586 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
587 (put-text-property cut (1+ cut) 'intangible very-strange))))))
589 (defun gnugo-move-history (&optional rsel)
590 "Determine and return the game's move history.
591 Optional arg RSEL controls side effects and return value.
592 If nil, display the history in the echo area as \"(N moves)\"
593 followed by the space-separated list of moves. When called
594 interactively with a prefix arg (i.e., RSEL is `(4)'), display
595 similarly, but suffix with the mover (either \":B\" or \":W\").
596 If RSEL is the symbol `car' return the most-recent move; if
597 `cadr', the next-to-most-recent move; if `count' the number of
600 For all other values of RSEL, do nothing and return nil."
602 (let ((size (gnugo-treeroot :SZ))
604 (mem (aref (gnugo-get :monkey) 1))
607 ((as-pos (cc) (if (string= "tt" cc)
609 (setq col (aref cc 0))
611 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
612 (- size (- (aref cc 1) ?a)))))
613 (next (byp) (when (setq node (caar mem)
614 mprop (or (assq :B node)
616 (setq move (as-pos (cdr mprop))
619 (format "%s%s" move (car mprop))
622 (tell () (message "(%d moves) %s"
624 (mapconcat 'identity (nreverse acc) " "))))
626 ((not rsel) (while (next nil)) (tell))
627 ((equal '(4) rsel) (while (next t)) (tell))
628 ((eq 'car rsel) (car (next nil)))
629 ((eq 'cadr rsel) (next nil) (car (next nil)))
630 ((eq 'count rsel) (aref (gnugo-get :monkey) 2))))))
632 (defun gnugo-note (property value &optional movep mogrifyp)
634 (let ((sz (gnugo-treeroot :SZ)))
636 ((mog (pos) (if (string= "PASS" pos)
638 (let* ((col (aref pos 0))
639 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
640 (two (+ ?a (- sz (string-to-number
641 (substring pos 1))))))
642 (format "%c%c" one two)))))
643 (setq value (if (consp value)
646 (let* ((fruit (list (cons property value)))
647 (monkey (gnugo-get :monkey))
648 (loc (aref monkey 0)))
650 (let ((mem (aref monkey 1)))
651 ;; todo: do variation check/merge/branch here.
652 (setcdr loc (list fruit))
653 (aset monkey 0 (setq loc (cdr loc)))
654 (aset monkey 1 (cons loc mem))
655 (aset monkey 2 (1+ (aref monkey 2))))
656 (setcdr (last (car loc)) fruit))))
658 (defun gnugo-close-game (end-time resign)
659 (gnugo-put :game-end-time end-time)
660 (let ((now (or end-time (current-time))))
661 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
663 (gnugo-put :game-over
664 (if (or (eq t resign)
665 (and (stringp resign)
666 (string-match "[BW][+][Rr]esign" resign)))
673 (gnugo-query "worm_stones %s" color)
675 (let ((live (append (ls "black") (ls "white"))))
678 (let ((dd (gnugo-query "dragon_data"))
679 (start 0) mem color ent live dead)
680 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
682 (setq mem (match-string 1 dd)
683 color (match-string 2 dd)
685 ent (cons (list color)
686 (sort (gnugo-lsquery "dragon_stones %s" mem)
688 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
690 (if (match-string 2 dd)
693 (setq start (match-end 0)))
697 (defun gnugo-push-move (userp move)
698 (let* ((color (gnugo-get (if userp :user-color :gnugo-color)))
699 (start (gnugo-get :waiting-start))
701 (resignp (string= "resign" move))
702 (passp (string= "PASS" move))
703 (head (gnugo-move-history 'car))
704 (onep (and head (string= "PASS" head)))
705 (donep (or resignp (and onep passp))))
707 (gnugo-merge-showboard-results))
708 (gnugo-put :last-mover color)
710 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
711 (gnugo-note (if (string= "black" color) :B :W) move t (not resignp))
713 (gnugo-note :EV "resignation"))
715 (gnugo-put :last-waiting (cadr (time-subtract now start))))
717 (gnugo-close-game now resignp))
718 (gnugo-put :waiting-start (and (not donep) now))
721 (defun gnugo-venerate (yin yang)
722 (let* ((fg-yy (gnugo-yy yin yang))
723 (fg-disp (or (get fg-yy 'display)
724 (get fg-yy 'do-not-display)))
725 (fg-data (plist-get (cdr fg-disp) :data))
726 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
727 (bg-disp (or (get bg-yy 'display)
728 (get bg-yy 'do-not-display)))
729 (bg-data (plist-get (cdr bg-disp) :data))
733 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
734 (setq start (match-end 0))
735 (string-to-number (match-string 1 s)))))
736 (while (and (<= 0 ncolors) (string-match ",\n" s start))
737 (setq start (match-end 0)
738 ncolors (1- ncolors)))
739 (string-match "\"" s start)
741 (new (copy-sequence fg-data))
742 (lx (length fg-data))
743 (lb (length bg-data))
744 (sx (funcall bop fg-data))
745 (sb (funcall bop bg-data))
746 (color-key (aref new sx))) ; blech, heuristic
748 (when (and (not (= color-key (aref new sx)))
750 (aset new sx (aref bg-data sb)))
753 (create-image new 'xpm t :ascent 'center)))
755 (defun gnugo-refresh (&optional nocache)
756 "Update GNUGO Board buffer display.
757 While a game is in progress, parenthesize the last-played stone (no parens
758 for pass). If the buffer is currently displayed in the selected window,
759 recenter the board (presuming there is extra space in the window). Update
760 the mode line. Lastly, move point to the last position played by the user,
761 if that move was not a pass.
763 Prefix arg NOCACHE requests complete reconstruction of the display, which may
764 be slow. (This should normally be unnecessary; specify it only if the display
765 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
768 (when (and nocache (not (gnugo-get :waitingp)))
769 (gnugo-propertize-board-buffer))
770 (let* ((last-mover (gnugo-get :last-mover))
771 (other (gnugo-other last-mover))
772 (move (gnugo-move-history 'car))
773 (game-over (gnugo-get :game-over))
777 (let ((l-ov (gnugo-get :lparen-ov))
778 (r-ov (gnugo-get :rparen-ov)))
779 (if (member move '("PASS" "resign"))
780 (mapc 'delete-overlay (list l-ov r-ov))
781 (gnugo-goto-pos move)
783 (hspec (gnugo-get :highlight-last-move-spec))
784 (display-value (nth 0 hspec))
785 (l-offset (nth 1 hspec))
786 (l-new-pos (+ p l-offset))
787 (r-action (nth 2 hspec)))
788 (overlay-put l-ov 'display
789 (if (functionp display-value)
790 (funcall display-value p)
792 (move-overlay l-ov l-new-pos (1+ l-new-pos))
794 (funcall r-action r-ov)
795 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
797 (rename-buffer (concat (gnugo-get :diamond)
799 (format "%s(game over)"
800 (if (string= move "resign")
801 (concat move "ation ")
803 (format "%s(%s to play)"
804 (if move (concat move " ") "")
808 (let ((live (cdr (assq 'live game-over)))
809 (dead (cdr (assq 'dead game-over)))
811 (unless (eq game-over (get-text-property 1 'game-over))
812 (dolist (group (append live dead))
813 (dolist (pos (cdr group))
816 (put-text-property p (1+ p) 'group group)))
817 (put-text-property 1 2 'game-over game-over))
819 (when (setq pall (cdar group))
820 (mapc 'delete-overlay pall)
821 (setcdr (car group) nil)))
824 (let (ov pall c (color (caar group)))
825 (setq c (if (string= "black" color) "x" "o"))
826 (dolist (pos (cdr group))
828 (setq p (point) ov (make-overlay p (1+ p)))
831 (if (gnugo-get :display-using-images)
832 ;; respect the dead individually; it takes more time
833 ;; but that's not a problem (for them)
834 (gnugo-venerate (get-text-property p 'gnugo-yin)
835 (gnugo-yang (aref (upcase c) 0)))
836 (propertize c 'face 'font-lock-warning-face)))
838 (setcdr (car group) pall))))))
840 (when (setq window (get-buffer-window (current-buffer)))
841 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
842 (size (gnugo-treeroot :SZ))
843 (under10p (< size 10))
844 (h (- (truncate (- (window-height window)
845 (* size (gnugo-get :hmul))
849 (edges (window-edges window))
850 (right-w-edge (nth 2 edges))
851 (avail-width (- right-w-edge (nth 0 edges)))
852 (wmul (gnugo-get :wmul))
853 (imagesp (symbol-plist (gnugo-f 'ispc)))
859 2 ; between board and grid
864 (dolist (pair `((tpad . ,(if (and h (< 0 h))
865 `(display ,(make-string h 10))
866 '(invisible :nogrid)))
871 (cond (imagesp (+ (* 0.5 wmul)
877 (gspc . ,(when imagesp
878 `(display (space-width ,(- wmul 1.0)))))
879 (lpad . ,(let ((d `(display (space :align-to ,w))))
880 ;; We distinguish between these cases to
881 ;; workaround a display bug whereby the
882 ;; `before-string' is omitted entirely (not
883 ;; rendered) when interacting w/ the text
884 ;; mode last-move left-paren for moves in
888 ,(apply 'propertize " " d))
891 (space :align-to ,(1- avail-width))))))
892 (setplist (gnugo-f (car pair)) (cdr pair)))))
894 (let ((cur (gnugo-get :mode-line)))
895 (unless (equal cur gnugo-mode-line)
896 (setq cur gnugo-mode-line)
897 (gnugo-put :mode-line cur)
898 (gnugo-put :mode-line-form
900 (setq cur (copy-sequence cur))
902 (while (setq cut (string-match "~[bwpmtu]" cur))
904 (setq cut (1+ cut) c (aref cur cut))
907 `(,(intern (format "squig-%c" c))
909 (?b '(or (gnugo-get :black-captures) 0))
910 (?w '(or (gnugo-get :white-captures) 0))
911 (?p '(gnugo-other (gnugo-get :last-mover)))
912 (?t '(let ((ws (gnugo-get :waiting-start)))
914 (cadr (time-since ws))
916 (?u '(or (gnugo-get :last-waiting) "-"))
917 (?m '(gnugo-move-history 'count))))
919 `(let ,(delete-dups (copy-sequence acc))
920 (format ,cur ,@(reverse (mapcar 'car acc))))))
922 (let ((form (gnugo-get :mode-line-form)))
923 (setq mode-line-process
925 ;; this dynamicism is nice but excessive in its wantonness
926 ;;- `(" [" (:eval ,form) "]")
927 ;; this dynamicism is ok because the user triggers it
928 (list (format " [%s]" (eval form))))))
929 (force-mode-line-update))
931 (when (setq last (gnugo-get :last-user-bpos))
932 (gnugo-goto-pos last))))
934 ;;;---------------------------------------------------------------------------
935 ;;; Game play actions
937 (defun gnugo-get-move-insertion-filter (proc string)
938 (with-current-buffer (process-buffer proc)
939 (let* ((so-far (gnugo-get :get-move-string))
940 (full (gnugo-put :get-move-string (concat so-far string))))
941 (when (string-match "^= \\(.+\\)\n\n" full)
942 (let ((pos-or-pass (match-string 1 full)))
943 (gnugo-put :get-move-string nil)
944 (gnugo-put :waitingp nil)
945 (gnugo-push-move nil pos-or-pass)
946 (let ((buf (current-buffer)))
947 (let (inhibit-gnugo-refresh)
948 (run-hooks 'gnugo-post-move-hook)
949 (unless inhibit-gnugo-refresh
950 (with-current-buffer buf
951 (gnugo-refresh))))))))))
953 (defun gnugo-get-move (color)
954 (gnugo-put :waitingp t)
955 (set-process-filter (gnugo-get :proc) 'gnugo-get-move-insertion-filter)
956 (gnugo-send-line (concat "genmove " color))
957 (accept-process-output))
959 (defun gnugo-cleanup ()
960 (when (gnugo-board-buffer-p)
961 (unless (zerop (buffer-size))
962 (message "Thank you for playing GNU Go."))
964 (setplist sym nil) ; "...is next to fordliness." --Huxley
966 (append (gnugo-get :all-yy)
975 (setq gnugo-state nil)))
977 (defun gnugo-position ()
978 (or (get-text-property (point) 'gnugo-position)
979 (error "Not a proper position point")))
982 "Make a move on the GNUGO Board buffer.
983 The position is computed from current point.
984 Signal error if done out-of-turn or if game-over.
985 To start a game try M-x gnugo."
988 (let* ((buf (current-buffer))
989 (pos (gnugo-position))
990 (move (format "play %s %s" (gnugo-get :user-color) pos))
991 (accept (cdr (gnugo-synchronous-send/return move))))
992 (unless (= ?= (aref accept 0))
994 (gnugo-push-move t pos) ; value always nil for non-pass move
995 (let (inhibit-gnugo-refresh)
996 (run-hooks 'gnugo-post-move-hook)
997 (unless inhibit-gnugo-refresh
998 (with-current-buffer buf
1000 (with-current-buffer buf
1001 (gnugo-get-move (gnugo-get :gnugo-color)))))
1003 (defun gnugo-mouse-move (e)
1004 "Do `gnugo-move' at mouse location."
1007 (when (looking-at "[.+]")
1010 (defun gnugo-pass ()
1011 "Make a pass on the GNUGO Board buffer.
1012 Signal error if done out-of-turn or if game-over.
1013 To start a game try M-x gnugo."
1016 (let ((accept (cdr (gnugo-synchronous-send/return
1017 (format "play %s PASS" (gnugo-get :user-color))))))
1018 (unless (= ?= (aref accept 0))
1019 (error "%s" accept)))
1020 (let ((donep (gnugo-push-move t "PASS"))
1021 (buf (current-buffer)))
1022 (let (inhibit-gnugo-refresh)
1023 (run-hooks 'gnugo-post-move-hook)
1024 (unless inhibit-gnugo-refresh
1025 (with-current-buffer buf
1028 (with-current-buffer buf
1029 (gnugo-get-move (gnugo-get :gnugo-color))))))
1031 (defun gnugo-mouse-pass (e)
1032 "Do `gnugo-pass' at mouse location."
1037 (defun gnugo-resign ()
1040 (if (not (y-or-n-p "Resign? "))
1041 (message "(not resigning)")
1042 (gnugo-push-move t "resign")
1045 (defun gnugo-animate-group (command)
1046 (message "Computing %s ..." command)
1047 (let* ((pos (gnugo-position))
1048 (orig-b-m-p (buffer-modified-p))
1049 (stones (if (memq (char-after) '(?X ?O))
1050 (gnugo-lsquery "%s %s" command pos)
1051 (error "No stone at %s" pos))))
1052 (message "Computing %s ... %s in group." command (length stones))
1053 (setplist (gnugo-f 'anim) nil)
1054 (let* ((spec (let ((spec (split-string gnugo-animation-string "" t)))
1055 (cond ((gnugo-get :display-using-images)
1056 (let* ((yin (get-text-property (point) 'gnugo-yin))
1057 (yang (gnugo-yang (char-after)))
1058 (up (get (gnugo-yy yin yang t) 'display))
1059 (dn (get (gnugo-yy yin yang) 'display))
1062 (if (setq flip-flop (not flip-flop))
1064 (mapcar 'string-to-char spec))))
1067 (ovs (save-excursion
1068 (mapcar (lambda (pos)
1069 (gnugo-goto-pos pos)
1071 (ov (make-overlay p (1+ p))))
1072 (overlay-put ov 'category (gnugo-f 'anim))
1073 (overlay-put ov 'priority most-positive-fixnum)
1076 (setplist (gnugo-f 'anim) (cons 'display cell))
1077 (while (and (cdr spec) ; let last linger lest levity lost
1078 (sit-for 0.08675309)) ; jenny jenny i got your number...
1079 (setcar cell (setq spec (cdr spec)))
1080 ;; Force redisplay of overlays.
1081 (set-buffer-modified-p orig-b-m-p))
1083 (mapc 'delete-overlay ovs)
1086 (defun gnugo-display-group-data (command buffer-name)
1087 (message "Computing %s ..." command)
1088 (let ((data (cdr (gnugo-synchronous-send/return
1089 (format "%s %s" command (gnugo-position))))))
1090 (switch-to-buffer buffer-name)
1093 (message "Computing %s ... done." command))
1095 (defun gnugo-worm-stones ()
1096 "In the GNUGO Board buffer, animate \"worm\" at current position.
1097 Signal error if done out-of-turn or if game-over.
1098 See variable `gnugo-animation-string' for customization."
1101 (gnugo-animate-group "worm_stones"))
1103 (defun gnugo-worm-data ()
1104 "Display in another buffer data from \"worm\" at current position.
1105 Signal error if done out-of-turn or if game-over."
1108 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1110 (defun gnugo-dragon-stones ()
1111 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1112 Signal error if done out-of-turn or if game-over.
1113 See variable `gnugo-animation-string' for customization."
1116 (gnugo-animate-group "dragon_stones"))
1118 (defun gnugo-dragon-data ()
1119 "Display in another buffer data from \"dragon\" at current position.
1120 Signal error if done out-of-turn or if game-over."
1123 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1125 (defun gnugo-toggle-dead-group ()
1126 "In a GNUGO Board buffer, during game-over, toggle a group as dead.
1127 The group is selected from current position (point). Signal error if
1128 not in game-over or if there is no group at that position.
1130 In the context of GNU Go, a group is called a \"dragon\" and may be
1131 composed of more than one \"worm\" (set of directly-connected stones).
1132 It is unclear to the gnugo.el author whether or not GNU Go supports
1133 - considering worms as groups in their own right; and
1134 - toggling group aliveness via GTP.
1135 Due to these uncertainties, this command is only half complete; the
1136 changes you may see in Emacs are not propagated to the gnugo subprocess.
1137 Thus, GTP commands like `final_score' may give unexpected results.
1139 If you are able to expose via GTP `change_dragon_status' in utils.c,
1140 you may consider modifying the `gnugo-toggle-dead-group' source code
1141 to enable full functionality."
1143 (let ((game-over (or (gnugo-get :game-over)
1144 (error "Sorry, game still in play")))
1145 (group (or (get-text-property (point) 'group)
1146 (error "No stone at that position")))
1147 (now (current-time)))
1148 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1150 (let ((live (assq 'live game-over))
1151 (dead (assq 'dead game-over))
1153 (if (memq group live)
1154 (setq bef live now dead)
1155 (setq bef dead now live))
1156 (setcdr bef (delq group (cdr bef)))
1157 (setcdr now (cons group (cdr now)))
1158 ;; disabled permanently -- too wrong
1162 (let ((color (caar group)))
1163 (dolist (stone (cdr group))
1164 (gnugo-query "play %s %s" color stone)))))
1167 ;; drastic (and wrong -- clobbers capture info, etc)
1168 (gnugo-query "clear_board")
1169 (mapc #'populate (cdr live)))))
1170 ;; here is the desired interface (to be enabled Some Day)
1172 (gnugo-query "change_dragon_status %s %s"
1173 (cadr group) (if (eq now live)
1179 (defun gnugo-estimate-score ()
1180 "Display estimated score of a game of GNU Go.
1181 Output includes number of stones on the board and number of stones
1182 captured by each player, and the estimate of who has the advantage (and
1183 by how many stones)."
1185 (message "Est.score ...")
1186 (let ((black (length (gnugo-lsquery "list_stones black")))
1187 (white (length (gnugo-lsquery "list_stones white")))
1188 (black-captures (gnugo-query "captures black"))
1189 (white-captures (gnugo-query "captures white"))
1190 (est (gnugo-query "estimate_score")))
1191 ;; might as well update this
1192 (gnugo-put :black-captures black-captures)
1193 (gnugo-put :white-captures white-captures)
1194 (message "Est.score ... B %s %s | W %s %s | %s"
1195 black black-captures white white-captures est)))
1197 (defun gnugo-write-sgf-file (filename)
1198 "Save the game history to FILENAME (even if unfinished).
1199 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1200 (interactive "FWrite game as SGF file: ")
1201 (when (and (file-exists-p filename)
1202 (not (y-or-n-p "File exists. Continue? ")))
1203 (error "Not writing %s" filename))
1204 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1205 (set-buffer-modified-p nil))
1207 (defun gnugo-read-sgf-file (filename)
1208 "Load the first game tree from FILENAME, a file in SGF format."
1209 (interactive "fSGF file to load: ")
1210 (when (file-directory-p filename)
1211 (error "Cannot load a directory (try a filename with extension .sgf)"))
1212 (let (ans play wait samep coll)
1213 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1214 ;; todo: skip it altogether when confident about `gnugo/sgf-read-file'
1215 (unless (= ?= (aref (setq ans (cdr (gnugo-synchronous-send/return
1216 (format "loadsgf %s"
1217 (expand-file-name filename)))))
1220 (setq play (substring ans 2)
1221 wait (gnugo-other play)
1222 samep (string= (gnugo-get :user-color) play))
1223 (gnugo-put :last-mover wait)
1225 (gnugo-put :gnugo-color wait)
1226 (gnugo-put :user-color play))
1227 (gnugo-put :sgf-collection (setq coll (gnugo/sgf-read-file filename)))
1228 (gnugo-put :sgf-gametree
1229 (nth (let ((n (length coll)))
1233 ;; (let* ((q (format "Which game? (1-%d)" n))
1234 ;; (choice (1- (read-number q 1))))
1235 ;; (if (and (< -1 choice) (< choice n))
1237 ;; (message "(Selecting the first game)")
1239 ;; but this is what we use (for now) to accomodate
1240 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1242 (message "(Selecting the first game)"))
1245 (let* ((tree (gnugo-get :sgf-gametree))
1248 mem node play game-over)
1249 (while (setq node (car loc))
1250 (when (setq play (or (assq :B node)
1252 ;; SGF[4] allows "" to mean PASS. For now,
1253 ;; we normalize here instead of at the lower layer.
1254 (when (string= "" (cdr play))
1258 (setq loc (cdr loc)))
1259 (gnugo-put :game-over
1261 (or (cdr (assq :RE (car tree)))
1264 (let ((order (if (string= "black" wait)
1267 (mapcar (lambda (pk)
1268 (cdr (assq (funcall pk order)
1269 (car (funcall pk mem)))))
1273 (vector (or (car mem) (gnugo-get :sgf-gametree))
1276 (when (and game-over
1277 ;; (maybe) todo: user var to inhibit (can be slow)
1279 (gnugo-close-game nil game-over)))
1281 (message "GNU Go %splays as %s, you as %s (%s)"
1282 (if samep "" "now ")
1285 "NOTE: this is a switch!"))))
1287 (defun gnugo-magic-undo (spec &optional noalt)
1288 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1289 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1290 check that the position is occupied by a stone of the user's color,
1291 and if so, remove moves from the history until that position is clear.
1292 If SPEC is a positive number, remove exactly that many moves from the
1293 history, signaling an error if the history is exhausted before finishing.
1294 If SPEC is not recognized, signal \"bad spec\" error.
1296 Refresh the board for each move undone. If (in the case where SPEC is
1297 a number) after finishing, the color to play is not the user's color,
1298 schedule a move by GNU Go.
1300 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1301 turn to play. Optional second arg NOALT non-nil inhibits this."
1304 (monkey (gnugo-get :monkey))
1305 (mem (aref monkey 1))
1306 (count (aref monkey 2))
1308 (cond ((and (numberp spec) (< 0 spec))
1309 (setq n spec done (lambda () (zerop n))))
1310 ((string-match "^[a-z]" spec)
1311 (let ((pos (upcase spec)))
1312 (setq done `(lambda ()
1313 (gnugo-goto-pos ,pos)
1314 (memq (char-after) '(?. ?+))))
1315 (when (funcall done)
1316 (error "%s already clear" pos))
1317 (let ((u (gnugo-get :user-color)))
1318 (when (= (save-excursion
1319 (gnugo-goto-pos pos)
1321 (if (string= "black" u)
1324 (error "%s not occupied by %s" pos u)))))
1325 (t (error "Bad spec: %S" spec)))
1326 (when (gnugo-get :game-over)
1327 (gnugo-put :game-over nil))
1328 (while (not (funcall done))
1329 (setq ans (cdr (gnugo-synchronous-send/return "undo")))
1330 (unless (= ?= (aref ans 0))
1332 (aset monkey 2 (decf count))
1333 (aset monkey 1 (setq mem (cdr mem)))
1334 (aset monkey 0 (or (car mem) (gnugo-get :sgf-gametree)))
1335 (gnugo-put :last-mover (gnugo-other (gnugo-get :last-mover)))
1336 (gnugo-merge-showboard-results) ; all
1337 (gnugo-refresh) ; this
1339 (redisplay))) ; eye candy
1340 (let* ((ulastp (string= (gnugo-get :last-mover) (gnugo-get :user-color)))
1342 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1343 (gnugo-put :last-user-bpos (if (and ubpos (not (string= "PASS" ubpos)))
1345 (gnugo-get :center-position)))
1347 ;; preserve restricted-functionality semantics (todo: remove restriction)
1348 (setcdr (aref (gnugo-get :monkey) 0) nil)
1349 (when (and ulastp (not noalt))
1350 (gnugo-get-move (gnugo-get :gnugo-color)))))
1352 (defun gnugo-undo-one-move ()
1353 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1354 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1355 See also `gnugo-undo-two-moves'."
1358 (gnugo-magic-undo 1 t))
1360 (defun gnugo-undo-two-moves ()
1361 "Undo a pair of moves (GNU Go's and yours).
1362 However, if you are the last mover, undo only one move.
1363 Regardless, after undoing, it is your turn to play again."
1366 (gnugo-magic-undo (if (string= (gnugo-get :user-color)
1367 (gnugo-get :last-mover))
1371 (defun gnugo-display-final-score ()
1372 "Display final score and other info in another buffer (when game over).
1373 If the game is still ongoing, Emacs asks if you wish to stop play (by
1374 making sure two \"pass\" moves are played consecutively, if necessary).
1375 Also, add the `:RE' SGF property to the root node of the game tree."
1377 (unless (or (gnugo-get :game-over)
1378 (and (not (gnugo-get :waitingp))
1379 (y-or-n-p "Game still in play. Stop play now? ")))
1380 (error "Sorry, game still in play"))
1381 (unless (gnugo-get :game-over)
1384 (message "Playing PASS for %s ..."
1385 (gnugo-get (if userp :user-color :gnugo-color)))
1387 (gnugo-push-move userp "PASS")))
1392 (let ((b= " Black = ")
1394 (res (let* ((node (car (aref (gnugo-get :monkey) 0)))
1395 (event (and node (cdr (assq :EV node)))))
1396 (and event (string= "resignation" event)
1397 (if (assq :B node) "black" "white"))))
1401 (format "%s wins.\n"
1402 (substring (if (= ?b (aref res 0)) w= b=)
1404 "The game is over.\n"
1405 (format "Resignation by %s.\n" res))
1406 result (concat (upcase (substring (gnugo-other res) 0 1))
1408 (message "Computing final score ...")
1409 (let* ((live (cdr (assq 'live (gnugo-get :game-over))))
1410 (dead (cdr (assq 'dead (gnugo-get :game-over))))
1411 (seed (gnugo-get :scoring-seed))
1412 (terr-q (format "final_status_list %%s_territory %d" seed))
1415 (b-terr (length (gnugo-lsquery terr-q "black")))
1416 (w-terr (length (gnugo-lsquery terr-q "white")))
1417 (b-capt (string-to-number (gnugo-get :black-captures)))
1418 (w-capt (string-to-number (gnugo-get :white-captures)))
1419 (komi (gnugo-treeroot :KM)))
1420 (setq blurb (list "The game is over. Final score:\n")
1421 result (gnugo-query "final_score %d" seed))
1422 (cond ((string= "Chinese" (gnugo-treeroot :RU))
1423 (dolist (group live)
1424 (let ((count (length (cdr group))))
1425 (if (string= "black" (caar group))
1426 (setq b-terr (+ b-terr count))
1427 (setq w-terr (+ w-terr count)))))
1428 (dolist (group dead)
1429 (let* ((color (caar group))
1430 (count (length (cdr group))))
1431 (if (string= "black" color)
1432 (setq w-terr (+ count w-terr))
1433 (setq b-terr (+ count b-terr)))))
1434 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1435 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1436 w-terr terr komi 'komi (+ w-terr komi))
1439 (dolist (group dead)
1440 (let* ((color (caar group))
1441 (adjust (* 2 (length (cdr group)))))
1442 (if (string= "black" color)
1443 (setq w-terr (+ adjust w-terr))
1444 (setq b-terr (+ adjust b-terr)))))
1445 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1450 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1454 (+ w-terr w-capt komi))
1456 (push (if (string= "0" result)
1457 "The game is a draw.\n"
1458 (format "%s wins by %s.\n"
1459 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1460 (substring result 2)))
1462 (message "Computing final score ... done")))
1464 (when (gnugo-get :game-end-time)
1466 (dolist (spec '(("Game start" . :game-start-time)
1467 (" end" . :game-end-time)))
1468 (push (format-time-string
1469 (concat (car spec) ": %Y-%m-%d %H:%M:%S %z\n")
1470 (gnugo-get (cdr spec)))
1472 (setq blurb (apply 'concat (nreverse blurb)))
1473 (let* ((root (car (gnugo-get :sgf-gametree)))
1474 (cur (assq :RE root)))
1477 (setcdr (last root) (list (cons :RE result)))))
1478 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
1482 ;;;---------------------------------------------------------------------------
1483 ;;; Command properties and gnugo-command
1485 ;; GTP commands entered by the user are never issued directly to GNU Go;
1486 ;; instead, their behavior and output are controlled by the property
1487 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
1488 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
1490 ;; :full -- completely interpret the command string; the value is a
1491 ;; func that takes the list of words derived from splitting the
1492 ;; command string (minus the command) and handles everything.
1494 ;; :output -- either a keyword specifying the preferred output method:
1495 ;; :message -- show output in minibuffer
1496 ;; :discard -- sometimes you just don't care;
1497 ;; or a function that takes one arg, the output string, and
1498 ;; handles it completely. default is to switch to buffer
1499 ;; "*gnugo command output*" if the output has a newline,
1500 ;; otherwise use `message'.
1502 ;; :post-hook -- normal hook run after output processing (at the very end).
1504 (defun gnugo-command (command)
1505 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
1506 Output and Emacs behavior depend on which command is given (some
1507 commands are handled completely by Emacs w/o using the subprocess;
1508 some commands have their output displayed in specially prepared
1509 buffers or in the echo area; some commands are instrumented to do
1510 gnugo.el-specific housekeeping).
1512 For example, for the command \"help\", Emacs visits the
1513 GTP command reference info page.
1515 NOTE: At this time, GTP command handling specification is still
1516 incomplete. Thus, some commands WILL confuse gnugo.el."
1517 (interactive "sCommand: ")
1518 (if (string= "" command)
1519 (message "(no command given)")
1520 (let* ((split (split-string command))
1521 (cmd (intern (car split)))
1522 (spec (get cmd :gnugo-gtp-command-spec))
1523 (full (plist-get spec :full))
1526 (funcall full (cdr split))
1527 (message "Doing %s ..." command)
1528 (let* ((ans (cdr (gnugo-synchronous-send/return command)))
1529 (where (plist-get spec :output)))
1530 (if (string-match "unknown.command" ans)
1532 (cond ((functionp where) (funcall where ans))
1533 ((eq :discard where) (message ""))
1534 ((or (eq :message where)
1535 (not (string-match "\n" ans)))
1537 (t (switch-to-buffer "*gnugo command output*")
1540 (message "Doing %s ... done." command)))
1542 ;; do not elide this binding; `run-hooks' needs it
1543 (plist-get spec :post-hook)))
1544 (run-hooks 'hook))))))))
1546 ;;;---------------------------------------------------------------------------
1547 ;;; Major mode for interacting with a GNUGO subprocess
1549 (put 'gnugo-board-mode 'mode-class 'special)
1550 (defun gnugo-board-mode ()
1551 "Major mode for playing GNU Go.
1552 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
1553 In this mode, keys do not self insert. Default keybindings:
1557 RET or SPC Run `gnugo-move'.
1559 q or Q Quit (the latter without confirmation).
1563 u Run `gnugo-undo-two-moves'.
1565 U Pass to `gnugo-magic-undo' either the board position
1566 at point (if no prefix arg), or the prefix arg converted
1567 to a number. E.g., to undo 16 moves: `C-u C-u U' (see
1568 `universal-argument'); to undo 42 moves: `M-4 M-2 U'.
1570 C-l Run `gnugo-refresh'.
1572 _ or M-_ Bury the Board buffer (when the boss is near).
1576 i Toggle display using XPM images (if supported).
1578 w Run `gnugo-worm-stones'.
1579 d Run `gnugo-dragon-stones'.
1581 W Run `gnugo-worm-data'.
1582 D Run `gnugo-dragon-data'.
1584 t Run `gnugo-toggle-dead-group'.
1586 ! Run `gnugo-estimate-score'.
1588 : or ; Run `gnugo-command' (for GTP commands to GNU Go).
1590 = Display board position under point (if valid).
1592 h Run `gnugo-move-history'.
1594 F Run `gnugo-display-final-score'.
1596 s Run `gnugo-write-sgf-file'.
1600 l Run `gnugo-read-sgf-file'."
1601 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
1602 (buffer-disable-undo) ; todo: undo undo undoing
1603 (kill-all-local-variables)
1604 (setq truncate-lines t)
1605 (use-local-map gnugo-board-mode-map)
1606 (set (make-local-variable 'font-lock-defaults)
1607 '(gnugo-font-lock-keywords t))
1608 (setq major-mode 'gnugo-board-mode)
1609 (setq mode-name "GNUGO Board")
1610 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
1611 (set (make-local-variable 'gnugo-state)
1612 (make-hash-table :size (1- 42) :test 'eq))
1613 (add-to-invisibility-spec :nogrid)
1614 (mapc (lambda (prop)
1615 (gnugo-put prop nil)) ; todo: separate display/game aspects;
1616 '(:game-over ; move latter to func `gnugo'
1623 :display-using-images
1627 (let ((name (if (string-match "[ ]" gnugo-program)
1628 (let ((p (substring gnugo-program 0 (match-beginning 0)))
1629 (o (substring gnugo-program (match-end 0)))
1630 (h (or (car gnugo-option-history) "")))
1631 (when (string-match "--mode" o)
1632 (error "Found \"--mode\" in `gnugo-program'"))
1633 (when (and o (< 0 (length o))
1635 (or (< (length h) (length o))
1636 (not (string= (substring h 0 (length o))
1638 (push (concat o " " h) gnugo-option-history))
1641 (args (read-string "GNU Go options: "
1642 (car gnugo-option-history)
1643 'gnugo-option-history))
1645 board-size user-color handicap komi minus-l infile)
1647 (apply (lambda (var default opt &optional rx)
1649 (or (when (string-match opt args)
1650 (let ((start (match-end 0)) s)
1651 (string-match (or rx "[0-9.]+") args start)
1652 (setq s (match-string 0 args))
1653 (if rx s (string-to-number s))))
1656 '((board-size 19 "--boardsize")
1657 (user-color "black" "--color" "\\(black\\|white\\)")
1658 (handicap 0 "--handicap")
1660 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
1661 (infile nil "--infile" "[ ]*[^ ]+")))
1662 (gnugo-put :user-color user-color)
1663 (when (string-match "--chinese-rules" args)
1664 (setq rules "Chinese"))
1665 (let ((proc-args (split-string args)))
1666 (gnugo-put :proc-args proc-args)
1667 (gnugo-put :proc (apply 'start-process "gnugo" nil name
1668 "--mode" "gtp" "--quiet"
1670 ;; Emacs is too protective sometimes, blech.
1671 (remove-hook (make-local-variable 'kill-buffer-query-functions)
1672 'process-kill-buffer-query-function
1674 (when (or minus-l infile)
1676 (apply (lambda (prop q)
1677 (set prop (string-to-number (gnugo-query q))))
1679 '((board-size "query_boardsize")
1681 (handicap "get_handicap"))))
1682 (gnugo-put :diamond (substring (process-name (gnugo-get :proc)) 5))
1683 (gnugo-put :gnugo-color (gnugo-other (gnugo-get :user-color)))
1684 (gnugo-put :highlight-last-move-spec
1685 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
1686 (gnugo-put :lparen-ov (make-overlay 1 1))
1687 (gnugo-put :rparen-ov (let ((ov (make-overlay 1 1)))
1688 (overlay-put ov 'display ")")
1690 (gnugo-put :sgf-gametree (list (list '(:FF . 4) '(:GM . 1))))
1691 (let ((tree (gnugo-get :sgf-gametree)))
1692 (gnugo-put :sgf-collection (list tree))
1693 (gnugo-put :monkey (vector tree nil 0)))
1694 (let ((g-blackp (string= "black" (gnugo-get :gnugo-color))))
1695 (mapc (lambda (x) (apply 'gnugo-note x))
1697 (:DT ,(format-time-string "%Y-%m-%d"))
1699 (:AP ("gnugo.el" . ,gnugo-version))
1701 (,(if g-blackp :PW :PB) ,(user-full-name))
1702 (,(if g-blackp :PB :PW) ,(concat "GNU Go "
1703 (gnugo-query "version")))
1704 ,@(when (not (zerop handicap))
1706 (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
1708 (set-process-sentinel (gnugo-get :proc) 'gnugo-sentinel)
1709 (set-process-buffer (gnugo-get :proc) (current-buffer))
1710 (gnugo-put :waiting-start (current-time))
1713 (run-hooks 'gnugo-board-mode-hook)
1716 ;;;---------------------------------------------------------------------------
1720 (defun gnugo (&optional new-game)
1721 "Run gnugo in a buffer, or resume a game in progress.
1722 Prefix arg means skip the game-in-progress check and start a new
1725 You are queried for additional command-line options (Emacs supplies
1726 \"--mode gtp --quiet\" automatically). Here is a list of options
1727 that gnugo.el understands and handles specially:
1729 --boardsize num Set the board size to use (5--19)
1730 --color <color> Choose your color ('black' or 'white')
1731 --handicap <num> Set the number of handicap stones (0--9)
1733 If there is already a game in progress you may resume it instead of
1734 starting a new one. See `gnugo-board-mode' documentation for more info."
1736 (let* ((all (let (acc)
1737 (dolist (buf (buffer-list))
1738 (when (gnugo-board-buffer-p buf)
1739 (push (cons (buffer-name buf) buf) acc)))
1742 (if (and (not new-game)
1744 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
1745 (if (= 1 n) "" "s"))))
1750 (let ((sel (completing-read "Which one? " all nil t)))
1751 (if (string= "" sel)
1753 (assoc sel all))))))
1754 ;; set up a new board
1756 (let ((half (truncate (1+ (gnugo-treeroot :SZ)) 2)))
1757 (gnugo-goto-pos (format "A%d" half))
1758 (forward-char (* 2 (1- half)))
1759 (gnugo-put :last-user-bpos
1760 (gnugo-put :center-position
1761 (get-text-property (point) 'gnugo-position))))
1763 (gnugo-put :game-start-time (current-time))
1764 (let ((g (gnugo-get :gnugo-color))
1765 (n (or (gnugo-treeroot :HA) 0))
1766 (u (gnugo-get :user-color)))
1767 (gnugo-put :last-mover g)
1768 (when (or (and (string= "black" u) (< 1 n))
1769 (and (string= "black" g) (< n 2)))
1770 (gnugo-put :last-mover u)
1772 (gnugo-get-move g))))))
1774 ;;;---------------------------------------------------------------------------
1775 ;;; Load-time actions
1777 (unless gnugo-board-mode-map
1778 (setq gnugo-board-mode-map (make-sparse-keymap))
1779 (suppress-keymap gnugo-board-mode-map)
1780 (mapc (lambda (pair)
1781 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
1782 '(("?" . describe-mode)
1783 ("\C-m" . gnugo-move)
1786 ("R" . gnugo-resign)
1787 ("q" . (lambda () (interactive)
1788 (if (or (gnugo-get :game-over)
1789 (y-or-n-p "Quit? "))
1791 (message "(not quitting)"))))
1792 ("Q" . (lambda () (interactive)
1794 ("U" . (lambda (x) (interactive "P")
1796 (cond ((numberp x) x)
1798 (t (gnugo-position))))))
1799 ("u" . gnugo-undo-two-moves)
1800 ("\C-l" . gnugo-refresh)
1801 ("\M-_" . bury-buffer)
1803 ("h" . gnugo-move-history)
1804 ("i" . (lambda () (interactive)
1805 (gnugo-toggle-image-display)
1806 (save-excursion (gnugo-refresh))))
1807 ("w" . gnugo-worm-stones)
1808 ("W" . gnugo-worm-data)
1809 ("d" . gnugo-dragon-stones)
1810 ("D" . gnugo-dragon-data)
1811 ("t" . gnugo-toggle-dead-group)
1812 ("g" . gnugo-toggle-grid)
1813 ("!" . gnugo-estimate-score)
1814 (":" . gnugo-command)
1815 (";" . gnugo-command)
1816 ("=" . (lambda () (interactive)
1817 (message (gnugo-position))))
1818 ("s" . gnugo-write-sgf-file)
1819 ("\C-x\C-s" . gnugo-write-sgf-file)
1820 ("\C-x\C-w" . gnugo-write-sgf-file)
1821 ("l" . gnugo-read-sgf-file)
1822 ("F" . gnugo-display-final-score)
1824 ([(down-mouse-1)] . gnugo-mouse-move)
1825 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
1826 ([(down-mouse-3)] . gnugo-mouse-pass)
1827 ;; delving into the curiosities
1828 ("\C-c\C-p" . gnugo-describe-internal-properties))))
1830 (unless (get 'help :gnugo-gtp-command-spec)
1832 ((sget (x) (get x :gnugo-gtp-command-spec))
1833 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
1834 (plist-put (sget cmd) prop val)))
1835 (add (cmd prop val) (jam cmd prop (let ((cur (plist-get
1838 (append (delete val cur)
1840 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
1843 (funcall (if (eq :post-hook (car ls))
1846 cmd (car ls) (cadr ls))
1847 (setq ls (cddr ls)))))))
1851 (info "(gnugo)GTP command reference")
1852 (when sel (setq sel (intern (car sel))))
1853 (let (buffer-read-only pad cur spec output found)
1855 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
1856 (goto-char (point-min))
1858 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
1861 (setq pad (make-string (- (match-beginning 1)
1862 (match-beginning 0))
1866 (get (setq cur (intern (match-string 1)))
1867 :gnugo-gtp-command-spec))
1869 (note "handles this command completely"))
1870 (when (setq output (plist-get spec :output))
1871 (cond ((functionp output)
1872 (note "handles the output specially"))
1873 ((eq :discard output)
1874 (note "discards the output"))
1875 ((eq :message output)
1876 (note "displays the output in the echo area"))))
1878 (setq found (match-beginning 0))))))
1879 (cond (found (goto-char found))
1881 (t (message "(no such command: %s)" sel))))))
1883 (defgtp 'final_score :full
1884 (lambda (sel) (gnugo-display-final-score)))
1890 :post-hook (lambda ()
1891 (gnugo-put :game-over nil)
1892 (gnugo-put :last-mover nil)
1895 (defgtp 'loadsgf :full
1896 (lambda (sel) (gnugo-read-sgf-file (car sel))))
1898 (defgtp '(undo gg-undo) :full
1899 (lambda (sel) (gnugo-magic-undo
1902 ((< 0 (setq n (string-to-number (car sel)))) n)
1903 (t (car sel)))))))))
1908 ;;;---------------------------------------------------------------------------
1909 ;;; The remainder of this file defines a simplified SGF-handling library.
1910 ;;; When/if it should start to attain generality, it should be split off into
1911 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
1912 ;;; "gnugo/" prefix.
1914 (defconst gnugo/sgf-*r4-properties*
1915 '((AB "Add Black" setup list stone)
1916 (AE "Add Empty" game list point)
1917 (AN "Annotation" game simpletext)
1918 (AP "Application" root (simpletext . simpletext))
1919 (AR "Arrow" - list (point . point))
1920 (AS "Who adds stones" - simpletext) ; (LOA)
1921 (AW "Add White" setup list stone)
1922 (B "Black" move move)
1923 (BL "Black time left" move real)
1924 (BM "Bad move" move double)
1925 (BR "Black rank" game simpletext)
1926 (BT "Black team" game simpletext)
1927 (C "Comment" - text)
1928 (CA "Charset" root simpletext)
1929 (CP "Copyright" game simpletext)
1930 (CR "Circle" - list point)
1931 (DD "Dim points" - elist point) ; (inherit)
1932 (DM "Even position" - double)
1933 (DO "Doubtful" move none)
1934 (DT "Date" game simpletext)
1935 (EV "Event" game simpletext)
1936 (FF "Fileformat" root [number (1 . 4)])
1937 (FG "Figure" - (or none (number . simpletext)))
1938 (GB "Good for Black" - double)
1939 (GC "Game comment" game text)
1940 (GM "Game" root [number (1 . 20)])
1941 (GN "Game name" game simpletext)
1942 (GW "Good for White" - double)
1943 (HA "Handicap" game number) ; (Go)
1944 (HO "Hotspot" - double)
1945 (IP "Initial pos." game simpletext) ; (LOA)
1946 (IT "Interesting" move none)
1947 (IY "Invert Y-axis" game simpletext) ; (LOA)
1948 (KM "Komi" game real) ; (Go)
1950 (LB "Label" - list (point . simpletext))
1951 (LN "Line" - list (point . point))
1952 (MA "Mark" - list point)
1953 (MN "set move number" move number)
1954 (N "Nodename" - simpletext)
1955 (OB "OtStones Black" move number)
1956 (ON "Opening" game text)
1957 (OT "Overtime" game simpletext)
1958 (OW "OtStones White" move number)
1959 (PB "Player Black" game simpletext)
1960 (PC "Place" game simpletext)
1961 (PL "Player to play" setup color)
1962 (PM "Print move mode" - number) ; (inherit)
1963 (PW "Player White" game simpletext)
1964 (RE "Result" game simpletext)
1965 (RO "Round" game simpletext)
1966 (RU "Rules" game simpletext)
1967 (SE "Markup" - point) ; (LOA)
1968 (SL "Selected" - list point)
1969 (SO "Source" game simpletext)
1970 (SQ "Square" - list point)
1971 (ST "Style" root [number (0 . 3)])
1972 (SU "Setup type" game simpletext) ; (LOA)
1973 (SZ "Size" root (or number (number . number)))
1974 (TB "Territory Black" - elist point) ; (Go)
1975 (TE "Tesuji" move double)
1976 (TM "Timelimit" game real)
1977 (TR "Triangle" - list point)
1978 (TW "Territory White" - elist point) ; (Go)
1979 (UC "Unclear pos" - double)
1980 (US "User" game simpletext)
1982 (VW "View" - elist point) ; (inherit)
1983 (W "White" move move)
1984 (WL "White time left" move real)
1985 (WR "White rank" game simpletext)
1986 (WT "White team" game simpletext)
1987 (LT "Lose on time" setup simpletext))
1988 ;; r4-specific notes
1989 ;; - changed: DT FG LB RE RU SZ
1990 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
1991 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
1993 (defun gnugo/sgf-read-file (filename)
1994 "Return the collection (list) of gametrees in SGF[4] file FILENAME."
1995 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
1996 (put 'gnugo/sgf-*r4-properties* :keywords
1997 (mapcar (lambda (full)
1999 (intern (format ":%s" (car full)))))
2000 gnugo/sgf-*r4-properties*))))
2001 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2002 (put 'gnugo/sgf-*r4-properties* :specs
2003 (mapcar (lambda (full)
2004 (cons (car full) (cdddr full)))
2005 gnugo/sgf-*r4-properties*)))))
2007 ((sw () (skip-chars-forward " \t\n"))
2008 (x (end) (let ((beg (point))
2010 (:end (lambda (char) (= ?\] char)))
2011 (:mid (lambda (char) (= ?\: char)))
2012 (t (lambda (char) (or (= ?\: char)
2015 (while (not (funcall endp (setq c (char-after))))
2021 ((looking-at "\\s-+")
2022 (delete-region (point) (match-end 0))
2024 (t (forward-char 1))))
2025 (buffer-substring-no-properties beg (point))))
2026 (one (type end) (unless (eq 'none type)
2030 ((stone point move simpletext color) s)
2031 ((number real double) (string-to-number s))
2033 (t (error "Unhandled type: %S" type))))))
2034 (val (spec) (cond ((symbolp spec)
2037 ;; todo: check range here.
2038 (one (aref spec 0) :end))
2039 ((eq 'or (car spec))
2040 (let ((v (one (cadr spec) t)))
2041 (if (= ?\] (char-after))
2044 ;; todo: this assumes `spec' has the form
2045 ;; (or foo (foo . bar))
2046 ;; i.e., foo is not rescanned. e.g., `SZ'.
2047 ;; probably this assumption is consistent
2048 ;; w/ the SGF authors' desire to make the
2049 ;; parsing easy, but you never know...
2050 (cons v (one (cdaddr spec) :end)))))
2051 (t (cons (one (car spec) :mid)
2052 (one (cdr spec) :end)))))
2053 (short (who) (when (eobp)
2054 (error "Unexpected EOF while reading %s" who)))
2055 (atvalp () (= ?\[ (char-after)))
2056 (PROP () (let (name spec ltype)
2057 (sw) (short 'property)
2058 (when (looking-at "[A-Z]")
2059 (setq name (read (current-buffer))
2060 spec (cdr (assq name specs)))
2063 (cdr (assq name keywords))
2064 (prog1 (if (= 1 (length spec))
2066 (unless (memq (setq ltype (car spec))
2068 (error "Bad spec: %S" spec))
2069 (if (and (eq 'elist ltype) (sw)
2072 (let ((type (cadr spec))
2074 (while (and (sw) (atvalp)
2075 (setq mo (val type)))
2080 (forward-char 1))))))
2081 (NODE () (let (prop props)
2083 (when (= ?\; (char-after))
2085 (while (setq prop (PROP))
2088 (TREE () (let (nodes)
2089 (while (and (sw) (not (eobp)))
2091 (?\; (push (NODE) nodes))
2092 (?\( (forward-char 1)
2093 (push (TREE) nodes))
2094 (?\) (forward-char 1))))
2097 (insert-file-contents filename)
2099 (while (and (sw) (not (eobp)) (= 40 (char-after))) ; left paren
2101 (push (TREE) trees))
2102 (nreverse trees))))))
2104 (defun gnugo/sgf-write-file (collection filename)
2105 ;; take responsibility for our actions
2106 (dolist (tree collection)
2107 (let* ((root (car tree))
2108 (who (assq :AP root))
2109 (fruit (cons "gnugo.el" gnugo-version)))
2112 (setcdr (last root) (list (cons :AP fruit))))))
2114 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2115 (specs (mapcar (lambda (full)
2116 (cons (intern (format ":%s" (car full)))
2118 gnugo/sgf-*r4-properties*))
2120 ;; todo: escape special chars for `text' and `simpletext'.
2122 ((>>one (v) (insert (format "[%s]" v)))
2123 (>>two (v) (insert (format "[%s:%s]" (car v) (cdr v))))
2124 (>>nl () (cond ((memq name aft-newline-appreciated)
2126 ((< 60 (current-column))
2131 (dolist (tree collection)
2139 (insert (substring (symbol-name name) 1))
2142 (memq (car (setq spec (cdr (assq name specs))))
2145 (let ((>> (if (consp (cadr spec))
2148 (dolist (little-v v)
2149 (setq p (point)) (funcall >> little-v) (>>nl))))
2153 (>>one v) (>>nl)))))
2155 (write-file filename)))))
2157 ;;; gnugo.el ends here