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