Add .fluxbox/keys.
[dotfiles-framework.git] / src / .emacs.d / load / gnugo.el
1 ;;; gnugo.el
2 ;;;
3 ;;; Copyright (C) 1999, 2000, 2002, 2003,
4 ;;;   2004, 2005, 2006, 2007, 2008 Thien-Thi Nguyen
5 ;;; This file is part of ttn's personal elisp library, released under GNU
6 ;;; GPL with ABSOLUTELY NO WARRANTY.  See the file COPYING for details.
7
8 ;;; Description: Run GNU Go in a buffer.
9
10 ;;; Commentary:
11
12 ;; Playing
13 ;; -------
14 ;;
15 ;; This file provides the command `gnugo' which allows you to play the game of
16 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
17 ;; in a dedicated Emacs buffer, or to resume a game in progress.  NOTE: In
18 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
19 ;; Go" to refer to the process object created by running the external program.
20 ;;
21 ;; At the start of a new game, you can pass additional command-line arguments
22 ;; to GNU Go to specify level, board size, color, komi, handicap, etc.  By
23 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
24 ;; both komi and handicap.
25 ;;
26 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
27 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
28 ;; moves (as well as a possibly intervening move by GNU Go), `u'.  To undo
29 ;; back through an arbitrary stone that you played, place the cursor on a
30 ;; stone and type `U' (note: uppercase).  Other keybindings are described in
31 ;; the `gnugo-board-mode' documentation, which you may view with the command
32 ;; `describe-mode' (normally `C-h m') in that buffer.  The buffer name shows
33 ;; the last move and who is currently to play.  Capture counts and other info
34 ;; are shown on the mode line immediately following the major mode name.
35 ;;
36 ;; While GNU Go is pondering its next move, certain commands that rely on its
37 ;; assistence will result in a "still waiting" error.  Do not be alarmed; that
38 ;; is normal.  When it is your turn again you may retry the command.  In the
39 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
40 ;; with `C-u M-x gnugo'.  (NOTE: A new game will slow down all games. :-)
41 ;;
42 ;; If GNU Go should crash during a game the mode line will show "no process".
43 ;; Please report the event to the GNU Go maintainers so that they can improve
44 ;; the program.
45 ;;
46 ;; This code was tested with:
47 ;; - GNU Emacs: 21.3 / 22.0.50 (from CVS)
48 ;; - GNU Go: 3.3.15 / 3.4 / 3.6
49 ;;
50 ;;
51 ;; Meta-Playing (aka Customizing)
52 ;; ------------------------------
53 ;;
54 ;; Customization is presently limited to
55 ;;   vars:            `gnugo-program'
56 ;;                    `gnugo-animation-string'
57 ;;                    `gnugo-mode-line'
58 ;;                    `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
59 ;;                    `gnugo-xpms'
60 ;;   normal hooks:    `gnugo-board-mode-hook'
61 ;;                    `gnugo-post-move-hook'
62 ;;   and the keymap:  `gnugo-board-mode-map'
63 ;;
64 ;; The variable `gnugo-xpms' is a special case.  To set it you need to load
65 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
66 ;; interface.
67 ;;
68 ;;
69 ;; Meta-Meta-Playing (aka Hacking)
70 ;; -------------------------------
71 ;;
72 ;; You may wish to first fix the bugs:
73 ;; - `gnugo-toggle-dead-group' only half-complete; see docstring for details
74 ;; - probably sgf handling is not 100% to spec
75 ;; - subprocess should provide scoring details, gnugo.el not yet blissful
76 ;;
77 ;; Otherwise (we can live w/ some bugs), here are some ideas:
78 ;; - talk GTP over the network
79 ;; - "assist minor mode" (see gnugo-extra.el for work in progress)
80 ;; - using assist minor mode, gnugo-v-gnugo (ibid)
81 ;; - extract GNUGO Board mode and sgf stuff into sgf.el; make gnugo.el use it
82 ;; - make gnugo (the external program) support query (read-only) thread
83 ;;   so as to be able to lift "still waiting" restriction
84 ;; - alternatively, extend GNUGO Board mode to manage another subprocess
85 ;;   dedicated to analysis (no genmove)
86 ;; - command `C' to add a comment to the sgf tree
87 ;; - command `C-u =' to label a position
88 ;; - sgf tree display, traversal (belongs in sgf.el); review game history
89 ;;   in another buffer; branch subgame tree at arbitrary point
90 ;; - subgame branch matriculation (maturity: child leaves the family)
91 ;; - dribble the sgf tree
92 ;; - "undo undo undoing"; integrate Emacs undo, GTP undo, subgame branching
93 ;; - make buffer name format configurable (but enforce uniqueness)
94 ;; - more tilde escapes for `gnugo-mode-line'
95 ;; - make veneration configurable
96 ;; - make animation more configurable; lift same-color-stones-only
97 ;;   restriction; allow sequencing rather than lock-step; include sound
98 ;; - [your hacking ideas here]
99 ;;
100 ;; Some gnugo.el hackers update http://www.emacswiki.org -- check it out!
101 ;;
102 ;;
103 ;; History
104 ;; -------
105 ;;
106 ;; Originally gnugo.el was written to interact w/ "gnugo --mode text" and then
107 ;; "gnugo --mode emacs" as the subprocess.  Those versions were released as
108 ;; 1.x, w/ x < 14.  In Novemeber 2002, gnugo.el was changed to interact w/
109 ;; "gnugo --mode gtp", but was released as 1.14 through 1.26, even though the
110 ;; proper versions should be 2.0.x for "--mode gtp", and 2.1.x for XPM image
111 ;; support.  (Sorry about the confusion.)
112 ;;
113 ;; Thus we arrive at at the current version.  The first gnugo.el to be
114 ;; released w/ a `gnugo-version' variable is "2.2.0".  The versioning scheme
115 ;; is strictly monotonically increasing numbers and dots, no letters or other
116 ;; suffixes (and none of this even/odd crap).  Here we list, aside from the
117 ;; bugfixes, some of the notable changes introduced in each released version:
118 ;;
119 ;; 2.2.x -- uncluttered, letters and numbers hidden, board centered
120 ;;          buffer name shows last move and current player
121 ;;          mode-line customization (var `gnugo-mode-line')
122 ;;          new commands: `=', `h', `s', `F', `R', `l', `U', `C-c C-p'
123 ;;          program option customization (var `gnugo-program')
124 ;;          new hooks (vars `gnugo-post-move-hook', `gnugo-board-mode-hook')
125 ;;          multiple independent buffers/games
126 ;;          XPM set can be changed on the fly (global and/or local)
127 ;;          font-locking for "X", "O", "[xo]"
128 ;;          undo by N moves, by "move pair", or by board position
129 ;;          grid (letters and numbers) visibility can be toggled
130 ;;
131 ;;
132 ;; History Predicted
133 ;; -----------------
134 ;;
135 ;; If you are an elisp programmer, this section might not apply to you;
136 ;; the GPL allows you to define the future of the code you receive under
137 ;; its terms, as long as you do not deny that freedom to subsequent users.
138 ;;
139 ;; For users who are not elisp programmers, you can look forward to gradual
140 ;; refinement in 2.x, splitting into gnugo.el and sgf.el in 3.x, and then
141 ;; eventual merging into GNU Emacs for 4.x (if RMS gives it the thumbs-up).
142 ;; If it is not accepted into Emacs at that time, a new maintainer will be
143 ;; sought.  In any case, it will no longer be bundled w/ ttn-pers-elisp.
144
145 ;;; Code:
146
147 (require 'cl)                           ; use the source luke!
148 (ignore-errors (require 'time-date))    ; for `time-subtract'
149
150 ;;;---------------------------------------------------------------------------
151 ;;; Political arts
152
153 (defconst gnugo-version "2.2.13"
154   "Version of gnugo.el currently loaded.
155 Note that more than two dots in the value indicates \"pre-release\",
156 or \"alpha\" or \"hackers-invited-all-else-beware\"; use at your own risk!
157 The more dots the more courage/foolishness you must find to continue.
158 See source code for a history of what means what version-wise.")
159
160 ;;;---------------------------------------------------------------------------
161 ;;; Variables for the uninquisitive programmer
162
163 (defvar gnugo-program "gnugo"
164   "*Command to start an external program that speaks GTP, such as \"gnugo\".
165 The value may also be in the form \"PROGRAM OPTIONS...\" in which case the
166 the command `gnugo' will prefix OPTIONS in its default offering when it
167 queries you for additional options.  It is an error for \"--mode\" to appear
168 in OPTIONS.
169
170 For more information on GTP and GNU Go, feel free to visit:
171 http://www.gnu.org/software/gnugo")
172
173 (defvar gnugo-board-mode-map nil
174   "Keymap for GNUGO Board mode.")
175
176 (defvar gnugo-board-mode-hook nil
177   "*Hook run when entering GNUGO Board mode.")
178
179 (defvar gnugo-post-move-hook nil
180   "*Normal hook run after a move and before the board is refreshed.
181 Hook functions can prevent the call to `gnugo-refresh' by evaluating:
182   (setq inhibit-gnugo-refresh t)
183 Initially, when `run-hooks' is called, the current buffer is the GNUGO
184 Board buffer of the game.  Hook functions that switch buffers must take
185 care not to call (directly or indirectly through some other function)
186 `gnugo-put' or `gnugo-get' after the switch.")
187
188 (defvar gnugo-animation-string
189   (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
190     (concat jam jam jam jam jam
191             ;; "SECRET MESSAGE HERE"
192             blink blink blink blink blink blink blink blink
193             ;; Playing go is like fighting ignorance: when you think you have
194             ;; surrounded something by knowing it very well it often turns
195             ;; out that in the time you spent deepening this understanding,
196             ;; other areas of ignorance have surrounded you.
197             spin spin spin spin spin spin spin spin spin
198             ;; Playing go is not like fighting ignorance: what one person
199             ;; knows many people may come to know; knowledge does not build
200             ;; solely move by move.  Wisdom, on the other hand...
201             yada yada yada))
202   "*String whose individual characters are used for animation.
203 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
204 render the stones in their respective result groups as the first character
205 in the string, then the next, and so on.")
206
207 (defvar gnugo-mode-line "~b ~w :~m :~u"
208   "*A `mode-line-format'-compliant value for GNUGO Board mode.
209 If a single string, the following special escape sequences are
210 replaced with their associated information:
211   ~b,~w  black,white captures (a number)
212   ~p     current player (black or white)
213   ~m     move number
214   ~t     time waiting for the current move
215   ~u     time taken for the Ultimate (most recent) move
216 The times are in seconds, or \"-\" if that information is not available.
217 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
218
219 (defvar gnugo-X-face 'font-lock-string-face
220   "*Name of face to use for X (black) stones.")
221
222 (defvar gnugo-O-face 'font-lock-builtin-face
223   "*Name of face to use for O (white) stones.")
224
225 (defvar gnugo-grid-face 'default
226   "*Name of face to use for the grid (A B C ... 1 2 3 ...).")
227
228 ;;;---------------------------------------------------------------------------
229 ;;; Variables for the inquisitive programmer
230
231 (defconst gnugo-font-lock-keywords
232   '(("X" . gnugo-X-face)
233     ("O" . gnugo-O-face))
234   "Font lock keywords for `gnugo-board-mode'.")
235
236 (defvar gnugo-option-history nil)
237
238 (defvar gnugo-state nil)                ; hint: C-c C-p
239
240 (eval-when-compile
241   (defvar gnugo-xpms nil))
242
243 ;;;---------------------------------------------------------------------------
244 ;;; In case Emacs is lacking
245
246 (unless (fboundp 'delete-dups)
247   (defun delete-dups (list)             ; from repo 2004-10-29
248     "Destructively remove `equal' duplicates from LIST.
249 Store the result in LIST and return it.  LIST must be a proper list.
250 Of several `equal' occurrences of an element in LIST, the first
251 one is kept."
252     (let ((tail list))
253       (while tail
254         (setcdr tail (delete (car tail) (cdr tail)))
255         (setq tail (cdr tail))))
256     list))
257
258 (unless (fboundp 'time-subtract)
259   (defun time-subtract (t1 t2)          ; from repo 2004-10-29
260     "Subtract two time values.
261 Return the difference in the format of a time value."
262     (let ((borrow (< (cadr t1) (cadr t2))))
263       (list (- (car t1) (car t2) (if borrow 1 0))
264             (- (+ (if borrow 65536 0) (cadr t1)) (cadr t2))))))
265
266 (unless (fboundp 'window-edges)
267   (defun window-edges (&optional window)
268     (let ((cw (/ (frame-pixel-width) (frame-width)))
269           (ch (/ (frame-pixel-height) (frame-height)))
270           (pix-edges (window-pixel-edges window)))
271       (list (/ (nth 0 pix-edges) cw)
272             (/ (nth 1 pix-edges) ch)
273             (/ (nth 2 pix-edges) cw)
274             (/ (nth 3 pix-edges) ch)))))
275
276 ;;;---------------------------------------------------------------------------
277 ;;; Support functions
278
279 (put  'gnugo-put 'lisp-indent-function 1)
280 (defun gnugo-put (key value) (puthash key value gnugo-state))
281 (defun gnugo-get (key)       (gethash key gnugo-state))
282
283 (let ((docs "Put or get move/game/board-specific properties.
284 \(This docstring is shared by `gnugo-put' and `gnugo-get'.\)
285
286 There are many properties, each named by a keyword, that record and control
287 how gnugo.el manages each game.  Each GNUGO Board buffer has its own set
288 of properties, stored in the hash table `gnugo-state'.  Here we document
289 some of the more stable properties.  You may wish to use them as part of
290 a `gnugo-post-move-hook' function, for example.  Be careful to preserve
291 the current buffer as `gnugo-state' is made into a buffer-local variable.
292 NOTE: In the following, \"see foo\" actually means \"see foo source or
293 you may never really understand to any degree of personal satisfaction\".
294
295  :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
296
297  :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
298
299  :game-over -- nil until game over at which time its value is set to
300                the alist `((live GROUP ...) (dead GROUP ...))'
301
302  :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
303                     a simple list of one or more gametrees, updated in
304                     conjunction w/ :sgf-gametree and :monkey
305
306  :sgf-gametree -- one of the gametrees in :sgf-collection
307
308  :monkey -- vector of three elements: LOC, a pointer to a node on the
309             :sgf-gametree representing the most recently-played move
310             (the next move modifies the cdr of LOC); MEM, the simple
311             reverse-chronological list of previous LOC pointers; and
312             COUNT, the number of moves from the beginning of the game
313
314  :gnugo-color -- either \"black\" or \"white\"
315  :user-color
316  :last-mover
317
318  :last-waiting  -- seconds and time value, respectively; see `gnugo-push-move'
319  :waiting-start
320
321  :black-captures -- these are strings since gnugo.el doesn't do anything
322  :white-captures    w/ the information besides display it in the mode line;
323                     gory details in functions `gnugo-propertize-board-buffer'
324                     and `gnugo-merge-showboard-results' (almost more effort
325                     than they are worth!)
326
327  :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
328                           `gnugo-toggle-image-display' and `gnugo-refresh',
329                           as well as gnugo-xpms.el (available elsewhere)
330
331  :all-yy -- list of 46 keywords used as the `category' text property
332             (so that their plists, typically w/ property `display' or
333             `do-not-display') are consulted by the Emacs display engine;
334             46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
335             `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
336
337  :lparen-ov -- overlays shuffled about to indicate the last move; only
338  :rparen-ov    one is used when displaying using images
339
340  :last-user-bpos -- board position; keep the hapless human happy
341
342 As things stabilize probably more info will be added to this docstring."))
343   (put 'gnugo-put 'function-documentation docs)
344   (put 'gnugo-get 'function-documentation docs))
345
346 (defun gnugo-describe-internal-properties ()
347   "Pretty-print `gnugo-state' properties in another buffer.
348 Handle the big, slow-to-render, and/or uninteresting ones specially."
349   (interactive)
350   (let ((buf (current-buffer))
351         (d (gnugo-get :diamond))
352         acc)
353     (maphash (lambda (&rest args)
354                (case (car args)
355                  ((:xpms :local-xpms)
356                   (setcdr args (format "hash: %X (%d images)"
357                                        (sxhash (cadr args))
358                                        (length (cadr args)))))
359                  (:sgf-collection
360                   (setcdr args (length (cadr args))))
361                  (:monkey
362                   (let* ((value (cadr args))
363                          (loc (aref value 0)))
364                     (setcdr args (list
365                                   (length (aref value 1))
366                                   (length (cdr loc))
367                                   (car loc))))))
368                (setq acc (cons args acc)))
369              gnugo-state)
370     (switch-to-buffer (get-buffer-create
371                        (format "%s*GNUGO Board Properties*"
372                                (gnugo-get :diamond))))
373     (erase-buffer)
374     (emacs-lisp-mode)
375     (setq truncate-lines t)
376     (save-excursion
377       (let ((standard-output (current-buffer)))
378         (pp (reverse acc)))
379       (goto-char (point-min))
380       (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
381                         (if (string= "" d)
382                             ".+\n"
383                           ""))))
384         (while (re-search-forward rx (point-max) t)
385           (let ((pos (get-text-property (string-to-number (match-string 1))
386                                         'gnugo-position buf)))
387             (delete-region (+ 2 (match-beginning 0)) (point))
388             (insert (format " %S" pos))))))
389     (message "%d properties" (length acc))))
390
391 (defun gnugo-board-buffer-p (&optional buffer)
392   "Return non-nil if BUFFER is a GNUGO Board buffer."
393   (with-current-buffer (or buffer (current-buffer)) gnugo-state))
394
395 (defun gnugo-board-user-play-ok-p (&optional buffer)
396   "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
397   (with-current-buffer (or buffer (current-buffer))
398     (and gnugo-state (not (gnugo-get :waitingp)))))
399
400 (defun gnugo-other (color)
401   (if (string= "black" color) "white" "black"))
402
403 (defun gnugo-gate (&optional in-progress-p)
404   (unless (gnugo-board-buffer-p)
405     (error "Wrong buffer -- try M-x gnugo"))
406   (unless (gnugo-get :proc)
407     (error "No \"gnugo\" process!"))
408   (when (gnugo-get :waitingp)
409     (error "Not your turn yet -- please wait for \"\(%s to play\)\""
410            (gnugo-get :user-color)))
411   (when (and (gnugo-get :game-over) in-progress-p)
412     (error "Sorry, game over")))
413
414 (defun gnugo-sentinel (proc string)
415   (let ((status (process-status proc)))
416     (when (or (eq status 'exit)
417               (eq status 'signal))
418       (let ((buf (process-buffer proc)))
419         (when (buffer-live-p buf)
420           (with-current-buffer buf
421             (setq mode-line-process '( " [%s]"))
422             (when (eq proc (gnugo-get :proc))
423               (gnugo-put :proc nil))))))))
424
425 (defun gnugo-send-line (line)
426   (let ((proc (gnugo-get :proc)))
427     (process-send-string proc line)
428     (process-send-string proc "\n")))
429
430 (defun gnugo-synchronous-send/return (message)
431   "Return (TIME . STRING) where TIME is that returned by `current-time' and
432 STRING omits the two trailing newlines.  See also `gnugo-query'."
433   (when (gnugo-get :waitingp)
434     (error "Sorry, still waiting for %s to play" (gnugo-get :gnugo-color)))
435   (gnugo-put :sync-return "")
436   (let ((proc (gnugo-get :proc)))
437     (set-process-filter
438      proc (lambda (proc string)
439             (let* ((so-far (gnugo-get :sync-return))
440                    (start  (max 0 (- (length so-far) 2))) ; backtrack a little
441                    (full   (gnugo-put :sync-return (concat so-far string))))
442               (when (string-match "\n\n" full start)
443                 (gnugo-put :sync-return
444                   (cons (current-time) (substring full 0 -2)))))))
445     (gnugo-send-line message)
446     (let (rv)
447       ;; type change => break
448       (while (stringp (setq rv (gnugo-get :sync-return)))
449         (accept-process-output proc))
450       (gnugo-put :sync-return "")
451       rv)))
452
453 (defun gnugo-query (message-format &rest args)
454   "Return cleaned-up value of a call to `gnugo-synchronous-send/return'.
455 The TIME portion is omitted as well as the first two characters of the STRING
456 portion (corresponding to the status indicator in the Go Text Protocol).  Use
457 this function when you are sure the command cannot fail.  The first arg is
458 a format string applied to the rest of the args."
459   (substring (cdr (gnugo-synchronous-send/return
460                    (apply 'format message-format args)))
461              2))
462
463 (defun gnugo-lsquery (message-format &rest args)
464   (split-string (apply 'gnugo-query message-format args)))
465
466 (defsubst gnugo-treeroot (prop)
467   (cdr (assq prop (car (gnugo-get :sgf-gametree)))))
468
469 (defun gnugo-goto-pos (pos)
470   "Move point to board position POS, a letter-number string."
471   (goto-char (point-min))
472   (forward-line (- (1+ (gnugo-treeroot :SZ))
473                    (string-to-number (substring pos 1))))
474   (forward-char 1)
475   (forward-char (+ (if (= 32 (following-char)) 1 2)
476                    (* 2 (- (let ((letter (aref pos 0)))
477                              (if (> ?I letter)
478                                  letter
479                                (1- letter)))
480                            ?A)))))
481
482 (defun gnugo-f (frag)
483   (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
484
485 (defun gnugo-yang (c)
486   (cdr (assq c '((?+ . hoshi)
487                  (?. . empty)
488                  (?X . (bmoku . bpmoku))
489                  (?O . (wmoku . wpmoku))))))
490
491 (defun gnugo-yy (yin yang &optional momentaryp)
492   (gnugo-f (format "%d-%s"
493                    yin (cond ((and (consp yang) momentaryp) (cdr yang))
494                              ((consp yang) (car yang))
495                              (t yang)))))
496
497 (defun gnugo-toggle-image-display ()
498   (unless (and (fboundp 'display-images-p) (display-images-p))
499     (error "Display does not support images, sorry"))
500   (require 'gnugo-xpms)
501   (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
502     (error "Could not load `gnugo-xpms', sorry"))
503   (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
504     (unless (eq fresh (gnugo-get :xpms))
505       (gnugo-put :xpms fresh)
506       (gnugo-put :all-yy nil)))
507   (let* ((new (not (gnugo-get :display-using-images)))
508          (act (if new 'display 'do-not-display)))
509     (mapc (lambda (yy)
510             (setcar (symbol-plist yy) act))
511           (or (gnugo-get :all-yy)
512               (gnugo-put :all-yy
513                 (prog1 (mapcar (lambda (ent)
514                                  (let* ((k (car ent))
515                                         (yy (gnugo-yy (cdr k) (car k))))
516                                    (setplist yy `(not-yet ,(cdr ent)))
517                                    yy))
518                                (gnugo-get :xpms))
519                   (let ((imul (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
520                                                'not-yet))))
521                     (gnugo-put :w-imul (car imul))
522                     (gnugo-put :h-imul (cdr imul)))))))
523     (setplist (gnugo-f 'ispc) (and new
524                                    ;; `(display (space :width 0))'
525                                    ;; works as well, for newer emacs
526                                    '(invisible t)))
527     (gnugo-put :highlight-last-move-spec
528       (if new
529           '((lambda (p)
530               (get (gnugo-yy (get-text-property p 'gnugo-yin)
531                              (get-text-property p 'gnugo-yang)
532                              t)
533                    'display))
534             0 delete-overlay)
535         (gnugo-get :default-highlight-last-move-spec)))
536     ;; a kludge to be reworked another time perhaps by another gnugo.el lover
537     (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
538       (mapc 'delete-overlay (cdar group))
539       (setcdr (car group) nil))
540     (gnugo-put :wmul (if new (gnugo-get :w-imul) 1))
541     (gnugo-put :hmul (if new (gnugo-get :h-imul) 1))
542     (gnugo-put :display-using-images new)))
543
544 (defun gnugo-toggle-grid ()
545   "Turn the grid around the board on or off."
546   (interactive)
547   (funcall (if (memq :nogrid buffer-invisibility-spec)
548                'remove-from-invisibility-spec
549              'add-to-invisibility-spec)
550            :nogrid)
551   (save-excursion (gnugo-refresh)))
552
553 (defun gnugo-propertize-board-buffer ()
554   (erase-buffer)
555   (insert (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
556   (let* ((grid-props (list 'invisible :nogrid
557                            'font-lock-face gnugo-grid-face))
558          (%gpad (gnugo-f 'gpad))
559          (%gspc (gnugo-f 'gspc))
560          (%lpad (gnugo-f 'lpad))
561          (%rpad (gnugo-f 'rpad))
562          (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
563          (size (gnugo-treeroot :SZ))
564          (size-string (number-to-string size)))
565     (goto-char (point-min))
566     (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
567     (skip-chars-forward " ")
568     (put-text-property (1- (point)) (point) 'category %gpad)
569     (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
570     (forward-char 1)
571     (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
572     (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
573       (let* ((row (match-string-no-properties 1))
574              (edge (match-end 0))
575              (other-edge (+ edge (* 2 size) -1))
576              (right-empty (+ other-edge (length row) 1))
577              (top-p (string= size-string row))
578              (bot-p (string= "1" row)))
579         (let* ((nL (- edge 1 (length size-string)))
580                (nR (- edge 1))
581                (ov (make-overlay nL nR (current-buffer) t)))
582           (add-text-properties nL nR grid-props)
583           ;; We redundantly set `invisible' in the overlay to workaround
584           ;; a display bug whereby text *following* the overlaid text is
585           ;; displayed with the face of the overlaid text, but only when
586           ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
587           ;; This has something to do w/ the bletcherous `before-string'.
588           (overlay-put ov 'invisible :nogrid)
589           (overlay-put ov 'category %lpad))
590         (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
591             ((< other-edge p))
592           (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
593                                                 (truncate (- p edge) 2))
594                                    row))
595                  (yin (let ((A-p (= edge p))
596                             (Z-p (= (1- other-edge) p)))
597                         (cond ((and top-p A-p) 1)
598                               ((and top-p Z-p) 3)
599                               ((and bot-p A-p) 7)
600                               ((and bot-p Z-p) 9)
601                               (top-p 2)
602                               (bot-p 8)
603                               (A-p 4)
604                               (Z-p 6)
605                               (t 5))))
606                  (yang (gnugo-yang (char-after p))))
607             (add-text-properties p (1+ p)
608                                  `(gnugo-position
609                                    ,position
610                                    gnugo-yin
611                                    ,yin
612                                    gnugo-yang
613                                    ,yang
614                                    category
615                                    ,(gnugo-yy yin yang)
616                                    front-sticky
617                                    (gnugo-position gnugo-yin))))
618           (unless (= (1- other-edge) p)
619             (add-text-properties (1+ p) (+ 2 p) ispc-props)
620             (put-text-property p (+ 2 p) 'intangible ival)))
621         (add-text-properties (1+ other-edge) right-empty grid-props)
622         (goto-char right-empty)
623         (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
624           (let ((prop (if (string= "WH" (match-string 1))
625                           :white-captures
626                         :black-captures))
627                 (beg (match-beginning 2))
628                 (end (match-end 2)))
629             (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
630             (gnugo-put prop (match-string-no-properties 2))))
631         (end-of-line)
632         (put-text-property right-empty (point) 'category %rpad)
633         (forward-char 1)))
634     (add-text-properties (1- (point)) (point-max) grid-props)
635     (skip-chars-forward " ")
636     (put-text-property (1- (point)) (point) 'category %gpad)
637     (put-text-property (point) (progn (end-of-line) (point))
638                        'category %gspc)))
639
640 (defun gnugo-merge-showboard-results ()
641   (let ((aft (substring (cdr (gnugo-synchronous-send/return "showboard")) 3))
642         (adj 1)                         ; string to buffer position adjustment
643         (sync "[0-9]+ stones$")
644         (bef (buffer-substring-no-properties (point-min) (point-max)))
645         (bef-start 0) (bef-idx 0)
646         (aft-start 0) (aft-idx 0)
647         aft-sync-backtrack mis inc cut new very-strange)
648     (while (numberp (setq mis (compare-strings bef bef-start nil
649                                                aft aft-start nil)))
650       (setq aft-sync-backtrack nil
651             inc (if (> 0 mis)
652                     (- (+ 1 mis))
653                   (- mis 1))
654             bef-idx (+ bef-start inc)
655             aft-idx (+ aft-start inc)
656             bef-start (if (eq bef-idx (string-match sync bef bef-idx))
657                           (match-end 0)
658                         (1+ bef-idx))
659             aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
660                                (let ((peek (1- aft-idx)))
661                                  (while (not (= 32 (aref aft peek)))
662                                    (setq peek (1- peek)))
663                                  (setq aft-sync-backtrack (1+ peek))))
664                           (match-end 0)
665                         (1+ aft-idx))
666             cut (+ bef-idx adj
667                    (if aft-sync-backtrack
668                        (- aft-sync-backtrack aft-idx)
669                      0)))
670       (goto-char cut)
671       (if aft-sync-backtrack
672           (let* ((asb aft-sync-backtrack)
673                  (l-p (get-text-property cut :gnugo-cf))
674                  (old-len (car l-p))
675                  (capprop (cdr l-p))
676                  (keep (text-properties-at cut)))
677             (setq new (substring aft asb (string-match " " aft asb)))
678             (plist-put keep :gnugo-cf (cons (length new) capprop))
679             (gnugo-put capprop new)
680             (delete-char old-len)
681             (insert (apply 'propertize new keep))
682             (setq adj (+ adj (- (length new) old-len))))
683         (setq new (aref aft aft-idx))
684         (insert-and-inherit (char-to-string new))
685         (let ((yin (get-text-property cut 'gnugo-yin))
686               (yang (gnugo-yang new)))
687           (add-text-properties cut (1+ cut)
688                                `(gnugo-yang
689                                  ,yang
690                                  category
691                                  ,(gnugo-yy yin yang))))
692         (delete-char 1)
693         ;; do this last to avoid complications w/ font lock
694         ;; (this also means we cannot include `intangible' in `front-sticky')
695         (when (setq very-strange (get-text-property (1+ cut) 'intangible))
696           (put-text-property cut (1+ cut) 'intangible very-strange))))))
697
698 (defun gnugo-move-history (&optional rsel)
699   "Determine and return the game's move history.
700 Optional arg RSEL controls side effects and return value.
701 If nil, display the history in the echo area as \"(N moves)\"
702 followed by the space-separated list of moves.  When called
703 interactively with a prefix arg (i.e., RSEL is `(4)'), display
704 similarly, but suffix with the mover (either \":B\" or \":W\").
705 If RSEL is the symbol `car' return the most-recent move; if
706 `cadr', the next-to-most-recent move; if `count' the number of
707 moves thus far.
708
709 For all other values of RSEL, do nothing and return nil."
710   (interactive "P")
711   (let ((size (gnugo-treeroot :SZ))
712         col
713         (mem (aref (gnugo-get :monkey) 1))
714         acc node mprop move)
715     (flet ((as-pos (cc) (if (string= "tt" cc)
716                             "PASS"
717                           (setq col (aref cc 0))
718                           (format "%c%d"
719                                   (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
720                                   (- size (- (aref cc 1) ?a)))))
721            (next (byp) (when (setq node (caar mem)
722                                    mprop (or (assq :B node)
723                                              (assq :W node)))
724                          (setq move (as-pos (cdr mprop))
725                                mem (cdr mem))
726                          (push (if byp
727                                    (format "%s%s" move (car mprop))
728                                  move)
729                                acc)))
730            (tell () (message "(%d moves) %s"
731                              (length acc)
732                              (mapconcat 'identity (nreverse acc) " "))))
733       (cond
734        ((not rsel)        (while (next nil)) (tell))
735        ((equal '(4) rsel) (while (next t))   (tell))
736        ((eq 'car rsel)             (car (next nil)))
737        ((eq 'cadr rsel) (next nil) (car (next nil)))
738        ((eq 'count rsel) (aref (gnugo-get :monkey) 2))))))
739
740 (defun gnugo-note (property value &optional movep mogrifyp)
741   (when mogrifyp
742     (let ((sz (gnugo-treeroot :SZ)))
743       (flet ((mog (pos) (if (string= "PASS" pos)
744                             "tt"
745                           (let* ((col (aref pos 0))
746                                  (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
747                                  (two (+ ?a (- sz (string-to-number
748                                                    (substring pos 1))))))
749                             (format "%c%c" one two)))))
750         (setq value (if (consp value)
751                         (mapcar 'mog value)
752                       (mog value))))))
753   (let* ((fruit (list (cons property value)))
754          (monkey (gnugo-get :monkey))
755          (loc (aref monkey 0)))
756     (if movep
757         (let ((mem (aref monkey 1)))
758           ;; todo: do variation check/merge/branch here.
759           (setcdr loc (list fruit))
760           (aset monkey 0 (setq loc (cdr loc)))
761           (aset monkey 1 (cons loc mem))
762           (aset monkey 2 (1+ (aref monkey 2))))
763       (setcdr (last (car loc)) fruit))))
764
765 (defun gnugo-close-game (end-time resign)
766   (gnugo-put :game-end-time end-time)
767   (let ((now (or end-time (current-time))))
768     (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
769                                      (cadr now))))
770   (gnugo-put :game-over
771     (if (or (eq t resign)
772             (and (stringp resign)
773                  (string-match "[BW][+][Rr]esign" resign)))
774         (flet ((ls (color) (mapcar
775                             (lambda (x)
776                               (cons (list color)
777                                     (split-string x)))
778                             (split-string
779                              (gnugo-query "worm_stones %s" color)
780                              "\n"))))
781           (let ((live (append (ls "black") (ls "white"))))
782             `((live ,@live)
783               (dead))))
784       (let ((dd (gnugo-query "dragon_data"))
785             (start 0) mem color ent live dead)
786         (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
787                              dd start)
788           (setq mem (match-string 1 dd)
789                 color (match-string 2 dd)
790                 start (match-end 0)
791                 ent (cons (list color)
792                           (sort (gnugo-lsquery "dragon_stones %s" mem)
793                                 'string<)))
794           (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
795                         dd start)
796           (if (match-string 2 dd)
797               (push ent live)
798             (push ent dead))
799           (setq start (match-end 0)))
800         `((live ,@live)
801           (dead ,@dead))))))
802
803 (defun gnugo-push-move (userp move)
804   (let* ((color (gnugo-get (if userp :user-color :gnugo-color)))
805          (start (gnugo-get :waiting-start))
806          (now (current-time))
807          (resignp (string= "resign" move))
808          (passp (string= "PASS" move))
809          (head (gnugo-move-history 'car))
810          (onep (and head (string= "PASS" head)))
811          (donep (or resignp (and onep passp))))
812     (unless passp
813       (gnugo-merge-showboard-results))
814     (gnugo-put :last-mover color)
815     (when userp
816       (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
817     (gnugo-note (if (string= "black" color) :B :W) move t (not resignp))
818     (when resignp
819       (gnugo-note :EV "resignation"))
820     (when start
821       (gnugo-put :last-waiting (cadr (time-subtract now start))))
822     (when donep
823       (gnugo-close-game now resignp))
824     (gnugo-put :waiting-start (and (not donep) now))
825     donep))
826
827 (defun gnugo-venerate (yin yang)
828   (let* ((fg-yy (gnugo-yy yin yang))
829          (fg-disp (or (get fg-yy 'display)
830                       (get fg-yy 'do-not-display)))
831          (fg-data (plist-get (cdr fg-disp) :data))
832          (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
833          (bg-disp (or (get bg-yy 'display)
834                       (get bg-yy 'do-not-display)))
835          (bg-data (plist-get (cdr bg-disp) :data))
836          (bop (lambda (s)
837                 (let* ((start 0)
838                        (ncolors
839                         (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
840                           (setq start (match-end 0))
841                           (string-to-number (match-string 1 s)))))
842                   (while (and (<= 0 ncolors) (string-match ",\n" s start))
843                     (setq start (match-end 0)
844                           ncolors (1- ncolors)))
845                   (string-match "\"" s start)
846                   (match-end 0))))
847          (new (copy-sequence fg-data))
848          (lx (length fg-data))
849          (lb (length bg-data))
850          (sx (funcall bop fg-data))
851          (sb (funcall bop bg-data))
852          (color-key (aref new sx)))     ; blech, heuristic
853     (while (< sx lx)
854       (when (and (not (= color-key (aref new sx)))
855                  (< 0 (random 4)))
856         (aset new sx (aref bg-data sb)))
857       (incf sx)
858       (incf sb))
859     (create-image new 'xpm t :ascent 'center)))
860
861 (defun gnugo-refresh (&optional nocache)
862   "Update GNUGO Board buffer display.
863 While a game is in progress, parenthesize the last-played stone (no parens
864 for pass).  If the buffer is currently displayed in the selected window,
865 recenter the board (presuming there is extra space in the window).  Update
866 the mode line.  Lastly, move point to the last position played by the user,
867 if that move was not a pass.
868
869 Prefix arg NOCACHE requests complete reconstruction of the display, which may
870 be slow.  (This should normally be unnecessary; specify it only if the display
871 seems corrupted.)  NOCACHE is silently ignored when GNU Go is thinking about
872 its move."
873   (interactive "P")
874   (when (and nocache (not (gnugo-get :waitingp)))
875     (gnugo-propertize-board-buffer))
876   (let* ((last-mover (gnugo-get :last-mover))
877          (other (gnugo-other last-mover))
878          (move (gnugo-move-history 'car))
879          (game-over (gnugo-get :game-over))
880          window last)
881     ;; last move
882     (when move
883       (let ((l-ov (gnugo-get :lparen-ov))
884             (r-ov (gnugo-get :rparen-ov)))
885         (if (member move '("PASS" "resign"))
886             (mapc 'delete-overlay (list l-ov r-ov))
887           (gnugo-goto-pos move)
888           (let* ((p (point))
889                  (hspec (gnugo-get :highlight-last-move-spec))
890                  (display-value (nth 0 hspec))
891                  (l-offset (nth 1 hspec))
892                  (l-new-pos (+ p l-offset))
893                  (r-action (nth 2 hspec)))
894             (overlay-put l-ov 'display
895                          (if (functionp display-value)
896                              (funcall display-value p)
897                            display-value))
898             (move-overlay l-ov l-new-pos (1+ l-new-pos))
899             (if r-action
900                 (funcall r-action r-ov)
901               (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
902     ;; buffer name
903     (rename-buffer (concat (gnugo-get :diamond)
904                            (if game-over
905                                (format "%s(game over)"
906                                        (if (string= move "resign")
907                                            (concat move "ation ")
908                                          ""))
909                              (format "%s(%s to play)"
910                                      (if move (concat move " ") "")
911                                      other))))
912     ;; pall of death
913     (when game-over
914       (let ((live (cdr (assq 'live game-over)))
915             (dead (cdr (assq 'dead game-over)))
916             p pall)
917         (unless (eq game-over (get-text-property 1 'game-over))
918           (dolist (group (append live dead))
919             (dolist (pos (cdr group))
920               (gnugo-goto-pos pos)
921               (setq p (point))
922               (put-text-property p (1+ p) 'group group)))
923           (put-text-property 1 2 'game-over game-over))
924         (dolist (group live)
925           (when (setq pall (cdar group))
926             (mapc 'delete-overlay pall)
927             (setcdr (car group) nil)))
928         (dolist (group dead)
929           (unless (cdar group)
930             (let (ov pall c (color (caar group)))
931               (setq c (if (string= "black" color) "x" "o"))
932               (dolist (pos (cdr group))
933                 (gnugo-goto-pos pos)
934                 (setq p (point) ov (make-overlay p (1+ p)))
935                 (overlay-put
936                  ov 'display
937                  (if (gnugo-get :display-using-images)
938                      ;; respect the dead individually; it takes more time
939                      ;; but that's not a problem (for them)
940                      (gnugo-venerate (get-text-property p 'gnugo-yin)
941                                      (gnugo-yang (aref (upcase c) 0)))
942                    (propertize c 'face 'font-lock-warning-face)))
943                 (push ov pall))
944               (setcdr (car group) pall))))))
945     ;; window update
946     (when (setq window (get-buffer-window (current-buffer)))
947       (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
948              (size (gnugo-treeroot :SZ))
949              (under10p (< size 10))
950              (h (- (truncate (- (window-height window)
951                                 (* size (gnugo-get :hmul))
952                                 (if gridp 2 0))
953                              2)
954                    (if gridp 0 1)))
955              (edges (window-edges window))
956              (right-w-edge (nth 2 edges))
957              (avail-width (- right-w-edge (nth 0 edges)))
958              (wmul (gnugo-get :wmul))
959              (imagesp (symbol-plist (gnugo-f 'ispc)))
960              (w (/ (- avail-width
961                       (* size wmul)
962                       (if imagesp
963                           0
964                         (1- size))
965                       2                 ; between board and grid
966                       (if gridp
967                           (if under10p 2 4)
968                         0))
969                    2.0)))
970         (dolist (pair `((tpad . ,(if (and h (< 0 h))
971                                      `(display ,(make-string h 10))
972                                    '(invisible :nogrid)))
973                         (gpad . (display
974                                  (space :align-to
975                                         ,(+ w
976                                             2.0
977                                             (cond (imagesp (+ (* 0.5 wmul)
978                                                               (if under10p
979                                                                   -0.5
980                                                                 0.5)))
981                                                   (under10p 0)
982                                                   (t 1))))))
983                         (gspc . ,(when imagesp
984                                    `(display (space-width ,(- wmul 1.0)))))
985                         (lpad . ,(let ((d `(display (space :align-to ,w))))
986                                    ;; We distinguish between these cases to
987                                    ;; workaround a display bug whereby the
988                                    ;; `before-string' is omitted entirely (not
989                                    ;; rendered) when interacting w/ the text
990                                    ;; mode last-move left-paren for moves in
991                                    ;; column A.
992                                    (if gridp
993                                        `(before-string
994                                          ,(apply 'propertize " " d))
995                                      d)))
996                         (rpad . (display
997                                  (space :align-to ,(1- avail-width))))))
998           (setplist (gnugo-f (car pair)) (cdr pair)))))
999     ;; mode line update
1000     (let ((cur (gnugo-get :mode-line)))
1001       (unless (equal cur gnugo-mode-line)
1002         (setq cur gnugo-mode-line)
1003         (gnugo-put :mode-line cur)
1004         (gnugo-put :mode-line-form
1005           (cond ((stringp cur)
1006                  (setq cur (copy-sequence cur))
1007                  (let (acc cut c)
1008                    (while (setq cut (string-match "~[bwpmtu]" cur))
1009                      (aset cur cut ?%)
1010                      (setq cut (1+ cut) c (aref cur cut))
1011                      (aset cur cut ?s)
1012                      (push
1013                       `(,(intern (format "squig-%c" c))
1014                         ,(case c
1015                            (?b '(or (gnugo-get :black-captures) 0))
1016                            (?w '(or (gnugo-get :white-captures) 0))
1017                            (?p '(gnugo-other (gnugo-get :last-mover)))
1018                            (?t '(let ((ws (gnugo-get :waiting-start)))
1019                                   (if ws
1020                                       (cadr (time-since ws))
1021                                     "-")))
1022                            (?u '(or (gnugo-get :last-waiting) "-"))
1023                            (?m '(gnugo-move-history 'count))))
1024                       acc))
1025                    `(let ,(delete-dups (copy-sequence acc))
1026                       (format ,cur ,@(reverse (mapcar 'car acc))))))
1027                 (t cur))))
1028       (let ((form (gnugo-get :mode-line-form)))
1029         (setq mode-line-process
1030               (and form
1031                    ;; this dynamicism is nice but excessive in its wantonness
1032                    ;;- `(" [" (:eval ,form) "]")
1033                    ;; this dynamicism is ok because the user triggers it
1034                    (list (format " [%s]" (eval form))))))
1035       (force-mode-line-update))
1036     ;; last user move
1037     (when (setq last (gnugo-get :last-user-bpos))
1038       (gnugo-goto-pos last))))
1039
1040 ;;;---------------------------------------------------------------------------
1041 ;;; Game play actions
1042
1043 (defun gnugo-get-move-insertion-filter (proc string)
1044   (with-current-buffer (process-buffer proc)
1045     (let* ((so-far (gnugo-get :get-move-string))
1046            (full   (gnugo-put :get-move-string (concat so-far string))))
1047       (when (string-match "^= \\(.+\\)\n\n" full)
1048         (let ((pos-or-pass (match-string 1 full)))
1049           (gnugo-put :get-move-string nil)
1050           (gnugo-put :waitingp nil)
1051           (gnugo-push-move nil pos-or-pass)
1052           (let ((buf (current-buffer)))
1053             (let (inhibit-gnugo-refresh)
1054               (run-hooks 'gnugo-post-move-hook)
1055               (unless inhibit-gnugo-refresh
1056                 (with-current-buffer buf
1057                   (gnugo-refresh))))))))))
1058
1059 (defun gnugo-get-move (color)
1060   (gnugo-put :waitingp t)
1061   (set-process-filter (gnugo-get :proc) 'gnugo-get-move-insertion-filter)
1062   (gnugo-send-line (concat "genmove " color))
1063   (accept-process-output))
1064
1065 (defun gnugo-cleanup ()
1066   (when (gnugo-board-buffer-p)
1067     (unless (= 0 (buffer-size))
1068       (message "Thank you for playing GNU Go."))
1069     (mapc (lambda (sym)
1070             (setplist sym nil)          ; "...is next to fordliness." --Huxley
1071             (unintern sym))
1072           (append (gnugo-get :all-yy)
1073                   (mapcar 'gnugo-f
1074                           '(anim
1075                             tpad
1076                             gpad
1077                             gspc
1078                             lpad
1079                             rpad
1080                             ispc))))
1081     (setq gnugo-state nil)))
1082
1083 (defun gnugo-position ()
1084   (or (get-text-property (point) 'gnugo-position)
1085       (error "Not a proper position point")))
1086
1087 (defun gnugo-move ()
1088   "Make a move on the GNUGO Board buffer.
1089 The position is computed from current point.
1090 Signal error if done out-of-turn or if game-over.
1091 To start a game try M-x gnugo."
1092   (interactive)
1093   (gnugo-gate t)
1094   (let* ((buf (current-buffer))
1095          (pos (gnugo-position))
1096          (move (format "play %s %s" (gnugo-get :user-color) pos))
1097          (accept (cdr (gnugo-synchronous-send/return move))))
1098     (unless (= ?= (aref accept 0))
1099       (error "%s" accept))
1100     (gnugo-push-move t pos)             ; value always nil for non-pass move
1101     (let (inhibit-gnugo-refresh)
1102       (run-hooks 'gnugo-post-move-hook)
1103       (unless inhibit-gnugo-refresh
1104         (with-current-buffer buf
1105           (gnugo-refresh))))
1106     (with-current-buffer buf
1107       (gnugo-get-move (gnugo-get :gnugo-color)))))
1108
1109 (defun gnugo-mouse-move (e)
1110   "Do `gnugo-move' at mouse location."
1111   (interactive "@e")
1112   (mouse-set-point e)
1113   (when (looking-at "[.+]")
1114     (gnugo-move)))
1115
1116 (defun gnugo-pass ()
1117   "Make a pass on the GNUGO Board buffer.
1118 Signal error if done out-of-turn or if game-over.
1119 To start a game try M-x gnugo."
1120   (interactive)
1121   (gnugo-gate t)
1122   (let ((accept (cdr (gnugo-synchronous-send/return
1123                       (format "play %s PASS" (gnugo-get :user-color))))))
1124     (unless (= ?= (aref accept 0))
1125       (error "%s" accept)))
1126   (let ((donep (gnugo-push-move t "PASS"))
1127         (buf (current-buffer)))
1128     (let (inhibit-gnugo-refresh)
1129       (run-hooks 'gnugo-post-move-hook)
1130       (unless inhibit-gnugo-refresh
1131         (with-current-buffer buf
1132           (gnugo-refresh))))
1133     (unless donep
1134       (with-current-buffer buf
1135         (gnugo-get-move (gnugo-get :gnugo-color))))))
1136
1137 (defun gnugo-mouse-pass (e)
1138   "Do `gnugo-pass' at mouse location."
1139   (interactive "@e")
1140   (mouse-set-point e)
1141   (gnugo-pass))
1142
1143 (defun gnugo-resign ()
1144   (interactive)
1145   (gnugo-gate t)
1146   (if (not (y-or-n-p "Resign? "))
1147       (message "(not resigning)")
1148     (gnugo-push-move t "resign")
1149     (gnugo-refresh)))
1150
1151 (defun gnugo-animate-group (command)
1152   (message "Computing %s ..." command)
1153   (let* ((pos (gnugo-position))
1154          (stones (if (memq (char-after) '(?X ?O))
1155                      (gnugo-lsquery "%s %s" command pos)
1156                    (error "No stone at %s" pos))))
1157     (message "Computing %s ... %s in group." command (length stones))
1158     (setplist (gnugo-f 'anim) nil)
1159     (let* ((spec (let ((spec
1160                         ;; `(split-string gnugo-animation-string "" t)'
1161                         ;; works as well, for newer emacs versions
1162                         (delete "" (split-string gnugo-animation-string ""))))
1163                    (cond ((gnugo-get :display-using-images)
1164                           (let* ((yin (get-text-property (point) 'gnugo-yin))
1165                                  (yang (gnugo-yang (char-after)))
1166                                  (up (get (gnugo-yy yin yang t) 'display))
1167                                  (dn (get (gnugo-yy yin yang) 'display))
1168                                  flip-flop)
1169                             (mapcar (lambda (c)
1170                                       (if (setq flip-flop (not flip-flop))
1171                                           dn up))
1172                                     (mapcar 'string-to-char spec))))
1173                          (t spec))))
1174            (cell (list spec))
1175            (ovs (save-excursion
1176                   (mapcar (lambda (pos)
1177                             (gnugo-goto-pos pos)
1178                             (let* ((p (point))
1179                                    (ov (make-overlay p (1+ p))))
1180                               (overlay-put ov 'category (gnugo-f 'anim))
1181                               (overlay-put ov 'priority most-positive-fixnum)
1182                               ov))
1183                           stones))))
1184       (setplist (gnugo-f 'anim) (cons 'display cell))
1185       (while (and (cdr spec)            ; let last linger lest levity lost
1186                   (sit-for 0.08675309)) ; jenny jenny i got your number...
1187         (setcar cell (setq spec (cdr spec)))
1188         (set-buffer-modified-p t))
1189       (sit-for 5)
1190       (mapc 'delete-overlay ovs)
1191       t)))
1192
1193 (defun gnugo-display-group-data (command buffer-name)
1194   (message "Computing %s ..." command)
1195   (let ((data (cdr (gnugo-synchronous-send/return
1196                     (format "%s %s" command (gnugo-position))))))
1197     (switch-to-buffer buffer-name)
1198     (erase-buffer)
1199     (insert data))
1200   (message "Computing %s ... done." command))
1201
1202 (defun gnugo-worm-stones ()
1203   "In the GNUGO Board buffer, animate \"worm\" at current position.
1204 Signal error if done out-of-turn or if game-over.
1205 See variable `gnugo-animation-string' for customization."
1206   (interactive)
1207   (gnugo-gate)
1208   (gnugo-animate-group "worm_stones"))
1209
1210 (defun gnugo-worm-data ()
1211   "Display in another buffer data from \"worm\" at current position.
1212 Signal error if done out-of-turn or if game-over."
1213   (interactive)
1214   (gnugo-gate)
1215   (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1216
1217 (defun gnugo-dragon-stones ()
1218   "In the GNUGO Board buffer, animate \"dragon\" at current position.
1219 Signal error if done out-of-turn or if game-over.
1220 See variable `gnugo-animation-string' for customization."
1221   (interactive)
1222   (gnugo-gate)
1223   (gnugo-animate-group "dragon_stones"))
1224
1225 (defun gnugo-dragon-data ()
1226   "Display in another buffer data from \"dragon\" at current position.
1227 Signal error if done out-of-turn or if game-over."
1228   (interactive)
1229   (gnugo-gate)
1230   (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1231
1232 (defun gnugo-toggle-dead-group ()
1233   "In a GNUGO Board buffer, during game-over, toggle a group as dead.
1234 The group is selected from current position (point).  Signal error if
1235 not in game-over or if there is no group at that position.
1236
1237 In the context of GNU Go, a group is called a \"dragon\" and may be
1238 composed of more than one \"worm\" (set of directly-connected stones).
1239 It is unclear to the gnugo.el author whether or not GNU Go supports
1240  - considering worms as groups in their own right; and
1241  - toggling group aliveness via GTP.
1242 Due to these uncertainties, this command is only half complete; the
1243 changes you may see in Emacs are not propagated to the gnugo subprocess.
1244 Thus, GTP commands like `final_score' may give unexpected results.
1245
1246 If you are able to expose via GTP `change_dragon_status' in utils.c,
1247 you may consider modifying the `gnugo-toggle-dead-group' source code
1248 to enable full functionality."
1249   (interactive)
1250   (let ((game-over (or (gnugo-get :game-over)
1251                        (error "Sorry, game still in play")))
1252         (group (or (get-text-property (point) 'group)
1253                    (error "No stone at that position")))
1254         (now (current-time)))
1255     (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1256                                      (cadr now)))
1257     (let ((live (assq 'live game-over))
1258           (dead (assq 'dead game-over))
1259           bef now)
1260       (if (memq group live)
1261           (setq bef live now dead)
1262         (setq bef dead now live))
1263       (setcdr bef (delq group (cdr bef)))
1264       (setcdr now (cons group (cdr now)))
1265       ;; disabled permanently -- too wrong
1266       (when nil
1267         (flet ((populate (group)
1268                          (let ((color (caar group)))
1269                            (dolist (stone (cdr group))
1270                              (gnugo-query "play %s %s" color stone)))))
1271           (if (eq now live)
1272               (populate group)
1273             ;; drastic (and wrong -- clobbers capture info, etc)
1274             (gnugo-query "clear_board")
1275             (mapc 'populate (cdr live)))))
1276       ;; here is the desired interface (to be enabled Some Day)
1277       (when nil
1278         (gnugo-query "change_dragon_status %s %s"
1279                      (cadr group) (if (eq now live)
1280                                       'alive
1281                                     'dead)))))
1282   (save-excursion
1283     (gnugo-refresh)))
1284
1285 (defun gnugo-estimate-score ()
1286   "Display estimated score of a game of GNU Go.
1287 Output includes number of stones on the board and number of stones
1288 captured by each player, and the estimate of who has the advantage (and
1289 by how many stones)."
1290   (interactive)
1291   (message "Est.score ...")
1292   (let ((black (length (gnugo-lsquery "list_stones black")))
1293         (white (length (gnugo-lsquery "list_stones white")))
1294         (black-captures (gnugo-query "captures black"))
1295         (white-captures (gnugo-query "captures white"))
1296         (est (gnugo-query "estimate_score")))
1297     ;; might as well update this
1298     (gnugo-put :black-captures black-captures)
1299     (gnugo-put :white-captures white-captures)
1300     (message "Est.score ... B %s %s | W %s %s | %s"
1301              black black-captures white white-captures est)))
1302
1303 (defun gnugo-write-sgf-file (filename)
1304   "Save the game history to FILENAME (even if unfinished).
1305 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1306   (interactive "FWrite game as SGF file: ")
1307   (when (and (file-exists-p filename)
1308              (not (y-or-n-p "File exists. Continue? ")))
1309     (error "Not writing %s" filename))
1310   (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename))
1311
1312 (defun gnugo-read-sgf-file (filename)
1313   "Load the first game tree from FILENAME, a file in SGF format."
1314   (interactive "fSGF file to load: ")
1315   (when (file-directory-p filename)
1316     (error "Cannot load a directory (try a filename with extension .sgf)"))
1317   (let (ans play wait samep coll)
1318     ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1319     ;; todo: skip it altogether when confident about `gnugo/sgf-read-file'
1320     (unless (= ?= (aref (setq ans (cdr (gnugo-synchronous-send/return
1321                                         (format "loadsgf %s"
1322                                                 (expand-file-name filename)))))
1323                         0))
1324       (error "%s" ans))
1325     (setq play (substring ans 2)
1326           wait (gnugo-other play)
1327           samep (string= (gnugo-get :user-color) play))
1328     (gnugo-put :last-mover wait)
1329     (unless samep
1330       (gnugo-put :gnugo-color wait)
1331       (gnugo-put :user-color play))
1332     (gnugo-put :sgf-collection (setq coll (gnugo/sgf-read-file filename)))
1333     (gnugo-put :sgf-gametree
1334       (nth (let ((n (length coll)))
1335              ;; This is better:
1336              ;; (if (= 1 n)
1337              ;;     0
1338              ;;   (let* ((q (format "Which game? (1-%d)" n))
1339              ;;          (choice (1- (read-number q 1))))
1340              ;;     (if (and (< -1 choice) (< choice n))
1341              ;;         choice
1342              ;;       (message "(Selecting the first game)")
1343              ;;       0)))
1344              ;; but this is what we use (for now) to accomodate
1345              ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1346              (unless (= 1 n)
1347                (message "(Selecting the first game)"))
1348              0)
1349            coll))
1350     (let* ((tree (gnugo-get :sgf-gametree))
1351            (loc tree)
1352            (count 0)
1353            mem node play game-over)
1354       (while (setq node (car loc))
1355         (when (setq play (or (assq :B node)
1356                              (assq :W node)))
1357           ;; SGF[4] allows "" to mean PASS.  For now,
1358           ;; we normalize here instead of at the lower layer.
1359           (when (string= "" (cdr play))
1360             (setcdr play "tt"))
1361           (incf count)
1362           (push loc mem))
1363         (setq loc (cdr loc)))
1364       (gnugo-put :game-over
1365         (setq game-over
1366               (or (cdr (assq :RE (car tree)))
1367                   (and (cdr mem)
1368                        (equal '("tt" "tt")
1369                               (let ((order (if (string= "black" wait)
1370                                                '(:B :W)
1371                                              '(:W :B))))
1372                                 (mapcar (lambda (pk)
1373                                           (cdr (assq (funcall pk order)
1374                                                      (car (funcall pk mem)))))
1375                                         '(car cadr))))
1376                        'two-passes))))
1377       (gnugo-put :monkey
1378         (vector (or (car mem) (gnugo-get :sgf-gametree))
1379                 mem
1380                 count))
1381       (when (and game-over
1382                  ;; (maybe) todo: user var to inhibit (can be slow)
1383                  t)
1384         (gnugo-close-game nil game-over)))
1385     (gnugo-refresh t)
1386     (message "GNU Go %splays as %s, you as %s (%s)"
1387              (if samep "" "now ")
1388              wait play (if samep
1389                            "as before"
1390                          "NOTE: this is a switch!"))))
1391
1392 (defun gnugo-magic-undo (spec &optional noalt)
1393   "Undo moves on the GNUGO Board, based on SPEC, a string or number.
1394 If SPEC is a string in the form of a board position (e.g., \"T19\"),
1395 check that the position is occupied by a stone of the user's color,
1396 and if so, remove moves from the history until that position is clear.
1397 If SPEC is a positive number, remove exactly that many moves from the
1398 history, signaling an error if the history is exhausted before finishing.
1399 If SPEC is not recognized, signal \"bad spec\" error.
1400
1401 Refresh the board for each move undone.  If (in the case where SPEC is
1402 a number) after finishing, the color to play is not the user's color,
1403 schedule a move by GNU Go.
1404
1405 After undoing the move(s), schedule a move by GNU Go if it is GNU Go's
1406 turn to play.  Optional second arg NOALT non-nil inhibits this."
1407   (gnugo-gate)
1408   (let* ((n 0)
1409          (monkey (gnugo-get :monkey))
1410          (mem (aref monkey 1))
1411          (count (aref monkey 2))
1412          done ans)
1413     (cond ((and (numberp spec) (< 0 spec))
1414            (setq n spec done (lambda () (= 0 n))))
1415           ((string-match "^[a-z]" spec)
1416            (let ((pos (upcase spec)))
1417              (setq done `(lambda ()
1418                            (gnugo-goto-pos ,pos)
1419                            (memq (char-after) '(?. ?+))))
1420              (when (funcall done)
1421                (error "%s already clear" pos))
1422              (let ((u (gnugo-get :user-color)))
1423                (when (= (save-excursion
1424                           (gnugo-goto-pos pos)
1425                           (char-after))
1426                         (if (string= "black" u)
1427                             ?O
1428                           ?X))
1429                  (error "%s not occupied by %s" pos u)))))
1430           (t (error "Bad spec: %S" spec)))
1431     (when (gnugo-get :game-over)
1432       (gnugo-put :game-over nil))
1433     (while (not (funcall done))
1434       (setq ans (cdr (gnugo-synchronous-send/return "undo")))
1435       (unless (= ?= (aref ans 0))
1436         (error "%s" ans))
1437       (aset monkey 2 (decf count))
1438       (aset monkey 1 (setq mem (cdr mem)))
1439       (aset monkey 0 (or (car mem) (gnugo-get :sgf-gametree)))
1440       (gnugo-put :last-mover (gnugo-other (gnugo-get :last-mover)))
1441       (gnugo-merge-showboard-results)   ; all
1442       (gnugo-refresh)                   ; this
1443       (decf n)                          ; is
1444       (sit-for 0)))                     ; eye candy
1445   (let* ((ulastp (string= (gnugo-get :last-mover) (gnugo-get :user-color)))
1446
1447          (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1448     (gnugo-put :last-user-bpos (if (and ubpos (not (string= "PASS" ubpos)))
1449                                    ubpos
1450                                  (gnugo-get :center-position)))
1451     (gnugo-refresh t)
1452     ;; preserve restricted-functionality semantics (todo: remove restriction)
1453     (setcdr (aref (gnugo-get :monkey) 0) nil)
1454     (when (and ulastp (not noalt))
1455       (gnugo-get-move (gnugo-get :gnugo-color)))))
1456
1457 (defun gnugo-undo-one-move ()
1458   "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1459 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1460 See also `gnugo-undo-two-moves'."
1461   (interactive)
1462   (gnugo-gate)
1463   (gnugo-magic-undo 1 t))
1464
1465 (defun gnugo-undo-two-moves ()
1466   "Undo a pair of moves (GNU Go's and yours).
1467 However, if you are the last mover, undo only one move.
1468 Regardless, after undoing, it is your turn to play again."
1469   (interactive)
1470   (gnugo-gate)
1471   (gnugo-magic-undo (if (string= (gnugo-get :user-color)
1472                                  (gnugo-get :last-mover))
1473                         1
1474                       2)))
1475
1476 (defun gnugo-display-final-score ()
1477   "Display final score and other info in another buffer (when game over).
1478 If the game is still ongoing, Emacs asks if you wish to stop play (by
1479 making sure two \"pass\" moves are played consecutively, if necessary).
1480 Also, add the `:RE' SGF property to the root node of the game tree."
1481   (interactive)
1482   (unless (or (gnugo-get :game-over)
1483               (and (not (gnugo-get :waitingp))
1484                    (y-or-n-p "Game still in play. Stop play now? ")))
1485     (error "Sorry, game still in play"))
1486   (unless (gnugo-get :game-over)
1487     (flet ((pass (userp)
1488                  (message "Playing PASS for %s ..."
1489                           (gnugo-get (if userp :user-color :gnugo-color)))
1490                  (sit-for 1)
1491                  (gnugo-push-move userp "PASS")))
1492       (unless (pass t)
1493         (pass nil)))
1494     (gnugo-refresh)
1495     (sit-for 3))
1496   (let ((b=  "   Black = ")
1497         (w=  "   White = ")
1498         (res (let* ((node (car (aref (gnugo-get :monkey) 0)))
1499                     (event (and node (cdr (assq :EV node)))))
1500                (and event (string= "resignation" event)
1501                     (if (assq :B node) "black" "white"))))
1502         blurb result)
1503     (if res
1504         (setq blurb (list
1505                      (format "%s wins.\n"
1506                              (substring (if (= ?b (aref res 0)) w= b=)
1507                                         3 8))
1508                      "The game is over.\n"
1509                      (format "Resignation by %s.\n" res))
1510               result (concat (upcase (substring (gnugo-other res) 0 1))
1511                              "+Resign"))
1512       (message "Computing final score ...")
1513       (let* ((live   (cdr (assq 'live (gnugo-get :game-over))))
1514              (dead   (cdr (assq 'dead (gnugo-get :game-over))))
1515              (seed   (gnugo-get :scoring-seed))
1516              (terr-q (format "final_status_list %%s_territory %d" seed))
1517              (terr   "territory")
1518              (capt   "captures")
1519              (b-terr (length (gnugo-lsquery terr-q "black")))
1520              (w-terr (length (gnugo-lsquery terr-q "white")))
1521              (b-capt (string-to-number (gnugo-get :black-captures)))
1522              (w-capt (string-to-number (gnugo-get :white-captures)))
1523              (komi   (gnugo-treeroot :KM)))
1524         (setq blurb (list "The game is over.  Final score:\n")
1525               result (gnugo-query "final_score %d" seed))
1526         (cond ((string= "Chinese" (gnugo-treeroot :RU))
1527                (dolist (group live)
1528                  (let ((count (length (cdr group))))
1529                    (if (string= "black" (caar group))
1530                        (setq b-terr (+ b-terr count))
1531                      (setq w-terr (+ w-terr count)))))
1532                (dolist (group dead)
1533                  (let* ((color (caar group))
1534                         (count (length (cdr group))))
1535                    (if (string= "black" color)
1536                        (setq w-terr (+ count w-terr))
1537                      (setq b-terr (+ count b-terr)))))
1538                (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1539                (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1540                              w-terr terr komi 'komi (+ w-terr komi))
1541                      blurb))
1542               (t
1543                (dolist (group dead)
1544                  (let* ((color (caar group))
1545                         (adjust (* 2 (length (cdr group)))))
1546                    (if (string= "black" color)
1547                        (setq w-terr (+ adjust w-terr))
1548                      (setq b-terr (+ adjust b-terr)))))
1549                (push (format "%s%d %s + %s %s = %3.1f\n" b=
1550                              b-terr terr
1551                              b-capt capt
1552                              (+ b-terr b-capt))
1553                      blurb)
1554                (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1555                              w-terr terr
1556                              w-capt capt
1557                              komi 'komi
1558                              (+ w-terr w-capt komi))
1559                      blurb)))
1560         (push (if (string= "0" result)
1561                   "The game is a draw.\n"
1562                 (format "%s wins by %s.\n"
1563                         (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1564                         (substring result 2)))
1565               blurb)
1566         (message "Computing final score ... done")))
1567     ;; extra info
1568     (when (gnugo-get :game-end-time)
1569       (push "\n" blurb)
1570       (dolist (spec '(("Game start" . :game-start-time)
1571                       ("       end" . :game-end-time)))
1572         (push (format-time-string
1573                (concat (car spec) ": %Y-%m-%d %H:%M:%S %z\n")
1574                (gnugo-get (cdr spec)))
1575               blurb)))
1576     (setq blurb (apply 'concat (nreverse blurb)))
1577     (let* ((root (car (gnugo-get :sgf-gametree)))
1578            (cur (assq :RE root)))
1579       (if cur
1580           (setcdr cur result)
1581         (setcdr (last root) (list (cons :RE result)))))
1582     (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
1583     (erase-buffer)
1584     (insert blurb)))
1585
1586 ;;;---------------------------------------------------------------------------
1587 ;;; Command properties and gnugo-command
1588
1589 ;; GTP commands entered by the user are never issued directly to GNU Go;
1590 ;; instead, their behavior and output are controlled by the property
1591 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
1592 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
1593 ;;
1594 ;; :full -- completely interpret the command string; the value is a
1595 ;;          func that takes the list of words derived from splitting the
1596 ;;          command string (minus the command) and handles everything.
1597 ;;
1598 ;; :output -- either a keyword specifying the preferred output method:
1599 ;;              :message -- show output in minibuffer
1600 ;;              :discard -- sometimes you just don't care;
1601 ;;            or a function that takes one arg, the output string, and
1602 ;;            handles it completely.   default is to switch to buffer
1603 ;;            "*gnugo command output*" if the output has a newline,
1604 ;;            otherwise use `message'.
1605 ;;
1606 ;; :post-hook -- normal hook run after output processing (at the very end).
1607
1608 (defun gnugo-command (command)
1609   "Send the Go Text Protocol COMMAND (a string) to GNU Go.
1610 Output and Emacs behavior depend on which command is given (some
1611 commands are handled completely by Emacs w/o using the subprocess;
1612 some commands have their output displayed in specially prepared
1613 buffers or in the echo area; some commands are instrumented to do
1614 gnugo.el-specific housekeeping).
1615
1616 For example, for the command \"help\", Emacs visits the
1617 GTP command reference info page.
1618
1619 NOTE: At this time, GTP command handling specification is still
1620       incomplete.  Thus, some commands WILL confuse gnugo.el."
1621   (interactive "sCommand: ")
1622   (if (string= "" command)
1623       (message "(no command given)")
1624     (let* ((split (split-string command))
1625            (cmd (intern (car split)))
1626            (spec (get cmd :gnugo-gtp-command-spec))
1627            (full (plist-get spec :full))
1628            (last-message nil))
1629       (if full
1630           (funcall full (cdr split))
1631         (message "Doing %s ..." command)
1632         (let* ((ans (cdr (gnugo-synchronous-send/return command)))
1633                (where (plist-get spec :output)))
1634           (if (string-match "unknown.command" ans)
1635               (message ans)
1636             (cond ((functionp where) (funcall where ans))
1637                   ((eq :discard where) (message ""))
1638                   ((or (eq :message where)
1639                        (not (string-match "\n" ans)))
1640                    (message ans))
1641                   (t (switch-to-buffer "*gnugo command output*")
1642                      (erase-buffer)
1643                      (insert ans)
1644                      (message "Doing %s ... done." command)))
1645             (let ((hook
1646                    ;; do not elide this binding; `run-hooks' needs it
1647                    (plist-get spec :post-hook)))
1648               (run-hooks 'hook))))))))
1649
1650 ;;;---------------------------------------------------------------------------
1651 ;;; Major mode for interacting with a GNUGO subprocess
1652
1653 (put 'gnugo-board-mode 'mode-class 'special)
1654 (defun gnugo-board-mode ()
1655   "Major mode for playing GNU Go.
1656 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
1657 In this mode, keys do not self insert.  Default keybindings:
1658
1659   ?             View this help.
1660
1661   RET or SPC    Run `gnugo-move'.
1662
1663   q or Q        Quit (the latter without confirmation).
1664
1665   R             Resign.
1666
1667   u             Run `gnugo-undo-two-moves'.
1668
1669   U             Pass to `gnugo-magic-undo' either the board position
1670                 at point (if no prefix arg), or the prefix arg converted
1671                 to a number.  E.g., to undo 16 moves: `C-u C-u U' (see
1672                 `universal-argument'); to undo 42 moves: `M-4 M-2 U'.
1673
1674   C-l           Run `gnugo-refresh'.
1675
1676   _ or M-_      Bury the Board buffer (when the boss is near).
1677
1678   P             Run `gnugo-pass'.
1679
1680   i             Toggle display using XPM images (if supported).
1681
1682   w             Run `gnugo-worm-stones'.
1683   d             Run `gnugo-dragon-stones'.
1684
1685   W             Run `gnugo-worm-data'.
1686   D             Run `gnugo-dragon-data'.
1687
1688   t             Run `gnugo-toggle-dead-group'.
1689
1690   !             Run `gnugo-estimate-score'.
1691
1692   : or ;        Run `gnugo-command' (for GTP commands to GNU Go).
1693
1694   =             Display board position under point (if valid).
1695
1696   h             Run `gnugo-move-history'.
1697
1698   F             Run `gnugo-display-final-score'.
1699
1700   s             Run `gnugo-write-sgf-file'.
1701   or C-x C-w
1702   or C-x C-s
1703
1704   l             Run `gnugo-read-sgf-file'."
1705   (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
1706   (buffer-disable-undo)                 ; todo: undo undo undoing
1707   (kill-all-local-variables)
1708   (setq truncate-lines t)
1709   (use-local-map gnugo-board-mode-map)
1710   (set (make-local-variable 'font-lock-defaults)
1711        '(gnugo-font-lock-keywords t))
1712   (setq major-mode 'gnugo-board-mode)
1713   (setq mode-name "GNUGO Board")
1714   (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
1715   (set (make-local-variable 'gnugo-state)
1716        (make-hash-table :size (1- 42) :test 'eq))
1717   (add-to-invisibility-spec :nogrid)
1718   (mapc (lambda (prop)
1719           (gnugo-put prop nil))         ; todo: separate display/game aspects;
1720         '(:game-over                    ;       move latter to func `gnugo'
1721           :waitingp
1722           :last-waiting
1723           :black-captures
1724           :white-captures
1725           :mode-line
1726           :mode-line-form
1727           :display-using-images
1728           :xpms
1729           :local-xpms
1730           :all-yy))
1731   (let ((name (if (string-match "[ ]" gnugo-program)
1732                   (let ((p (substring gnugo-program 0 (match-beginning 0)))
1733                         (o (substring gnugo-program (match-end 0)))
1734                         (h (or (car gnugo-option-history) "")))
1735                     (when (string-match "--mode" o)
1736                       (error "Found \"--mode\" in `gnugo-program'"))
1737                     (when (and o (< 0 (length o))
1738                                h (< 0 (length o))
1739                                (or (< (length h) (length o))
1740                                    (not (string= (substring h 0 (length o))
1741                                                  o))))
1742                       (push (concat o " " h) gnugo-option-history))
1743                     p)
1744                 gnugo-program))
1745         (args (read-string "GNU Go options: "
1746                            (car gnugo-option-history)
1747                            'gnugo-option-history))
1748         (rules "Japanese")
1749         board-size user-color handicap komi minus-l infile)
1750     (mapc (lambda (x)
1751             (apply (lambda (var default opt &optional rx)
1752                      (set var
1753                           (or (when (string-match opt args)
1754                                 (let ((start (match-end 0)) s)
1755                                   (string-match (or rx "[0-9.]+") args start)
1756                                   (setq s (match-string 0 args))
1757                                   (if rx s (string-to-number s))))
1758                               default)))
1759                    x))
1760           '((board-size      19 "--boardsize")
1761             (user-color "black" "--color" "\\(black\\|white\\)")
1762             (handicap         0 "--handicap")
1763             (komi           0.0 "--komi")
1764             (minus-l        nil "\\([^-]\\|^\\)-l[ ]*" "[^ ]+")
1765             (infile         nil "--infile" "[ ]*[^ ]+")))
1766     (gnugo-put :user-color user-color)
1767     (when (string-match "--chinese-rules" args)
1768       (setq rules "Chinese"))
1769     (let ((proc-args (split-string args)))
1770       (gnugo-put :proc-args proc-args)
1771       (gnugo-put :proc (apply 'start-process "gnugo" nil name
1772                               "--mode" "gtp" "--quiet"
1773                               proc-args)))
1774     (when (or minus-l infile)
1775       (mapc (lambda (x)
1776               (apply (lambda (prop q)
1777                        (set prop (string-to-number (gnugo-query q))))
1778                      x))
1779             '((board-size "query_boardsize")
1780               (komi       "get_komi")
1781               (handicap   "get_handicap"))))
1782     (gnugo-put :diamond (substring (process-name (gnugo-get :proc)) 5))
1783     (gnugo-put :gnugo-color (gnugo-other (gnugo-get :user-color)))
1784     (gnugo-put :highlight-last-move-spec
1785       (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
1786     (gnugo-put :lparen-ov (make-overlay 1 1))
1787     (gnugo-put :rparen-ov (let ((ov (make-overlay 1 1)))
1788                             (overlay-put ov 'display ")")
1789                             ov))
1790     (gnugo-put :sgf-gametree (list (list '(:FF . 4) '(:GM . 1))))
1791     (let ((tree (gnugo-get :sgf-gametree)))
1792       (gnugo-put :sgf-collection (list tree))
1793       (gnugo-put :monkey (vector tree nil 0)))
1794     (let ((g-blackp (string= "black" (gnugo-get :gnugo-color))))
1795       (mapc (lambda (x) (apply 'gnugo-note x))
1796             `((:SZ ,board-size)
1797               (:DT ,(format-time-string "%Y-%m-%d"))
1798               (:RU ,rules)
1799               (:AP ("gnugo.el" . ,gnugo-version))
1800               (:KM ,komi)
1801               (,(if g-blackp :PW :PB) ,(user-full-name))
1802               (,(if g-blackp :PB :PW) ,(concat "GNU Go "
1803                                                (gnugo-query "version")))
1804               ,@(when (not (= 0 handicap))
1805                   `((:HA ,handicap)
1806                     (:AB ,(gnugo-lsquery "fixed_handicap %d" handicap)
1807                          nil t)))))))
1808   (set-process-sentinel (gnugo-get :proc) 'gnugo-sentinel)
1809   (set-process-buffer (gnugo-get :proc) (current-buffer))
1810   (gnugo-put :waiting-start (current-time))
1811   (gnugo-put :hmul 1)
1812   (gnugo-put :wmul 1)
1813   (run-hooks 'gnugo-board-mode-hook)
1814   (gnugo-refresh t))
1815
1816 ;;;---------------------------------------------------------------------------
1817 ;;; Entry point
1818
1819 ;;;###autoload
1820 (defun gnugo (&optional new-game)
1821   "Run gnugo in a buffer, or resume a game in progress.
1822 Prefix arg means skip the game-in-progress check and start a new
1823 game straight away.
1824
1825 You are queried for additional command-line options (Emacs supplies
1826 \"--mode gtp --quiet\" automatically).  Here is a list of options
1827 that gnugo.el understands and handles specially:
1828
1829     --boardsize num   Set the board size to use (5--19)
1830     --color <color>   Choose your color ('black' or 'white')
1831     --handicap <num>  Set the number of handicap stones (0--9)
1832
1833 If there is already a game in progress you may resume it instead of
1834 starting a new one.  See `gnugo-board-mode' documentation for more info."
1835   (interactive "P")
1836   (let* ((all (let (acc)
1837                 (dolist (buf (buffer-list))
1838                   (when (gnugo-board-buffer-p buf)
1839                     (push (cons (buffer-name buf) buf) acc)))
1840                 acc))
1841          (n (length all)))
1842     (if (and (not new-game)
1843              (< 0 n)
1844              (y-or-n-p (format "GNU Go game%s in progress, resume play? "
1845                                (if (= 1 n) "" "s"))))
1846         ;; resume
1847         (switch-to-buffer
1848          (cdr (if (= 1 n)
1849                   (car all)
1850                 (let ((sel (completing-read "Which one? " all nil t)))
1851                   (if (string= "" sel)
1852                       (car all)
1853                     (assoc sel all))))))
1854       ;; set up a new board
1855       (gnugo-board-mode)
1856       (let ((half (truncate (1+ (gnugo-treeroot :SZ)) 2)))
1857         (gnugo-goto-pos (format "A%d" half))
1858         (forward-char (* 2 (1- half)))
1859         (gnugo-put :last-user-bpos
1860           (gnugo-put :center-position
1861             (get-text-property (point) 'gnugo-position))))
1862       ;; first move
1863       (gnugo-put :game-start-time (current-time))
1864       (let ((g (gnugo-get :gnugo-color))
1865             (n (or (gnugo-treeroot :HA) 0))
1866             (u (gnugo-get :user-color)))
1867         (gnugo-put :last-mover g)
1868         (when (or (and (string= "black" u) (< 1 n))
1869                   (and (string= "black" g) (< n 2)))
1870           (gnugo-put :last-mover u)
1871           (gnugo-refresh t)
1872           (gnugo-get-move g))))))
1873
1874 ;;;---------------------------------------------------------------------------
1875 ;;; Load-time actions
1876
1877 (unless gnugo-board-mode-map
1878   (setq gnugo-board-mode-map (make-sparse-keymap))
1879   (suppress-keymap gnugo-board-mode-map)
1880   (mapc (lambda (pair)
1881           (define-key gnugo-board-mode-map (car pair) (cdr pair)))
1882         '(("?"        . describe-mode)
1883           ("\C-m"     . gnugo-move)
1884           (" "        . gnugo-move)
1885           ("P"        . gnugo-pass)
1886           ("R"        . gnugo-resign)
1887           ("q"        . (lambda () (interactive)
1888                           (if (or (gnugo-get :game-over)
1889                                   (y-or-n-p "Quit? "))
1890                               (kill-buffer nil)
1891                             (message "(not quitting)"))))
1892           ("Q"        . (lambda () (interactive)
1893                           (kill-buffer nil)))
1894           ("U"        . (lambda (x) (interactive "P")
1895                           (gnugo-magic-undo
1896                            (cond ((numberp x) x)
1897                                  ((consp x) (car x))
1898                                  (t (gnugo-position))))))
1899           ("u"        . gnugo-undo-two-moves)
1900           ("\C-l"     . gnugo-refresh)
1901           ("\M-_"     . bury-buffer)
1902           ("_"        . bury-buffer)
1903           ("h"        . gnugo-move-history)
1904           ("i"        . (lambda () (interactive)
1905                           (gnugo-toggle-image-display)
1906                           (save-excursion (gnugo-refresh))))
1907           ("w"        . gnugo-worm-stones)
1908           ("W"        . gnugo-worm-data)
1909           ("d"        . gnugo-dragon-stones)
1910           ("D"        . gnugo-dragon-data)
1911           ("t"        . gnugo-toggle-dead-group)
1912           ("g"        . gnugo-toggle-grid)
1913           ("!"        . gnugo-estimate-score)
1914           (":"        . gnugo-command)
1915           (";"        . gnugo-command)
1916           ("="        . (lambda () (interactive)
1917                           (message (gnugo-position))))
1918           ("s"        . gnugo-write-sgf-file)
1919           ("\C-x\C-s" . gnugo-write-sgf-file)
1920           ("\C-x\C-w" . gnugo-write-sgf-file)
1921           ("l"        . gnugo-read-sgf-file)
1922           ("F"        . gnugo-display-final-score)
1923           ;; mouse
1924           ([(down-mouse-1)] . gnugo-mouse-move)
1925           ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
1926           ([(down-mouse-3)] . gnugo-mouse-pass)
1927           ;; delving into the curiosities
1928           ("\C-c\C-p" . gnugo-describe-internal-properties))))
1929
1930 (unless (get 'help :gnugo-gtp-command-spec)
1931   (flet ((sget (x) (get x :gnugo-gtp-command-spec))
1932          (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
1933                                   (plist-put (sget cmd) prop val)))
1934          (add (cmd prop val) (jam cmd prop (let ((cur (plist-get
1935                                                        (sget cmd)
1936                                                        prop)))
1937                                              (append (delete val cur)
1938                                                      (list val)))))
1939          (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
1940                                    (let ((ls props))
1941                                      (while ls
1942                                        (funcall (if (eq :post-hook (car ls))
1943                                                     'add
1944                                                   'jam)
1945                                                 cmd (car ls) (cadr ls))
1946                                        (setq ls (cddr ls)))))))
1947
1948     (defgtp 'help :full
1949       (lambda (sel)
1950         (info "(gnugo)GTP command reference")
1951         (when sel (setq sel (intern (car sel))))
1952         (let (buffer-read-only pad cur spec output found)
1953           (flet ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
1954             (goto-char (point-min))
1955             (save-excursion
1956               (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
1957                                         (point-max) t)
1958                 (unless pad
1959                   (setq pad (make-string (- (match-beginning 1)
1960                                             (match-beginning 0))
1961                                          32)))
1962                 (when (plist-get
1963                        (setq spec
1964                              (get (setq cur (intern (match-string 1)))
1965                                   :gnugo-gtp-command-spec))
1966                        :full)
1967                   (note "handles this command completely"))
1968                 (when (setq output (plist-get spec :output))
1969                   (cond ((functionp output)
1970                          (note "handles the output specially"))
1971                         ((eq :discard output)
1972                          (note "discards the output"))
1973                         ((eq :message output)
1974                          (note "displays the output in the echo area"))))
1975                 (when (eq sel cur)
1976                   (setq found (match-beginning 0))))))
1977           (cond (found (goto-char found))
1978                 ((not sel))
1979                 (t (message "(no such command: %s)" sel))))))
1980
1981     (defgtp 'final_score :full
1982       (lambda (sel) (gnugo-display-final-score)))
1983
1984     (defgtp '(boardsize
1985               clear_board
1986               fixed_handicap)
1987       :output :discard
1988       :post-hook (lambda ()
1989                    (gnugo-put :game-over nil)
1990                    (gnugo-put :last-mover nil)
1991                    (gnugo-refresh t)))
1992
1993     (defgtp 'loadsgf :full
1994       (lambda (sel) (gnugo-read-sgf-file (car sel))))
1995
1996     (defgtp '(undo gg-undo) :full
1997       (lambda (sel) (gnugo-magic-undo
1998                      (let (n)
1999                        (cond ((not sel) 1)
2000                              ((< 0 (setq n (string-to-number (car sel)))) n)
2001                              (t (car sel)))))))))
2002
2003 (provide 'gnugo)
2004
2005 \f
2006 ;;;---------------------------------------------------------------------------
2007 ;;; The remainder of this file defines a simplified SGF-handling library.
2008 ;;; When/if it should start to attain generality, it should be split off into
2009 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2010 ;;; "gnugo/" prefix.
2011
2012 (defconst gnugo/sgf-*r4-properties*
2013   '((AB "Add Black"       setup list stone)
2014     (AE "Add Empty"       game  list point)
2015     (AN "Annotation"      game  simpletext)
2016     (AP "Application"     root  (simpletext . simpletext))
2017     (AR "Arrow"           -     list (point . point))
2018     (AS "Who adds stones" -     simpletext) ; (LOA)
2019     (AW "Add White"       setup list stone)
2020     (B  "Black"           move  move)
2021     (BL "Black time left" move  real)
2022     (BM "Bad move"        move  double)
2023     (BR "Black rank"      game  simpletext)
2024     (BT "Black team"      game  simpletext)
2025     (C  "Comment"         -     text)
2026     (CA "Charset"         root  simpletext)
2027     (CP "Copyright"       game  simpletext)
2028     (CR "Circle"          -     list point)
2029     (DD "Dim points"      -     elist point) ; (inherit)
2030     (DM "Even position"   -     double)
2031     (DO "Doubtful"        move  none)
2032     (DT "Date"            game  simpletext)
2033     (EV "Event"           game  simpletext)
2034     (FF "Fileformat"      root  [number (1 . 4)])
2035     (FG "Figure"          -     (or none (number . simpletext)))
2036     (GB "Good for Black"  -     double)
2037     (GC "Game comment"    game  text)
2038     (GM "Game"            root  [number (1 . 20)])
2039     (GN "Game name"       game  simpletext)
2040     (GW "Good for White"  -     double)
2041     (HA "Handicap"        game  number) ; (Go)
2042     (HO "Hotspot"         -     double)
2043     (IP "Initial pos."    game  simpletext) ; (LOA)
2044     (IT "Interesting"     move  none)
2045     (IY "Invert Y-axis"   game  simpletext)          ; (LOA)
2046     (KM "Komi"            game  real)                ; (Go)
2047     (KO "Ko"              move  none)
2048     (LB "Label"           -     list (point . simpletext))
2049     (LN "Line"            -     list (point . point))
2050     (MA "Mark"            -     list point)
2051     (MN "set move number" move  number)
2052     (N  "Nodename"        -     simpletext)
2053     (OB "OtStones Black"  move  number)
2054     (ON "Opening"         game  text)
2055     (OT "Overtime"        game  simpletext)
2056     (OW "OtStones White"  move  number)
2057     (PB "Player Black"    game  simpletext)
2058     (PC "Place"           game  simpletext)
2059     (PL "Player to play"  setup color)
2060     (PM "Print move mode" -     number) ; (inherit)
2061     (PW "Player White"    game  simpletext)
2062     (RE "Result"          game  simpletext)
2063     (RO "Round"           game  simpletext)
2064     (RU "Rules"           game  simpletext)
2065     (SE "Markup"          -     point)  ; (LOA)
2066     (SL "Selected"        -     list point)
2067     (SO "Source"          game  simpletext)
2068     (SQ "Square"          -     list point)
2069     (ST "Style"           root  [number (0 . 3)])
2070     (SU "Setup type"      game  simpletext) ; (LOA)
2071     (SZ "Size"            root  (or number (number . number)))
2072     (TB "Territory Black" -     elist point) ; (Go)
2073     (TE "Tesuji"          move  double)
2074     (TM "Timelimit"       game  real)
2075     (TR "Triangle"        -     list point)
2076     (TW "Territory White" -     elist point) ; (Go)
2077     (UC "Unclear pos"     -     double)
2078     (US "User"            game  simpletext)
2079     (V  "Value"           -     real)
2080     (VW "View"            -     elist point) ; (inherit)
2081     (W  "White"           move  move)
2082     (WL "White time left" move  real)
2083     (WR "White rank"      game  simpletext)
2084     (WT "White team"      game  simpletext)
2085     (LT "Lose on time"    setup simpletext))
2086   ;; r4-specific notes
2087   ;; - changed: DT FG LB RE RU SZ
2088   ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2089   "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2090
2091 (defun gnugo/sgf-read-file (filename)
2092   "Return the collection (list) of gametrees in SGF[4] file FILENAME."
2093   (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2094                       (put 'gnugo/sgf-*r4-properties* :keywords
2095                            (mapcar (lambda (full)
2096                             (cons (car full)
2097                                   (intern (format ":%s" (car full)))))
2098                                    gnugo/sgf-*r4-properties*))))
2099         (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2100                    (put 'gnugo/sgf-*r4-properties* :specs
2101                         (mapcar (lambda (full)
2102                          (cons (car full) (cdddr full)))
2103                                 gnugo/sgf-*r4-properties*)))))
2104     (flet ((sw () (skip-chars-forward " \t\n"))
2105            (x (end) (let ((beg (point))
2106                           (endp (case end
2107                                   (:end (lambda (char) (= ?\] char)))
2108                                   (:mid (lambda (char) (= ?\: char)))
2109                                   (t (lambda (char) (or (= ?\: char)
2110                                                         (= ?\] char))))))
2111                           c)
2112                       (while (not (funcall endp (setq c (char-after))))
2113                         (cond ((= ?\\ c)
2114                                (delete-char 1)
2115                                (if (eolp)
2116                                    (kill-line 1)
2117                                  (forward-char 1)))
2118                               ((looking-at "\\s-+")
2119                                (delete-region (point) (match-end 0))
2120                                (insert " "))
2121                               (t (forward-char 1))))
2122                       (buffer-substring-no-properties beg (point))))
2123            (one (type end) (unless (eq 'none type)
2124                              (forward-char 1)
2125                              (let ((s (x end)))
2126                                (case type
2127                                  ((stone point move simpletext color) s)
2128                                  ((number real double) (string-to-number s))
2129                                  ((text) s)
2130                                  (t (error "Unhandled type: %S" type))))))
2131            (val (spec) (cond ((symbolp spec)
2132                               (one spec :end))
2133                              ((vectorp spec)
2134                               ;; todo: check range here.
2135                               (one (aref spec 0) :end))
2136                              ((eq 'or (car spec))
2137                               (let ((v (one (cadr spec) t)))
2138                                 (if (= ?\] (char-after))
2139                                     v
2140                                   (forward-char 1)
2141                                   ;; todo: this assumes `spec' has the form
2142                                   ;;         (or foo (foo . bar))
2143                                   ;; i.e., foo is not rescanned.  e.g., `SZ'.
2144                                   ;; probably this assumption is consistent
2145                                   ;; w/ the SGF authors' desire to make the
2146                                   ;; parsing easy, but you never know...
2147                                   (cons v (one (cdaddr spec) :end)))))
2148                              (t (cons (one (car spec) :mid)
2149                                       (one (cdr spec) :end)))))
2150            (short (who) (when (eobp)
2151                           (error "Unexpected EOF while reading %s" who)))
2152            (atvalp () (= ?\[ (char-after)))
2153            (PROP () (let (name spec ltype)
2154                       (sw) (short 'property)
2155                       (when (looking-at "[A-Z]")
2156                         (setq name (read (current-buffer))
2157                               spec (cdr (assq name specs)))
2158                         (sw)
2159                         (cons
2160                          (cdr (assq name keywords))
2161                          (prog1 (if (= 1 (length spec))
2162                                     (val (car spec))
2163                                   (unless (memq (setq ltype (car spec))
2164                                                 '(elist list))
2165                                     (error "Bad spec: %S" spec))
2166                                   (if (and (eq 'elist ltype) (sw)
2167                                            (not (atvalp)))
2168                                       nil
2169                                     (let ((type (cadr spec))
2170                                           mo ls)
2171                                       (while (and (sw) (atvalp)
2172                                                   (setq mo (val type)))
2173                                         (push mo ls)
2174                                         (forward-char 1))
2175                                       (forward-char -1)
2176                                       (nreverse ls))))
2177                            (forward-char 1))))))
2178            (NODE () (let (prop props)
2179                       (sw) (short 'node)
2180                       (when (= ?\; (char-after))
2181                         (forward-char 1)
2182                         (while (setq prop (PROP))
2183                           (push prop props))
2184                         (nreverse props))))
2185            (TREE () (let (nodes)
2186                       (while (and (sw) (not (eobp)))
2187                         (case (char-after)
2188                           (?\; (push (NODE) nodes))
2189                           (?\( (forward-char 1)
2190                                (push (TREE) nodes))
2191                           (?\) (forward-char 1))))
2192                       (nreverse nodes))))
2193       (with-temp-buffer
2194         (insert-file-contents filename)
2195         (let (trees)
2196           (while (and (sw) (not (eobp)) (= 40 (char-after))) ; left paren
2197             (forward-char 1)
2198             (push (TREE) trees))
2199           (nreverse trees))))))
2200
2201 (defun gnugo/sgf-write-file (collection filename)
2202   ;; take responsibility for our actions
2203   (dolist (tree collection)
2204     (let* ((root (car tree))
2205            (who (assq :AP root))
2206            (fruit (cons "gnugo.el" gnugo-version)))
2207       (if who
2208           (setcdr who fruit)
2209         (setcdr (last root) (list (cons :AP fruit))))))
2210   ;; write it out
2211   (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2212         (specs (mapcar (lambda (full)
2213                          (cons (intern (format ":%s" (car full)))
2214                                (cdddr full)))
2215                        gnugo/sgf-*r4-properties*))
2216         p name v spec)
2217     ;; todo: escape special chars for `text' and `simpletext'.
2218     (flet ((>>one (v) (insert (format "[%s]" v)))
2219            (>>two (v) (insert (format "[%s:%s]" (car v) (cdr v))))
2220            (>>nl () (cond ((memq name aft-newline-appreciated)
2221                            (insert "\n"))
2222                           ((< 60 (current-column))
2223                            (save-excursion
2224                              (goto-char p)
2225                              (insert "\n"))))))
2226       (with-temp-buffer
2227         (dolist (tree collection)
2228           (insert "(")
2229           (dolist (node tree)
2230             (insert ";")
2231             (dolist (prop node)
2232               (setq p (point)
2233                     name (car prop)
2234                     v (cdr prop))
2235               (insert (substring (symbol-name name) 1))
2236               (cond ((not v))
2237                     ((and (consp v)
2238                           (memq (car (setq spec (cdr (assq name specs))))
2239                                 '(list elist)))
2240                      (>>nl)
2241                      (let ((>> (if (consp (cadr spec))
2242                                    '>>two
2243                                  '>>one)))
2244                        (dolist (little-v v)
2245                          (setq p (point)) (funcall >> little-v) (>>nl))))
2246                     ((consp v)
2247                      (>>two v) (>>nl))
2248                     (t
2249                      (>>one v) (>>nl)))))
2250           (insert ")\n"))
2251         (write-file filename)))))
2252
2253 ;;; gnugo.el ends here