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
57 ;; This code was tested with:
58 ;; - GNU Emacs: 21.3 / 22.0.50 (from CVS)
59 ;; - GNU Go: 3.3.15 / 3.4 / 3.6
62 ;; Meta-Playing (aka Customizing)
63 ;; ------------------------------
65 ;; Customization is presently limited to
66 ;; vars: `gnugo-program'
67 ;; `gnugo-animation-string'
69 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
71 ;; normal hooks: `gnugo-board-mode-hook'
72 ;; `gnugo-post-move-hook'
73 ;; and the keymap: `gnugo-board-mode-map'
75 ;; The variable `gnugo-xpms' is a special case. To set it you need to load
76 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
80 ;; Meta-Meta-Playing (aka Hacking)
81 ;; -------------------------------
83 ;; You may wish to first fix the bugs:
84 ;; - `gnugo-toggle-dead-group' only half-complete; see docstring for details
85 ;; - probably sgf handling is not 100% to spec
86 ;; - subprocess should provide scoring details, gnugo.el not yet blissful
88 ;; Otherwise (we can live w/ some bugs), here are some ideas:
89 ;; - talk GTP over the network
90 ;; - "assist minor mode" (see gnugo-extra.el for work in progress)
91 ;; - using assist minor mode, gnugo-v-gnugo (ibid)
92 ;; - extract GNUGO Board mode and sgf stuff into sgf.el; make gnugo.el use it
93 ;; - make gnugo (the external program) support query (read-only) thread
94 ;; so as to be able to lift "still waiting" restriction
95 ;; - alternatively, extend GNUGO Board mode to manage another subprocess
96 ;; dedicated to analysis (no genmove)
97 ;; - command `C' to add a comment to the sgf tree
98 ;; - command `C-u =' to label a position
99 ;; - sgf tree display, traversal (belongs in sgf.el); review game history
100 ;; in another buffer; branch subgame tree at arbitrary point
101 ;; - subgame branch matriculation (maturity: child leaves the family)
102 ;; - dribble the sgf tree
103 ;; - "undo undo undoing"; integrate Emacs undo, GTP undo, subgame branching
104 ;; - make buffer name format configurable (but enforce uniqueness)
105 ;; - more tilde escapes for `gnugo-mode-line'
106 ;; - make veneration configurable
107 ;; - make animation more configurable; lift same-color-stones-only
108 ;; restriction; allow sequencing rather than lock-step; include sound
109 ;; - [your hacking ideas here]
111 ;; Some gnugo.el hackers update http://www.emacswiki.org -- check it out!
115 (require 'cl-lib) ; use the source luke!
116 (require 'time-date) ; for `time-subtract'
118 ;;;---------------------------------------------------------------------------
121 (defconst gnugo-version "2.2.14"
122 "Version of gnugo.el currently loaded.
123 Note that more than two dots in the value indicates \"pre-release\",
124 or \"alpha\" or \"hackers-invited-all-else-beware\"; use at your own risk!
125 The more dots the more courage/foolishness you must find to continue.
126 See source code for a history of what means what version-wise.")
128 ;;;---------------------------------------------------------------------------
129 ;;; Variables for the uninquisitive programmer
131 (defvar gnugo-program "gnugo"
132 "*Command to start an external program that speaks GTP, such as \"gnugo\".
133 The value may also be in the form \"PROGRAM OPTIONS...\" in which case the
134 the command `gnugo' will prefix OPTIONS in its default offering when it
135 queries you for additional options. It is an error for \"--mode\" to appear
138 For more information on GTP and GNU Go, feel free to visit:
139 http://www.gnu.org/software/gnugo")
141 (defvar gnugo-board-mode-map nil
142 "Keymap for GNUGO Board mode.")
144 (defvar gnugo-board-mode-hook nil
145 "*Hook run when entering GNUGO Board mode.")
147 (defvar gnugo-post-move-hook nil
148 "*Normal hook run after a move and before the board is refreshed.
149 Hook functions can prevent the call to `gnugo-refresh' by evaluating:
150 (setq inhibit-gnugo-refresh t)
151 Initially, when `run-hooks' is called, the current buffer is the GNUGO
152 Board buffer of the game. Hook functions that switch buffers must take
153 care not to call (directly or indirectly through some other function)
154 `gnugo-put' or `gnugo-get' after the switch.")
156 (defvar gnugo-animation-string
157 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
158 (concat jam jam jam jam jam
159 ;; "SECRET MESSAGE HERE"
160 blink blink blink blink blink blink blink blink
161 ;; Playing go is like fighting ignorance: when you think you have
162 ;; surrounded something by knowing it very well it often turns
163 ;; out that in the time you spent deepening this understanding,
164 ;; other areas of ignorance have surrounded you.
165 spin spin spin spin spin spin spin spin spin
166 ;; Playing go is not like fighting ignorance: what one person
167 ;; knows many people may come to know; knowledge does not build
168 ;; solely move by move. Wisdom, on the other hand...
170 "*String whose individual characters are used for animation.
171 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
172 render the stones in their respective result groups as the first character
173 in the string, then the next, and so on.")
175 (defvar gnugo-mode-line "~b ~w :~m :~u"
176 "*A `mode-line-format'-compliant value for GNUGO Board mode.
177 If a single string, the following special escape sequences are
178 replaced with their associated information:
179 ~b,~w black,white captures (a number)
180 ~p current player (black or white)
182 ~t time waiting for the current move
183 ~u time taken for the Ultimate (most recent) move
184 The times are in seconds, or \"-\" if that information is not available.
185 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
187 (defvar gnugo-X-face 'font-lock-string-face
188 "*Name of face to use for X (black) stones.")
190 (defvar gnugo-O-face 'font-lock-builtin-face
191 "*Name of face to use for O (white) stones.")
193 (defvar gnugo-grid-face 'default
194 "*Name of face to use for the grid (A B C ... 1 2 3 ...).")
196 ;;;---------------------------------------------------------------------------
197 ;;; Variables for the inquisitive programmer
199 (defconst gnugo-font-lock-keywords
200 '(("X" . gnugo-X-face)
201 ("O" . gnugo-O-face))
202 "Font lock keywords for `gnugo-board-mode'.")
204 (defvar gnugo-option-history nil)
206 (defvar gnugo-state nil) ; hint: C-c C-p
209 (defvar gnugo-xpms nil))
211 ;;;---------------------------------------------------------------------------
212 ;;; In case Emacs is lacking
214 (unless (fboundp 'delete-dups)
215 (defun delete-dups (list) ; from repo 2004-10-29
216 "Destructively remove `equal' duplicates from LIST.
217 Store the result in LIST and return it. LIST must be a proper list.
218 Of several `equal' occurrences of an element in LIST, the first
222 (setcdr tail (delete (car tail) (cdr tail)))
223 (setq tail (cdr tail))))
226 (unless (fboundp 'window-edges)
227 (defun window-edges (&optional window)
228 (let ((cw (/ (frame-pixel-width) (frame-width)))
229 (ch (/ (frame-pixel-height) (frame-height)))
230 (pix-edges (window-pixel-edges window)))
231 (list (/ (nth 0 pix-edges) cw)
232 (/ (nth 1 pix-edges) ch)
233 (/ (nth 2 pix-edges) cw)
234 (/ (nth 3 pix-edges) ch)))))
236 ;;;---------------------------------------------------------------------------
237 ;;; Support functions
239 (put 'gnugo-put 'lisp-indent-function 1)
240 (defun gnugo-put (key value) (puthash key value gnugo-state))
241 (defun gnugo-get (key) (gethash key gnugo-state))
243 (let ((docs "Put or get move/game/board-specific properties.
244 \(This docstring is shared by `gnugo-put' and `gnugo-get'.\)
246 There are many properties, each named by a keyword, that record and control
247 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
248 of properties, stored in the hash table `gnugo-state'. Here we document
249 some of the more stable properties. You may wish to use them as part of
250 a `gnugo-post-move-hook' function, for example. Be careful to preserve
251 the current buffer as `gnugo-state' is made into a buffer-local variable.
252 NOTE: In the following, \"see foo\" actually means \"see foo source or
253 you may never really understand to any degree of personal satisfaction\".
255 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
257 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
259 :game-over -- nil until game over at which time its value is set to
260 the alist `((live GROUP ...) (dead GROUP ...))'
262 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
263 a simple list of one or more gametrees, updated in
264 conjunction w/ :sgf-gametree and :monkey
266 :sgf-gametree -- one of the gametrees in :sgf-collection
268 :monkey -- vector of three elements: LOC, a pointer to a node on the
269 :sgf-gametree representing the most recently-played move
270 (the next move modifies the cdr of LOC); MEM, the simple
271 reverse-chronological list of previous LOC pointers; and
272 COUNT, the number of moves from the beginning of the game
274 :gnugo-color -- either \"black\" or \"white\"
278 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
281 :black-captures -- these are strings since gnugo.el doesn't do anything
282 :white-captures w/ the information besides display it in the mode line;
283 gory details in functions `gnugo-propertize-board-buffer'
284 and `gnugo-merge-showboard-results' (almost more effort
285 than they are worth!)
287 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
288 `gnugo-toggle-image-display' and `gnugo-refresh',
289 as well as gnugo-xpms.el (available elsewhere)
291 :all-yy -- list of 46 keywords used as the `category' text property
292 (so that their plists, typically w/ property `display' or
293 `do-not-display') are consulted by the Emacs display engine;
294 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
295 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
297 :lparen-ov -- overlays shuffled about to indicate the last move; only
298 :rparen-ov one is used when displaying using images
300 :last-user-bpos -- board position; keep the hapless human happy
302 As things stabilize probably more info will be added to this docstring."))
303 (put 'gnugo-put 'function-documentation docs)
304 (put 'gnugo-get 'function-documentation docs))
306 (defun gnugo-describe-internal-properties ()
307 "Pretty-print `gnugo-state' properties in another buffer.
308 Handle the big, slow-to-render, and/or uninteresting ones specially."
310 (let ((buf (current-buffer))
311 (d (gnugo-get :diamond))
313 (maphash (lambda (&rest args)
316 (setcdr args (format "hash: %X (%d images)"
318 (length (cadr args)))))
320 (setcdr args (length (cadr args))))
322 (let* ((value (cadr args))
323 (loc (aref value 0)))
325 (length (aref value 1))
328 (setq acc (cons args acc)))
330 (switch-to-buffer (get-buffer-create
331 (format "%s*GNUGO Board Properties*"
332 (gnugo-get :diamond))))
335 (setq truncate-lines t)
337 (let ((standard-output (current-buffer)))
339 (goto-char (point-min))
340 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
344 (while (re-search-forward rx (point-max) t)
345 (let ((pos (get-text-property (string-to-number (match-string 1))
346 'gnugo-position buf)))
347 (delete-region (+ 2 (match-beginning 0)) (point))
348 (insert (format " %S" pos))))))
349 (message "%d properties" (length acc))))
351 (defun gnugo-board-buffer-p (&optional buffer)
352 "Return non-nil if BUFFER is a GNUGO Board buffer."
353 (with-current-buffer (or buffer (current-buffer)) gnugo-state))
355 (defun gnugo-board-user-play-ok-p (&optional buffer)
356 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
357 (with-current-buffer (or buffer (current-buffer))
358 (and gnugo-state (not (gnugo-get :waitingp)))))
360 (defun gnugo-other (color)
361 (if (string= "black" color) "white" "black"))
363 (defun gnugo-gate (&optional in-progress-p)
364 (unless (gnugo-board-buffer-p)
365 (error "Wrong buffer -- try M-x gnugo"))
366 (unless (gnugo-get :proc)
367 (error "No \"gnugo\" process!"))
368 (when (gnugo-get :waitingp)
369 (error "Not your turn yet -- please wait for \"\(%s to play\)\""
370 (gnugo-get :user-color)))
371 (when (and (gnugo-get :game-over) in-progress-p)
372 (error "Sorry, game over")))
374 (defun gnugo-sentinel (proc string)
375 (let ((status (process-status proc)))
376 (when (or (eq status 'exit)
378 (let ((buf (process-buffer proc)))
379 (when (buffer-live-p buf)
380 (with-current-buffer buf
381 (setq mode-line-process '( " [%s]"))
382 (when (eq proc (gnugo-get :proc))
383 (gnugo-put :proc nil))))))))
385 (defun gnugo-send-line (line)
386 (let ((proc (gnugo-get :proc)))
387 (process-send-string proc line)
388 (process-send-string proc "\n")))
390 (defun gnugo-synchronous-send/return (message)
391 "Return (TIME . STRING) where TIME is that returned by `current-time' and
392 STRING omits the two trailing newlines. See also `gnugo-query'."
393 (when (gnugo-get :waitingp)
394 (error "Sorry, still waiting for %s to play" (gnugo-get :gnugo-color)))
395 (gnugo-put :sync-return "")
396 (let ((proc (gnugo-get :proc)))
398 proc (lambda (proc string)
399 (let* ((so-far (gnugo-get :sync-return))
400 (start (max 0 (- (length so-far) 2))) ; backtrack a little
401 (full (gnugo-put :sync-return (concat so-far string))))
402 (when (string-match "\n\n" full start)
403 (gnugo-put :sync-return
404 (cons (current-time) (substring full 0 -2)))))))
405 (gnugo-send-line message)
407 ;; type change => break
408 (while (stringp (setq rv (gnugo-get :sync-return)))
409 (accept-process-output proc))
410 (gnugo-put :sync-return "")
413 (defun gnugo-query (message-format &rest args)
414 "Return cleaned-up value of a call to `gnugo-synchronous-send/return'.
415 The TIME portion is omitted as well as the first two characters of the STRING
416 portion (corresponding to the status indicator in the Go Text Protocol). Use
417 this function when you are sure the command cannot fail. The first arg is
418 a format string applied to the rest of the args."
419 (substring (cdr (gnugo-synchronous-send/return
420 (apply 'format message-format args)))
423 (defun gnugo-lsquery (message-format &rest args)
424 (split-string (apply 'gnugo-query message-format args)))
426 (defsubst gnugo-treeroot (prop)
427 (cdr (assq prop (car (gnugo-get :sgf-gametree)))))
429 (defun gnugo-goto-pos (pos)
430 "Move point to board position POS, a letter-number string."
431 (goto-char (point-min))
432 (forward-line (- (1+ (gnugo-treeroot :SZ))
433 (string-to-number (substring pos 1))))
435 (forward-char (+ (if (= 32 (following-char)) 1 2)
436 (* 2 (- (let ((letter (aref pos 0)))
442 (defun gnugo-f (frag)
443 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
445 (defun gnugo-yang (c)
446 (cdr (assq c '((?+ . hoshi)
448 (?X . (bmoku . bpmoku))
449 (?O . (wmoku . wpmoku))))))
451 (defun gnugo-yy (yin yang &optional momentaryp)
452 (gnugo-f (format "%d-%s"
453 yin (cond ((and (consp yang) momentaryp) (cdr yang))
454 ((consp yang) (car yang))
457 (defun gnugo-toggle-image-display ()
458 (unless (and (fboundp 'display-images-p) (display-images-p))
459 (error "Display does not support images, sorry"))
460 (require 'gnugo-xpms)
461 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
462 (error "Could not load `gnugo-xpms', sorry"))
463 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
464 (unless (eq fresh (gnugo-get :xpms))
465 (gnugo-put :xpms fresh)
466 (gnugo-put :all-yy nil)))
467 (let* ((new (not (gnugo-get :display-using-images)))
468 (act (if new 'display 'do-not-display)))
470 (setcar (symbol-plist yy) act))
471 (or (gnugo-get :all-yy)
473 (prog1 (mapcar (lambda (ent)
475 (yy (gnugo-yy (cdr k) (car k))))
476 (setplist yy `(not-yet ,(cdr ent)))
479 (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
481 (gnugo-put :w-imul (car imul))
482 (gnugo-put :h-imul (cdr imul)))))))
483 (setplist (gnugo-f 'ispc) (and new
484 ;; `(display (space :width 0))'
485 ;; works as well, for newer emacs
487 (gnugo-put :highlight-last-move-spec
490 (get (gnugo-yy (get-text-property p 'gnugo-yin)
491 (get-text-property p 'gnugo-yang)
495 (gnugo-get :default-highlight-last-move-spec)))
496 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
497 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
498 (mapc 'delete-overlay (cdar group))
499 (setcdr (car group) nil))
500 (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
501 (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
502 (gnugo-put :display-using-images new)))
504 (defun gnugo-toggle-grid ()
505 "Turn the grid around the board on or off."
507 (funcall (if (memq :nogrid buffer-invisibility-spec)
508 'remove-from-invisibility-spec
509 'add-to-invisibility-spec)
511 (save-excursion (gnugo-refresh)))
513 (defun gnugo-propertize-board-buffer ()
515 (insert (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
516 (let* ((grid-props (list 'invisible :nogrid
517 'font-lock-face gnugo-grid-face))
518 (%gpad (gnugo-f 'gpad))
519 (%gspc (gnugo-f 'gspc))
520 (%lpad (gnugo-f 'lpad))
521 (%rpad (gnugo-f 'rpad))
522 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
523 (size (gnugo-treeroot :SZ))
524 (size-string (number-to-string size)))
525 (goto-char (point-min))
526 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
527 (skip-chars-forward " ")
528 (put-text-property (1- (point)) (point) 'category %gpad)
529 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
531 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
532 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
533 (let* ((row (match-string-no-properties 1))
535 (other-edge (+ edge (* 2 size) -1))
536 (right-empty (+ other-edge (length row) 1))
537 (top-p (string= size-string row))
538 (bot-p (string= "1" row)))
539 (let* ((nL (- edge 1 (length size-string)))
541 (ov (make-overlay nL nR (current-buffer) t)))
542 (add-text-properties nL nR grid-props)
543 ;; We redundantly set `invisible' in the overlay to workaround
544 ;; a display bug whereby text *following* the overlaid text is
545 ;; displayed with the face of the overlaid text, but only when
546 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
547 ;; This has something to do w/ the bletcherous `before-string'.
548 (overlay-put ov 'invisible :nogrid)
549 (overlay-put ov 'category %lpad))
550 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
552 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
553 (truncate (- p edge) 2))
555 (yin (let ((A-p (= edge p))
556 (Z-p (= (1- other-edge) p)))
557 (cond ((and top-p A-p) 1)
566 (yang (gnugo-yang (char-after p))))
567 (add-text-properties p (1+ p)
577 (gnugo-position gnugo-yin))))
578 (unless (= (1- other-edge) p)
579 (add-text-properties (1+ p) (+ 2 p) ispc-props)
580 (put-text-property p (+ 2 p) 'intangible ival)))
581 (add-text-properties (1+ other-edge) right-empty grid-props)
582 (goto-char right-empty)
583 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
584 (let ((prop (if (string= "WH" (match-string 1))
587 (beg (match-beginning 2))
589 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
590 (gnugo-put prop (match-string-no-properties 2))))
592 (put-text-property right-empty (point) 'category %rpad)
594 (add-text-properties (1- (point)) (point-max) grid-props)
595 (skip-chars-forward " ")
596 (put-text-property (1- (point)) (point) 'category %gpad)
597 (put-text-property (point) (progn (end-of-line) (point))
600 (defun gnugo-merge-showboard-results ()
601 (let ((aft (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
602 (adj 1) ; string to buffer position adjustment
603 (sync "[0-9]+ stones$")
604 (bef (buffer-substring-no-properties (point-min) (point-max)))
605 (bef-start 0) (bef-idx 0)
606 (aft-start 0) (aft-idx 0)
607 aft-sync-backtrack mis inc cut new very-strange)
608 (while (numberp (setq mis (compare-strings bef bef-start nil
610 (setq aft-sync-backtrack nil
614 bef-idx (+ bef-start inc)
615 aft-idx (+ aft-start inc)
616 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
619 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
620 (let ((peek (1- aft-idx)))
621 (while (not (= 32 (aref aft peek)))
622 (setq peek (1- peek)))
623 (setq aft-sync-backtrack (1+ peek))))
627 (if aft-sync-backtrack
628 (- aft-sync-backtrack aft-idx)
631 (if aft-sync-backtrack
632 (let* ((asb aft-sync-backtrack)
633 (l-p (get-text-property cut :gnugo-cf))
636 (keep (text-properties-at cut)))
637 (setq new (substring aft asb (string-match " " aft asb)))
638 (plist-put keep :gnugo-cf (cons (length new) capprop))
639 (gnugo-put capprop new)
640 (delete-char old-len)
641 (insert (apply 'propertize new keep))
642 (setq adj (+ adj (- (length new) old-len))))
643 (setq new (aref aft aft-idx))
644 (insert-and-inherit (char-to-string new))
645 (let ((yin (get-text-property cut 'gnugo-yin))
646 (yang (gnugo-yang new)))
647 (add-text-properties cut (1+ cut)
651 ,(gnugo-yy yin yang))))
653 ;; do this last to avoid complications w/ font lock
654 ;; (this also means we cannot include `intangible' in `front-sticky')
655 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
656 (put-text-property cut (1+ cut) 'intangible very-strange))))))
658 (defun gnugo-move-history (&optional rsel)
659 "Determine and return the game's move history.
660 Optional arg RSEL controls side effects and return value.
661 If nil, display the history in the echo area as \"(N moves)\"
662 followed by the space-separated list of moves. When called
663 interactively with a prefix arg (i.e., RSEL is `(4)'), display
664 similarly, but suffix with the mover (either \":B\" or \":W\").
665 If RSEL is the symbol `car' return the most-recent move; if
666 `cadr', the next-to-most-recent move; if `count' the number of
669 For all other values of RSEL, do nothing and return nil."
671 (let ((size (gnugo-treeroot :SZ))
673 (mem (aref (gnugo-get :monkey) 1))
676 ((as-pos (cc) (if (string= "tt" cc)
678 (setq col (aref cc 0))
680 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
681 (- size (- (aref cc 1) ?a)))))
682 (next (byp) (when (setq node (caar mem)
683 mprop (or (assq :B node)
685 (setq move (as-pos (cdr mprop))
688 (format "%s%s" move (car mprop))
691 (tell () (message "(%d moves) %s"
693 (mapconcat 'identity (nreverse acc) " "))))
695 ((not rsel) (while (next nil)) (tell))
696 ((equal '(4) rsel) (while (next t)) (tell))
697 ((eq 'car rsel) (car (next nil)))
698 ((eq 'cadr rsel) (next nil) (car (next nil)))
699 ((eq 'count rsel) (aref (gnugo-get :monkey) 2))))))
701 (defun gnugo-note (property value &optional movep mogrifyp)
703 (let ((sz (gnugo-treeroot :SZ)))
705 ((mog (pos) (if (string= "PASS" pos)
707 (let* ((col (aref pos 0))
708 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
709 (two (+ ?a (- sz (string-to-number
710 (substring pos 1))))))
711 (format "%c%c" one two)))))
712 (setq value (if (consp value)
715 (let* ((fruit (list (cons property value)))
716 (monkey (gnugo-get :monkey))
717 (loc (aref monkey 0)))
719 (let ((mem (aref monkey 1)))
720 ;; todo: do variation check/merge/branch here.
721 (setcdr loc (list fruit))
722 (aset monkey 0 (setq loc (cdr loc)))
723 (aset monkey 1 (cons loc mem))
724 (aset monkey 2 (1+ (aref monkey 2))))
725 (setcdr (last (car loc)) fruit))))
727 (defun gnugo-close-game (end-time resign)
728 (gnugo-put :game-end-time end-time)
729 (let ((now (or end-time (current-time))))
730 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
732 (gnugo-put :game-over
733 (if (or (eq t resign)
734 (and (stringp resign)
735 (string-match "[BW][+][Rr]esign" resign)))
742 (gnugo-query "worm_stones %s" color)
744 (let ((live (append (ls "black") (ls "white"))))
747 (let ((dd (gnugo-query "dragon_data"))
748 (start 0) mem color ent live dead)
749 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
751 (setq mem (match-string 1 dd)
752 color (match-string 2 dd)
754 ent (cons (list color)
755 (sort (gnugo-lsquery "dragon_stones %s" mem)
757 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
759 (if (match-string 2 dd)
762 (setq start (match-end 0)))
766 (defun gnugo-push-move (userp move)
767 (let* ((color (gnugo-get (if userp :user-color :gnugo-color)))
768 (start (gnugo-get :waiting-start))
770 (resignp (string= "resign" move))
771 (passp (string= "PASS" move))
772 (head (gnugo-move-history 'car))
773 (onep (and head (string= "PASS" head)))
774 (donep (or resignp (and onep passp))))
776 (gnugo-merge-showboard-results))
777 (gnugo-put :last-mover color)
779 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
780 (gnugo-note (if (string= "black" color) :B :W) move t (not resignp))
782 (gnugo-note :EV "resignation"))
784 (gnugo-put :last-waiting (cadr (time-subtract now start))))
786 (gnugo-close-game now resignp))
787 (gnugo-put :waiting-start (and (not donep) now))
790 (defun gnugo-venerate (yin yang)
791 (let* ((fg-yy (gnugo-yy yin yang))
792 (fg-disp (or (get fg-yy 'display)
793 (get fg-yy 'do-not-display)))
794 (fg-data (plist-get (cdr fg-disp) :data))
795 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
796 (bg-disp (or (get bg-yy 'display)
797 (get bg-yy 'do-not-display)))
798 (bg-data (plist-get (cdr bg-disp) :data))
802 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
803 (setq start (match-end 0))
804 (string-to-number (match-string 1 s)))))
805 (while (and (<= 0 ncolors) (string-match ",\n" s start))
806 (setq start (match-end 0)
807 ncolors (1- ncolors)))
808 (string-match "\"" s start)
810 (new (copy-sequence fg-data))
811 (lx (length fg-data))
812 (lb (length bg-data))
813 (sx (funcall bop fg-data))
814 (sb (funcall bop bg-data))
815 (color-key (aref new sx))) ; blech, heuristic
817 (when (and (not (= color-key (aref new sx)))
819 (aset new sx (aref bg-data sb)))
822 (create-image new 'xpm t :ascent 'center)))
824 (defun gnugo-refresh (&optional nocache)
825 "Update GNUGO Board buffer display.
826 While a game is in progress, parenthesize the last-played stone (no parens
827 for pass). If the buffer is currently displayed in the selected window,
828 recenter the board (presuming there is extra space in the window). Update
829 the mode line. Lastly, move point to the last position played by the user,
830 if that move was not a pass.
832 Prefix arg NOCACHE requests complete reconstruction of the display, which may
833 be slow. (This should normally be unnecessary; specify it only if the display
834 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
837 (when (and nocache (not (gnugo-get :waitingp)))
838 (gnugo-propertize-board-buffer))
839 (let* ((last-mover (gnugo-get :last-mover))
840 (other (gnugo-other last-mover))
841 (move (gnugo-move-history 'car))
842 (game-over (gnugo-get :game-over))
846 (let ((l-ov (gnugo-get :lparen-ov))
847 (r-ov (gnugo-get :rparen-ov)))
848 (if (member move '("PASS" "resign"))
849 (mapc 'delete-overlay (list l-ov r-ov))
850 (gnugo-goto-pos move)
852 (hspec (gnugo-get :highlight-last-move-spec))
853 (display-value (nth 0 hspec))
854 (l-offset (nth 1 hspec))
855 (l-new-pos (+ p l-offset))
856 (r-action (nth 2 hspec)))
857 (overlay-put l-ov 'display
858 (if (functionp display-value)
859 (funcall display-value p)
861 (move-overlay l-ov l-new-pos (1+ l-new-pos))
863 (funcall r-action r-ov)
864 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
866 (rename-buffer (concat (gnugo-get :diamond)
868 (format "%s(game over)"
869 (if (string= move "resign")
870 (concat move "ation ")
872 (format "%s(%s to play)"
873 (if move (concat move " ") "")
877 (let ((live (cdr (assq 'live game-over)))
878 (dead (cdr (assq 'dead game-over)))
880 (unless (eq game-over (get-text-property 1 'game-over))
881 (dolist (group (append live dead))
882 (dolist (pos (cdr group))
885 (put-text-property p (1+ p) 'group group)))
886 (put-text-property 1 2 'game-over game-over))
888 (when (setq pall (cdar group))
889 (mapc 'delete-overlay pall)
890 (setcdr (car group) nil)))
893 (let (ov pall c (color (caar group)))
894 (setq c (if (string= "black" color) "x" "o"))
895 (dolist (pos (cdr group))
897 (setq p (point) ov (make-overlay p (1+ p)))
900 (if (gnugo-get :display-using-images)
901 ;; respect the dead individually; it takes more time
902 ;; but that's not a problem (for them)
903 (gnugo-venerate (get-text-property p 'gnugo-yin)
904 (gnugo-yang (aref (upcase c) 0)))
905 (propertize c 'face 'font-lock-warning-face)))
907 (setcdr (car group) pall))))))
909 (when (setq window (get-buffer-window (current-buffer)))
910 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
911 (size (gnugo-treeroot :SZ))
912 (under10p (< size 10))
913 (h (- (truncate (- (window-height window)
914 (* size (gnugo-get :hmul))
918 (edges (window-edges window))
919 (right-w-edge (nth 2 edges))
920 (avail-width (- right-w-edge (nth 0 edges)))
921 (wmul (gnugo-get :wmul))
922 (imagesp (symbol-plist (gnugo-f 'ispc)))
928 2 ; between board and grid
933 (dolist (pair `((tpad . ,(if (and h (< 0 h))
934 `(display ,(make-string h 10))
935 '(invisible :nogrid)))
940 (cond (imagesp (+ (* 0.5 wmul)
946 (gspc . ,(when imagesp
947 `(display (space-width ,(- wmul 1.0)))))
948 (lpad . ,(let ((d `(display (space :align-to ,w))))
949 ;; We distinguish between these cases to
950 ;; workaround a display bug whereby the
951 ;; `before-string' is omitted entirely (not
952 ;; rendered) when interacting w/ the text
953 ;; mode last-move left-paren for moves in
957 ,(apply 'propertize " " d))
960 (space :align-to ,(1- avail-width))))))
961 (setplist (gnugo-f (car pair)) (cdr pair)))))
963 (let ((cur (gnugo-get :mode-line)))
964 (unless (equal cur gnugo-mode-line)
965 (setq cur gnugo-mode-line)
966 (gnugo-put :mode-line cur)
967 (gnugo-put :mode-line-form
969 (setq cur (copy-sequence cur))
971 (while (setq cut (string-match "~[bwpmtu]" cur))
973 (setq cut (1+ cut) c (aref cur cut))
976 `(,(intern (format "squig-%c" c))
978 (?b '(or (gnugo-get :black-captures) 0))
979 (?w '(or (gnugo-get :white-captures) 0))
980 (?p '(gnugo-other (gnugo-get :last-mover)))
981 (?t '(let ((ws (gnugo-get :waiting-start)))
983 (cadr (time-since ws))
985 (?u '(or (gnugo-get :last-waiting) "-"))
986 (?m '(gnugo-move-history 'count))))
988 `(let ,(delete-dups (copy-sequence acc))
989 (format ,cur ,@(reverse (mapcar 'car acc))))))
991 (let ((form (gnugo-get :mode-line-form)))
992 (setq mode-line-process
994 ;; this dynamicism is nice but excessive in its wantonness
995 ;;- `(" [" (:eval ,form) "]")
996 ;; this dynamicism is ok because the user triggers it
997 (list (format " [%s]" (eval form))))))
998 (force-mode-line-update))
1000 (when (setq last (gnugo-get :last-user-bpos))
1001 (gnugo-goto-pos last))))
1003 ;;;---------------------------------------------------------------------------
1004 ;;; Game play actions
1006 (defun gnugo-get-move-insertion-filter (proc string)
1007 (with-current-buffer (process-buffer proc)
1008 (let* ((so-far (gnugo-get :get-move-string))
1009 (full (gnugo-put :get-move-string (concat so-far string))))
1010 (when (string-match "^= \\(.+\\)\n\n" full)
1011 (let ((pos-or-pass (match-string 1 full)))
1012 (gnugo-put :get-move-string nil)
1013 (gnugo-put :waitingp nil)
1014 (gnugo-push-move nil pos-or-pass)
1015 (let ((buf (current-buffer)))
1016 (let (inhibit-gnugo-refresh)
1017 (run-hooks 'gnugo-post-move-hook)
1018 (unless inhibit-gnugo-refresh
1019 (with-current-buffer buf
1020 (gnugo-refresh))))))))))
1022 (defun gnugo-get-move (color)
1023 (gnugo-put :waitingp t)
1024 (set-process-filter (gnugo-get :proc) 'gnugo-get-move-insertion-filter)
1025 (gnugo-send-line (concat "genmove " color))
1026 (accept-process-output))
1028 (defun gnugo-cleanup ()
1029 (when (gnugo-board-buffer-p)
1030 (unless (= 0 (buffer-size))
1031 (message "Thank you for playing GNU Go."))
1033 (setplist sym nil) ; "...is next to fordliness." --Huxley
1035 (append (gnugo-get :all-yy)
1044 (setq gnugo-state nil)))
1046 (defun gnugo-position ()
1047 (or (get-text-property (point) 'gnugo-position)
1048 (error "Not a proper position point")))
1050 (defun gnugo-move ()
1051 "Make a move on the GNUGO Board buffer.
1052 The position is computed from current point.
1053 Signal error if done out-of-turn or if game-over.
1054 To start a game try M-x gnugo."
1057 (let* ((buf (current-buffer))
1058 (pos (gnugo-position))
1059 (move (format "play %s %s" (gnugo-get :user-color) pos))
1060 (accept (cdr (gnugo-synchronous-send/return move))))
1061 (unless (= ?= (aref accept 0))
1062 (error "%s" accept))
1063 (gnugo-push-move t pos) ; value always nil for non-pass move
1064 (let (inhibit-gnugo-refresh)
1065 (run-hooks 'gnugo-post-move-hook)
1066 (unless inhibit-gnugo-refresh
1067 (with-current-buffer buf
1069 (with-current-buffer buf
1070 (gnugo-get-move (gnugo-get :gnugo-color)))))
1072 (defun gnugo-mouse-move (e)
1073 "Do `gnugo-move' at mouse location."
1076 (when (looking-at "[.+]")
1079 (defun gnugo-pass ()
1080 "Make a pass on the GNUGO Board buffer.
1081 Signal error if done out-of-turn or if game-over.
1082 To start a game try M-x gnugo."
1085 (let ((accept (cdr (gnugo-synchronous-send/return
1086 (format "play %s PASS" (gnugo-get :user-color))))))
1087 (unless (= ?= (aref accept 0))
1088 (error "%s" accept)))
1089 (let ((donep (gnugo-push-move t "PASS"))
1090 (buf (current-buffer)))
1091 (let (inhibit-gnugo-refresh)
1092 (run-hooks 'gnugo-post-move-hook)
1093 (unless inhibit-gnugo-refresh
1094 (with-current-buffer buf
1097 (with-current-buffer buf
1098 (gnugo-get-move (gnugo-get :gnugo-color))))))
1100 (defun gnugo-mouse-pass (e)
1101 "Do `gnugo-pass' at mouse location."
1106 (defun gnugo-resign ()
1109 (if (not (y-or-n-p "Resign? "))
1110 (message "(not resigning)")
1111 (gnugo-push-move t "resign")
1114 (defun gnugo-animate-group (command)
1115 (message "Computing %s ..." command)
1116 (let* ((pos (gnugo-position))
1117 (stones (if (memq (char-after) '(?X ?O))
1118 (gnugo-lsquery "%s %s" command pos)
1119 (error "No stone at %s" pos))))
1120 (message "Computing %s ... %s in group." command (length stones))
1121 (setplist (gnugo-f 'anim) nil)
1122 (let* ((spec (let ((spec
1123 ;; `(split-string gnugo-animation-string "" t)'
1124 ;; works as well, for newer emacs versions
1125 (delete "" (split-string gnugo-animation-string ""))))
1126 (cond ((gnugo-get :display-using-images)
1127 (let* ((yin (get-text-property (point) 'gnugo-yin))
1128 (yang (gnugo-yang (char-after)))
1129 (up (get (gnugo-yy yin yang t) 'display))
1130 (dn (get (gnugo-yy yin yang) 'display))
1133 (if (setq flip-flop (not flip-flop))
1135 (mapcar 'string-to-char spec))))
1138 (ovs (save-excursion
1139 (mapcar (lambda (pos)
1140 (gnugo-goto-pos pos)
1142 (ov (make-overlay p (1+ p))))
1143 (overlay-put ov 'category (gnugo-f 'anim))
1144 (overlay-put ov 'priority most-positive-fixnum)
1147 (setplist (gnugo-f 'anim) (cons 'display cell))
1148 (while (and (cdr spec) ; let last linger lest levity lost
1149 (sit-for 0.08675309)) ; jenny jenny i got your number...
1150 (setcar cell (setq spec (cdr spec)))
1151 (set-buffer-modified-p t))
1153 (mapc 'delete-overlay ovs)
1156 (defun gnugo-display-group-data (command buffer-name)
1157 (message "Computing %s ..." command)
1158 (let ((data (cdr (gnugo-synchronous-send/return
1159 (format "%s %s" command (gnugo-position))))))
1160 (switch-to-buffer buffer-name)
1163 (message "Computing %s ... done." command))
1165 (defun gnugo-worm-stones ()
1166 "In the GNUGO Board buffer, animate \"worm\" at current position.
1167 Signal error if done out-of-turn or if game-over.
1168 See variable `gnugo-animation-string' for customization."
1171 (gnugo-animate-group "worm_stones"))
1173 (defun gnugo-worm-data ()
1174 "Display in another buffer data from \"worm\" at current position.
1175 Signal error if done out-of-turn or if game-over."
1178 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1180 (defun gnugo-dragon-stones ()
1181 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1182 Signal error if done out-of-turn or if game-over.
1183 See variable `gnugo-animation-string' for customization."
1186 (gnugo-animate-group "dragon_stones"))
1188 (defun gnugo-dragon-data ()
1189 "Display in another buffer data from \"dragon\" at current position.
1190 Signal error if done out-of-turn or if game-over."
1193 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1195 (defun gnugo-toggle-dead-group ()
1196 "In a GNUGO Board buffer, during game-over, toggle a group as dead.
1197 The group is selected from current position (point). Signal error if
1198 not in game-over or if there is no group at that position.
1200 In the context of GNU Go, a group is called a \"dragon\" and may be
1201 composed of more than one \"worm\" (set of directly-connected stones).
1202 It is unclear to the gnugo.el author whether or not GNU Go supports
1203 - considering worms as groups in their own right; and
1204 - toggling group aliveness via GTP.
1205 Due to these uncertainties, this command is only half complete; the
1206 changes you may see in Emacs are not propagated to the gnugo subprocess.
1207 Thus, GTP commands like `final_score' may give unexpected results.
1209 If you are able to expose via GTP `change_dragon_status' in utils.c,
1210 you may consider modifying the `gnugo-toggle-dead-group' source code
1211 to enable full functionality."
1213 (let ((game-over (or (gnugo-get :game-over)
1214 (error "Sorry, game still in play")))
1215 (group (or (get-text-property (point) 'group)
1216 (error "No stone at that position")))
1217 (now (current-time)))
1218 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1220 (let ((live (assq 'live game-over))
1221 (dead (assq 'dead game-over))
1223 (if (memq group live)
1224 (setq bef live now dead)
1225 (setq bef dead now live))
1226 (setcdr bef (delq group (cdr bef)))
1227 (setcdr now (cons group (cdr now)))
1228 ;; disabled permanently -- too wrong
1232 (let ((color (caar group)))
1233 (dolist (stone (cdr group))
1234 (gnugo-query "play %s %s" color stone)))))
1237 ;; drastic (and wrong -- clobbers capture info, etc)
1238 (gnugo-query "clear_board")
1239 (mapc #'populate (cdr live)))))
1240 ;; here is the desired interface (to be enabled Some Day)
1242 (gnugo-query "change_dragon_status %s %s"
1243 (cadr group) (if (eq now live)
1249 (defun gnugo-estimate-score ()
1250 "Display estimated score of a game of GNU Go.
1251 Output includes number of stones on the board and number of stones
1252 captured by each player, and the estimate of who has the advantage (and
1253 by how many stones)."
1255 (message "Est.score ...")
1256 (let ((black (length (gnugo-lsquery "list_stones black")))
1257 (white (length (gnugo-lsquery "list_stones white")))
1258 (black-captures (gnugo-query "captures black"))
1259 (white-captures (gnugo-query "captures white"))
1260 (est (gnugo-query "estimate_score")))
1261 ;; might as well update this
1262 (gnugo-put :black-captures black-captures)
1263 (gnugo-put :white-captures white-captures)
1264 (message "Est.score ... B %s %s | W %s %s | %s"
1265 black black-captures white white-captures est)))
1267 (defun gnugo-write-sgf-file (filename)
1268 "Save the game history to FILENAME (even if unfinished).
1269 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1270 (interactive "FWrite game as SGF file: ")
1271 (when (and (file-exists-p filename)
1272 (not (y-or-n-p "File exists. Continue? ")))
1273 (error "Not writing %s" filename))
1274 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename))
1276 (defun gnugo-read-sgf-file (filename)
1277 "Load the first game tree from FILENAME, a file in SGF format."
1278 (interactive "fSGF file to load: ")
1279 (when (file-directory-p filename)
1280 (error "Cannot load a directory (try a filename with extension .sgf)"))
1281 (let (ans play wait samep coll)
1282 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1283 ;; todo: skip it altogether when confident about `gnugo/sgf-read-file'
1284 (unless (= ?= (aref (setq ans (cdr (gnugo-synchronous-send/return
1285 (format "loadsgf %s"
1286 (expand-file-name filename)))))
1289 (setq play (substring ans 2)
1290 wait (gnugo-other play)
1291 samep (string= (gnugo-get :user-color) play))
1292 (gnugo-put :last-mover wait)
1294 (gnugo-put :gnugo-color wait)
1295 (gnugo-put :user-color play))
1296 (gnugo-put :sgf-collection (setq coll (gnugo/sgf-read-file filename)))
1297 (gnugo-put :sgf-gametree
1298 (nth (let ((n (length coll)))
1302 ;; (let* ((q (format "Which game? (1-%d)" n))
1303 ;; (choice (1- (read-number q 1))))
1304 ;; (if (and (< -1 choice) (< choice n))
1306 ;; (message "(Selecting the first game)")
1308 ;; but this is what we use (for now) to accomodate
1309 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1311 (message "(Selecting the first game)"))
1314 (let* ((tree (gnugo-get :sgf-gametree))
1317 mem node play game-over)
1318 (while (setq node (car loc))
1319 (when (setq play (or (assq :B node)
1321 ;; SGF[4] allows "" to mean PASS. For now,
1322 ;; we normalize here instead of at the lower layer.
1323 (when (string= "" (cdr play))
1327 (setq loc (cdr loc)))
1328 (gnugo-put :game-over
1330 (or (cdr (assq :RE (car tree)))
1333 (let ((order (if (string= "black" wait)
1336 (mapcar (lambda (pk)
1337 (cdr (assq (funcall pk order)
1338 (car (funcall pk mem)))))
1342 (vector (or (car mem) (gnugo-get :sgf-gametree))
1345 (when (and game-over
1346 ;; (maybe) todo: user var to inhibit (can be slow)
1348 (gnugo-close-game nil game-over)))
1350 (message "GNU Go %splays as %s, you as %s (%s)"
1351 (if samep "" "now ")
1354 "NOTE: this is a switch!"))))
1356 (defun gnugo-magic-undo (spec &optional noalt)
1357 "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1358 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1359 check that the position is occupied by a stone of the user's color,
1360 and if so, remove moves from the history until that position is clear.
1361 If SPEC is a positive number, remove exactly that many moves from the
1362 history, signaling an error if the history is exhausted before finishing.
1363 If SPEC is not recognized, signal \"bad spec\" error.
1365 Refresh the board for each move undone. If (in the case where SPEC is
1366 a number) after finishing, the color to play is not the user's color,
1367 schedule a move by GNU Go.
1369 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1370 turn to play. Optional second arg NOALT non-nil inhibits this."
1373 (monkey (gnugo-get :monkey))
1374 (mem (aref monkey 1))
1375 (count (aref monkey 2))
1377 (cond ((and (numberp spec) (< 0 spec))
1378 (setq n spec done (lambda () (= 0 n))))
1379 ((string-match "^[a-z]" spec)
1380 (let ((pos (upcase spec)))
1381 (setq done `(lambda ()
1382 (gnugo-goto-pos ,pos)
1383 (memq (char-after) '(?. ?+))))
1384 (when (funcall done)
1385 (error "%s already clear" pos))
1386 (let ((u (gnugo-get :user-color)))
1387 (when (= (save-excursion
1388 (gnugo-goto-pos pos)
1390 (if (string= "black" u)
1393 (error "%s not occupied by %s" pos u)))))
1394 (t (error "Bad spec: %S" spec)))
1395 (when (gnugo-get :game-over)
1396 (gnugo-put :game-over nil))
1397 (while (not (funcall done))
1398 (setq ans (cdr (gnugo-synchronous-send/return "undo")))
1399 (unless (= ?= (aref ans 0))
1401 (aset monkey 2 (decf count))
1402 (aset monkey 1 (setq mem (cdr mem)))
1403 (aset monkey 0 (or (car mem) (gnugo-get :sgf-gametree)))
1404 (gnugo-put :last-mover (gnugo-other (gnugo-get :last-mover)))
1405 (gnugo-merge-showboard-results) ; all
1406 (gnugo-refresh) ; this
1408 (sit-for 0))) ; eye candy
1409 (let* ((ulastp (string= (gnugo-get :last-mover) (gnugo-get :user-color)))
1411 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1412 (gnugo-put :last-user-bpos (if (and ubpos (not (string= "PASS" ubpos)))
1414 (gnugo-get :center-position)))
1416 ;; preserve restricted-functionality semantics (todo: remove restriction)
1417 (setcdr (aref (gnugo-get :monkey) 0) nil)
1418 (when (and ulastp (not noalt))
1419 (gnugo-get-move (gnugo-get :gnugo-color)))))
1421 (defun gnugo-undo-one-move ()
1422 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1423 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1424 See also `gnugo-undo-two-moves'."
1427 (gnugo-magic-undo 1 t))
1429 (defun gnugo-undo-two-moves ()
1430 "Undo a pair of moves (GNU Go's and yours).
1431 However, if you are the last mover, undo only one move.
1432 Regardless, after undoing, it is your turn to play again."
1435 (gnugo-magic-undo (if (string= (gnugo-get :user-color)
1436 (gnugo-get :last-mover))
1440 (defun gnugo-display-final-score ()
1441 "Display final score and other info in another buffer (when game over).
1442 If the game is still ongoing, Emacs asks if you wish to stop play (by
1443 making sure two \"pass\" moves are played consecutively, if necessary).
1444 Also, add the `:RE' SGF property to the root node of the game tree."
1446 (unless (or (gnugo-get :game-over)
1447 (and (not (gnugo-get :waitingp))
1448 (y-or-n-p "Game still in play. Stop play now? ")))
1449 (error "Sorry, game still in play"))
1450 (unless (gnugo-get :game-over)
1453 (message "Playing PASS for %s ..."
1454 (gnugo-get (if userp :user-color :gnugo-color)))
1456 (gnugo-push-move userp "PASS")))
1461 (let ((b= " Black = ")
1463 (res (let* ((node (car (aref (gnugo-get :monkey) 0)))
1464 (event (and node (cdr (assq :EV node)))))
1465 (and event (string= "resignation" event)
1466 (if (assq :B node) "black" "white"))))
1470 (format "%s wins.\n"
1471 (substring (if (= ?b (aref res 0)) w= b=)
1473 "The game is over.\n"
1474 (format "Resignation by %s.\n" res))
1475 result (concat (upcase (substring (gnugo-other res) 0 1))
1477 (message "Computing final score ...")
1478 (let* ((live (cdr (assq 'live (gnugo-get :game-over))))
1479 (dead (cdr (assq 'dead (gnugo-get :game-over))))
1480 (seed (gnugo-get :scoring-seed))
1481 (terr-q (format "final_status_list %%s_territory %d" seed))
1484 (b-terr (length (gnugo-lsquery terr-q "black")))
1485 (w-terr (length (gnugo-lsquery terr-q "white")))
1486 (b-capt (string-to-number (gnugo-get :black-captures)))
1487 (w-capt (string-to-number (gnugo-get :white-captures)))
1488 (komi (gnugo-treeroot :KM)))
1489 (setq blurb (list "The game is over. Final score:\n")
1490 result (gnugo-query "final_score %d" seed))
1491 (cond ((string= "Chinese" (gnugo-treeroot :RU))
1492 (dolist (group live)
1493 (let ((count (length (cdr group))))
1494 (if (string= "black" (caar group))
1495 (setq b-terr (+ b-terr count))
1496 (setq w-terr (+ w-terr count)))))
1497 (dolist (group dead)
1498 (let* ((color (caar group))
1499 (count (length (cdr group))))
1500 (if (string= "black" color)
1501 (setq w-terr (+ count w-terr))
1502 (setq b-terr (+ count b-terr)))))
1503 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1504 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1505 w-terr terr komi 'komi (+ w-terr komi))
1508 (dolist (group dead)
1509 (let* ((color (caar group))
1510 (adjust (* 2 (length (cdr group)))))
1511 (if (string= "black" color)
1512 (setq w-terr (+ adjust w-terr))
1513 (setq b-terr (+ adjust b-terr)))))
1514 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1519 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1523 (+ w-terr w-capt komi))
1525 (push (if (string= "0" result)
1526 "The game is a draw.\n"
1527 (format "%s wins by %s.\n"
1528 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1529 (substring result 2)))
1531 (message "Computing final score ... done")))
1533 (when (gnugo-get :game-end-time)
1535 (dolist (spec '(("Game start" . :game-start-time)
1536 (" end" . :game-end-time)))
1537 (push (format-time-string
1538 (concat (car spec) ": %Y-%m-%d %H:%M:%S %z\n")
1539 (gnugo-get (cdr spec)))
1541 (setq blurb (apply 'concat (nreverse blurb)))
1542 (let* ((root (car (gnugo-get :sgf-gametree)))
1543 (cur (assq :RE root)))
1546 (setcdr (last root) (list (cons :RE result)))))
1547 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
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-hook -- normal hook 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))
1595 (funcall full (cdr split))
1596 (message "Doing %s ..." command)
1597 (let* ((ans (cdr (gnugo-synchronous-send/return command)))
1598 (where (plist-get spec :output)))
1599 (if (string-match "unknown.command" ans)
1601 (cond ((functionp where) (funcall where ans))
1602 ((eq :discard where) (message ""))
1603 ((or (eq :message where)
1604 (not (string-match "\n" ans)))
1606 (t (switch-to-buffer "*gnugo command output*")
1609 (message "Doing %s ... done." command)))
1611 ;; do not elide this binding; `run-hooks' needs it
1612 (plist-get spec :post-hook)))
1613 (run-hooks 'hook))))))))
1615 ;;;---------------------------------------------------------------------------
1616 ;;; Major mode for interacting with a GNUGO subprocess
1618 (put 'gnugo-board-mode 'mode-class 'special)
1619 (defun gnugo-board-mode ()
1620 "Major mode for playing GNU Go.
1621 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
1622 In this mode, keys do not self insert. Default keybindings:
1626 RET or SPC Run `gnugo-move'.
1628 q or Q Quit (the latter without confirmation).
1632 u Run `gnugo-undo-two-moves'.
1634 U Pass to `gnugo-magic-undo' either the board position
1635 at point (if no prefix arg), or the prefix arg converted
1636 to a number. E.g., to undo 16 moves: `C-u C-u U' (see
1637 `universal-argument'); to undo 42 moves: `M-4 M-2 U'.
1639 C-l Run `gnugo-refresh'.
1641 _ or M-_ Bury the Board buffer (when the boss is near).
1645 i Toggle display using XPM images (if supported).
1647 w Run `gnugo-worm-stones'.
1648 d Run `gnugo-dragon-stones'.
1650 W Run `gnugo-worm-data'.
1651 D Run `gnugo-dragon-data'.
1653 t Run `gnugo-toggle-dead-group'.
1655 ! Run `gnugo-estimate-score'.
1657 : or ; Run `gnugo-command' (for GTP commands to GNU Go).
1659 = Display board position under point (if valid).
1661 h Run `gnugo-move-history'.
1663 F Run `gnugo-display-final-score'.
1665 s Run `gnugo-write-sgf-file'.
1669 l Run `gnugo-read-sgf-file'."
1670 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
1671 (buffer-disable-undo) ; todo: undo undo undoing
1672 (kill-all-local-variables)
1673 (setq truncate-lines t)
1674 (use-local-map gnugo-board-mode-map)
1675 (set (make-local-variable 'font-lock-defaults)
1676 '(gnugo-font-lock-keywords t))
1677 (setq major-mode 'gnugo-board-mode)
1678 (setq mode-name "GNUGO Board")
1679 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
1680 (set (make-local-variable 'gnugo-state)
1681 (make-hash-table :size (1- 42) :test 'eq))
1682 (add-to-invisibility-spec :nogrid)
1683 (mapc (lambda (prop)
1684 (gnugo-put prop nil)) ; todo: separate display/game aspects;
1685 '(:game-over ; move latter to func `gnugo'
1692 :display-using-images
1696 (let ((name (if (string-match "[ ]" gnugo-program)
1697 (let ((p (substring gnugo-program 0 (match-beginning 0)))
1698 (o (substring gnugo-program (match-end 0)))
1699 (h (or (car gnugo-option-history) "")))
1700 (when (string-match "--mode" o)
1701 (error "Found \"--mode\" in `gnugo-program'"))
1702 (when (and o (< 0 (length o))
1704 (or (< (length h) (length o))
1705 (not (string= (substring h 0 (length o))
1707 (push (concat o " " h) gnugo-option-history))
1710 (args (read-string "GNU Go options: "
1711 (car gnugo-option-history)
1712 'gnugo-option-history))
1714 board-size user-color handicap komi minus-l infile)
1716 (apply (lambda (var default opt &optional rx)
1718 (or (when (string-match opt args)
1719 (let ((start (match-end 0)) s)
1720 (string-match (or rx "[0-9.]+") args start)
1721 (setq s (match-string 0 args))
1722 (if rx s (string-to-number s))))
1725 '((board-size 19 "--boardsize")
1726 (user-color "black" "--color" "\\(black\\|white\\)")
1727 (handicap 0 "--handicap")
1729 (minus-l nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
1730 (infile nil "--infile" "[ ]*[^ ]+")))
1731 (gnugo-put :user-color user-color)
1732 (when (string-match "--chinese-rules" args)
1733 (setq rules "Chinese"))
1734 (let ((proc-args (split-string args)))
1735 (gnugo-put :proc-args proc-args)
1736 (gnugo-put :proc (apply 'start-process "gnugo" nil name
1737 "--mode" "gtp" "--quiet"
1739 (when (or minus-l infile)
1741 (apply (lambda (prop q)
1742 (set prop (string-to-number (gnugo-query q))))
1744 '((board-size "query_boardsize")
1746 (handicap "get_handicap"))))
1747 (gnugo-put :diamond (substring (process-name (gnugo-get :proc)) 5))
1748 (gnugo-put :gnugo-color (gnugo-other (gnugo-get :user-color)))
1749 (gnugo-put :highlight-last-move-spec
1750 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
1751 (gnugo-put :lparen-ov (make-overlay 1 1))
1752 (gnugo-put :rparen-ov (let ((ov (make-overlay 1 1)))
1753 (overlay-put ov 'display ")")
1755 (gnugo-put :sgf-gametree (list (list '(:FF . 4) '(:GM . 1))))
1756 (let ((tree (gnugo-get :sgf-gametree)))
1757 (gnugo-put :sgf-collection (list tree))
1758 (gnugo-put :monkey (vector tree nil 0)))
1759 (let ((g-blackp (string= "black" (gnugo-get :gnugo-color))))
1760 (mapc (lambda (x) (apply 'gnugo-note x))
1762 (:DT ,(format-time-string "%Y-%m-%d"))
1764 (:AP ("gnugo.el" . ,gnugo-version))
1766 (,(if g-blackp :PW :PB) ,(user-full-name))
1767 (,(if g-blackp :PB :PW) ,(concat "GNU Go "
1768 (gnugo-query "version")))
1769 ,@(when (not (= 0 handicap))
1771 (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
1773 (set-process-sentinel (gnugo-get :proc) 'gnugo-sentinel)
1774 (set-process-buffer (gnugo-get :proc) (current-buffer))
1775 (gnugo-put :waiting-start (current-time))
1778 (run-hooks 'gnugo-board-mode-hook)
1781 ;;;---------------------------------------------------------------------------
1785 (defun gnugo (&optional new-game)
1786 "Run gnugo in a buffer, or resume a game in progress.
1787 Prefix arg means skip the game-in-progress check and start a new
1790 You are queried for additional command-line options (Emacs supplies
1791 \"--mode gtp --quiet\" automatically). Here is a list of options
1792 that gnugo.el understands and handles specially:
1794 --boardsize num Set the board size to use (5--19)
1795 --color <color> Choose your color ('black' or 'white')
1796 --handicap <num> Set the number of handicap stones (0--9)
1798 If there is already a game in progress you may resume it instead of
1799 starting a new one. See `gnugo-board-mode' documentation for more info."
1801 (let* ((all (let (acc)
1802 (dolist (buf (buffer-list))
1803 (when (gnugo-board-buffer-p buf)
1804 (push (cons (buffer-name buf) buf) acc)))
1807 (if (and (not new-game)
1809 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
1810 (if (= 1 n) "" "s"))))
1815 (let ((sel (completing-read "Which one? " all nil t)))
1816 (if (string= "" sel)
1818 (assoc sel all))))))
1819 ;; set up a new board
1821 (let ((half (truncate (1+ (gnugo-treeroot :SZ)) 2)))
1822 (gnugo-goto-pos (format "A%d" half))
1823 (forward-char (* 2 (1- half)))
1824 (gnugo-put :last-user-bpos
1825 (gnugo-put :center-position
1826 (get-text-property (point) 'gnugo-position))))
1828 (gnugo-put :game-start-time (current-time))
1829 (let ((g (gnugo-get :gnugo-color))
1830 (n (or (gnugo-treeroot :HA) 0))
1831 (u (gnugo-get :user-color)))
1832 (gnugo-put :last-mover g)
1833 (when (or (and (string= "black" u) (< 1 n))
1834 (and (string= "black" g) (< n 2)))
1835 (gnugo-put :last-mover u)
1837 (gnugo-get-move g))))))
1839 ;;;---------------------------------------------------------------------------
1840 ;;; Load-time actions
1842 (unless gnugo-board-mode-map
1843 (setq gnugo-board-mode-map (make-sparse-keymap))
1844 (suppress-keymap gnugo-board-mode-map)
1845 (mapc (lambda (pair)
1846 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
1847 '(("?" . describe-mode)
1848 ("\C-m" . gnugo-move)
1851 ("R" . gnugo-resign)
1852 ("q" . (lambda () (interactive)
1853 (if (or (gnugo-get :game-over)
1854 (y-or-n-p "Quit? "))
1856 (message "(not quitting)"))))
1857 ("Q" . (lambda () (interactive)
1859 ("U" . (lambda (x) (interactive "P")
1861 (cond ((numberp x) x)
1863 (t (gnugo-position))))))
1864 ("u" . gnugo-undo-two-moves)
1865 ("\C-l" . gnugo-refresh)
1866 ("\M-_" . bury-buffer)
1868 ("h" . gnugo-move-history)
1869 ("i" . (lambda () (interactive)
1870 (gnugo-toggle-image-display)
1871 (save-excursion (gnugo-refresh))))
1872 ("w" . gnugo-worm-stones)
1873 ("W" . gnugo-worm-data)
1874 ("d" . gnugo-dragon-stones)
1875 ("D" . gnugo-dragon-data)
1876 ("t" . gnugo-toggle-dead-group)
1877 ("g" . gnugo-toggle-grid)
1878 ("!" . gnugo-estimate-score)
1879 (":" . gnugo-command)
1880 (";" . gnugo-command)
1881 ("=" . (lambda () (interactive)
1882 (message (gnugo-position))))
1883 ("s" . gnugo-write-sgf-file)
1884 ("\C-x\C-s" . gnugo-write-sgf-file)
1885 ("\C-x\C-w" . gnugo-write-sgf-file)
1886 ("l" . gnugo-read-sgf-file)
1887 ("F" . gnugo-display-final-score)
1889 ([(down-mouse-1)] . gnugo-mouse-move)
1890 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
1891 ([(down-mouse-3)] . gnugo-mouse-pass)
1892 ;; delving into the curiosities
1893 ("\C-c\C-p" . gnugo-describe-internal-properties))))
1895 (unless (get 'help :gnugo-gtp-command-spec)
1897 ((sget (x) (get x :gnugo-gtp-command-spec))
1898 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
1899 (plist-put (sget cmd) prop val)))
1900 (add (cmd prop val) (jam cmd prop (let ((cur (plist-get
1903 (append (delete val cur)
1905 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
1908 (funcall (if (eq :post-hook (car ls))
1911 cmd (car ls) (cadr ls))
1912 (setq ls (cddr ls)))))))
1916 (info "(gnugo)GTP command reference")
1917 (when sel (setq sel (intern (car sel))))
1918 (let (buffer-read-only pad cur spec output found)
1920 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
1921 (goto-char (point-min))
1923 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
1926 (setq pad (make-string (- (match-beginning 1)
1927 (match-beginning 0))
1931 (get (setq cur (intern (match-string 1)))
1932 :gnugo-gtp-command-spec))
1934 (note "handles this command completely"))
1935 (when (setq output (plist-get spec :output))
1936 (cond ((functionp output)
1937 (note "handles the output specially"))
1938 ((eq :discard output)
1939 (note "discards the output"))
1940 ((eq :message output)
1941 (note "displays the output in the echo area"))))
1943 (setq found (match-beginning 0))))))
1944 (cond (found (goto-char found))
1946 (t (message "(no such command: %s)" sel))))))
1948 (defgtp 'final_score :full
1949 (lambda (sel) (gnugo-display-final-score)))
1955 :post-hook (lambda ()
1956 (gnugo-put :game-over nil)
1957 (gnugo-put :last-mover nil)
1960 (defgtp 'loadsgf :full
1961 (lambda (sel) (gnugo-read-sgf-file (car sel))))
1963 (defgtp '(undo gg-undo) :full
1964 (lambda (sel) (gnugo-magic-undo
1967 ((< 0 (setq n (string-to-number (car sel)))) n)
1968 (t (car sel)))))))))
1973 ;;;---------------------------------------------------------------------------
1974 ;;; The remainder of this file defines a simplified SGF-handling library.
1975 ;;; When/if it should start to attain generality, it should be split off into
1976 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
1977 ;;; "gnugo/" prefix.
1979 (defconst gnugo/sgf-*r4-properties*
1980 '((AB "Add Black" setup list stone)
1981 (AE "Add Empty" game list point)
1982 (AN "Annotation" game simpletext)
1983 (AP "Application" root (simpletext . simpletext))
1984 (AR "Arrow" - list (point . point))
1985 (AS "Who adds stones" - simpletext) ; (LOA)
1986 (AW "Add White" setup list stone)
1987 (B "Black" move move)
1988 (BL "Black time left" move real)
1989 (BM "Bad move" move double)
1990 (BR "Black rank" game simpletext)
1991 (BT "Black team" game simpletext)
1992 (C "Comment" - text)
1993 (CA "Charset" root simpletext)
1994 (CP "Copyright" game simpletext)
1995 (CR "Circle" - list point)
1996 (DD "Dim points" - elist point) ; (inherit)
1997 (DM "Even position" - double)
1998 (DO "Doubtful" move none)
1999 (DT "Date" game simpletext)
2000 (EV "Event" game simpletext)
2001 (FF "Fileformat" root [number (1 . 4)])
2002 (FG "Figure" - (or none (number . simpletext)))
2003 (GB "Good for Black" - double)
2004 (GC "Game comment" game text)
2005 (GM "Game" root [number (1 . 20)])
2006 (GN "Game name" game simpletext)
2007 (GW "Good for White" - double)
2008 (HA "Handicap" game number) ; (Go)
2009 (HO "Hotspot" - double)
2010 (IP "Initial pos." game simpletext) ; (LOA)
2011 (IT "Interesting" move none)
2012 (IY "Invert Y-axis" game simpletext) ; (LOA)
2013 (KM "Komi" game real) ; (Go)
2015 (LB "Label" - list (point . simpletext))
2016 (LN "Line" - list (point . point))
2017 (MA "Mark" - list point)
2018 (MN "set move number" move number)
2019 (N "Nodename" - simpletext)
2020 (OB "OtStones Black" move number)
2021 (ON "Opening" game text)
2022 (OT "Overtime" game simpletext)
2023 (OW "OtStones White" move number)
2024 (PB "Player Black" game simpletext)
2025 (PC "Place" game simpletext)
2026 (PL "Player to play" setup color)
2027 (PM "Print move mode" - number) ; (inherit)
2028 (PW "Player White" game simpletext)
2029 (RE "Result" game simpletext)
2030 (RO "Round" game simpletext)
2031 (RU "Rules" game simpletext)
2032 (SE "Markup" - point) ; (LOA)
2033 (SL "Selected" - list point)
2034 (SO "Source" game simpletext)
2035 (SQ "Square" - list point)
2036 (ST "Style" root [number (0 . 3)])
2037 (SU "Setup type" game simpletext) ; (LOA)
2038 (SZ "Size" root (or number (number . number)))
2039 (TB "Territory Black" - elist point) ; (Go)
2040 (TE "Tesuji" move double)
2041 (TM "Timelimit" game real)
2042 (TR "Triangle" - list point)
2043 (TW "Territory White" - elist point) ; (Go)
2044 (UC "Unclear pos" - double)
2045 (US "User" game simpletext)
2047 (VW "View" - elist point) ; (inherit)
2048 (W "White" move move)
2049 (WL "White time left" move real)
2050 (WR "White rank" game simpletext)
2051 (WT "White team" game simpletext)
2052 (LT "Lose on time" setup simpletext))
2053 ;; r4-specific notes
2054 ;; - changed: DT FG LB RE RU SZ
2055 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2056 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2058 (defun gnugo/sgf-read-file (filename)
2059 "Return the collection (list) of gametrees in SGF[4] file FILENAME."
2060 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2061 (put 'gnugo/sgf-*r4-properties* :keywords
2062 (mapcar (lambda (full)
2064 (intern (format ":%s" (car full)))))
2065 gnugo/sgf-*r4-properties*))))
2066 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2067 (put 'gnugo/sgf-*r4-properties* :specs
2068 (mapcar (lambda (full)
2069 (cons (car full) (cdddr full)))
2070 gnugo/sgf-*r4-properties*)))))
2072 ((sw () (skip-chars-forward " \t\n"))
2073 (x (end) (let ((beg (point))
2075 (:end (lambda (char) (= ?\] char)))
2076 (:mid (lambda (char) (= ?\: char)))
2077 (t (lambda (char) (or (= ?\: char)
2080 (while (not (funcall endp (setq c (char-after))))
2086 ((looking-at "\\s-+")
2087 (delete-region (point) (match-end 0))
2089 (t (forward-char 1))))
2090 (buffer-substring-no-properties beg (point))))
2091 (one (type end) (unless (eq 'none type)
2095 ((stone point move simpletext color) s)
2096 ((number real double) (string-to-number s))
2098 (t (error "Unhandled type: %S" type))))))
2099 (val (spec) (cond ((symbolp spec)
2102 ;; todo: check range here.
2103 (one (aref spec 0) :end))
2104 ((eq 'or (car spec))
2105 (let ((v (one (cadr spec) t)))
2106 (if (= ?\] (char-after))
2109 ;; todo: this assumes `spec' has the form
2110 ;; (or foo (foo . bar))
2111 ;; i.e., foo is not rescanned. e.g., `SZ'.
2112 ;; probably this assumption is consistent
2113 ;; w/ the SGF authors' desire to make the
2114 ;; parsing easy, but you never know...
2115 (cons v (one (cdaddr spec) :end)))))
2116 (t (cons (one (car spec) :mid)
2117 (one (cdr spec) :end)))))
2118 (short (who) (when (eobp)
2119 (error "Unexpected EOF while reading %s" who)))
2120 (atvalp () (= ?\[ (char-after)))
2121 (PROP () (let (name spec ltype)
2122 (sw) (short 'property)
2123 (when (looking-at "[A-Z]")
2124 (setq name (read (current-buffer))
2125 spec (cdr (assq name specs)))
2128 (cdr (assq name keywords))
2129 (prog1 (if (= 1 (length spec))
2131 (unless (memq (setq ltype (car spec))
2133 (error "Bad spec: %S" spec))
2134 (if (and (eq 'elist ltype) (sw)
2137 (let ((type (cadr spec))
2139 (while (and (sw) (atvalp)
2140 (setq mo (val type)))
2145 (forward-char 1))))))
2146 (NODE () (let (prop props)
2148 (when (= ?\; (char-after))
2150 (while (setq prop (PROP))
2153 (TREE () (let (nodes)
2154 (while (and (sw) (not (eobp)))
2156 (?\; (push (NODE) nodes))
2157 (?\( (forward-char 1)
2158 (push (TREE) nodes))
2159 (?\) (forward-char 1))))
2162 (insert-file-contents filename)
2164 (while (and (sw) (not (eobp)) (= 40 (char-after))) ; left paren
2166 (push (TREE) trees))
2167 (nreverse trees))))))
2169 (defun gnugo/sgf-write-file (collection filename)
2170 ;; take responsibility for our actions
2171 (dolist (tree collection)
2172 (let* ((root (car tree))
2173 (who (assq :AP root))
2174 (fruit (cons "gnugo.el" gnugo-version)))
2177 (setcdr (last root) (list (cons :AP fruit))))))
2179 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2180 (specs (mapcar (lambda (full)
2181 (cons (intern (format ":%s" (car full)))
2183 gnugo/sgf-*r4-properties*))
2185 ;; todo: escape special chars for `text' and `simpletext'.
2187 ((>>one (v) (insert (format "[%s]" v)))
2188 (>>two (v) (insert (format "[%s:%s]" (car v) (cdr v))))
2189 (>>nl () (cond ((memq name aft-newline-appreciated)
2191 ((< 60 (current-column))
2196 (dolist (tree collection)
2204 (insert (substring (symbol-name name) 1))
2207 (memq (car (setq spec (cdr (assq name specs))))
2210 (let ((>> (if (consp (cadr spec))
2213 (dolist (little-v v)
2214 (setq p (point)) (funcall >> little-v) (>>nl))))
2218 (>>one v) (>>nl)))))
2220 (write-file filename)))))
2222 ;;; gnugo.el ends here