]> code.delx.au - gnu-emacs-elpa/blob - packages/gnugo/gnugo.el
[gnugo int] Avoid superfluous ‘gnugo-other’ call.
[gnu-emacs-elpa] / packages / gnugo / gnugo.el
1 ;;; gnugo.el --- play GNU Go in a buffer -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
4
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
6 ;; Version: 2.3.1
7 ;; Package-Requires: ((ascii-art-to-unicode "1.5"))
8
9 ;; This program is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation, either version 3 of the License, or
12 ;; (at your option) any later version.
13
14 ;; This program is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22 ;;; Commentary:
23
24 ;; Playing
25 ;; -------
26 ;;
27 ;; This file provides the command `gnugo' which allows you to play the game of
28 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
29 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
30 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
31 ;; Go" to refer to the process object created by running the external program.
32 ;;
33 ;; At the start of a new game, you can pass additional command-line arguments
34 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
35 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
36 ;; both komi and handicap.
37 ;;
38 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
39 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
40 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
41 ;; back through an arbitrary stone that you played, place the cursor on a
42 ;; stone and type `U' (note: uppercase).
43 ;;
44 ;; There are a great many other commands. Other keybindings are described in
45 ;; the `gnugo-board-mode' documentation, which you may view with the command
46 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
47 ;; the last move and who is currently to play. Capture counts and other info
48 ;; are shown on the mode line immediately following the major mode name.
49 ;;
50 ;; While GNU Go is pondering its next move, certain commands that rely on its
51 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
52 ;; is normal. When it is your turn again you may retry the command. In the
53 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
54 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
55 ;;
56 ;; If GNU Go should crash during a game the mode line will show "no process".
57 ;; Please report the event to the GNU Go maintainers so that they can improve
58 ;; the program.
59 ;;
60 ;;
61 ;; Meta-Playing (aka Customizing)
62 ;; ------------------------------
63 ;;
64 ;; Customization is presently limited to
65 ;; vars: `gnugo-program'
66 ;; `gnugo-animation-string'
67 ;; `gnugo-mode-line'
68 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
69 ;; `gnugo-xpms'
70 ;; normal hooks: `gnugo-board-mode-hook'
71 ;; `gnugo-frolic-mode-hook'
72 ;; `gnugo-start-game-hook'
73 ;; `gnugo-post-move-hook'
74 ;; and the keymap: `gnugo-board-mode-map'
75 ;;
76 ;; The variable `gnugo-xpms' is a special case. To set it you need to load
77 ;; gnugo-xpms.el (http://www.emacswiki.org) or some other library w/ congruent
78 ;; interface.
79
80 ;;; Code:
81
82 (eval-when-compile (require 'cl)) ; use the source luke!
83 (require 'ascii-art-to-unicode) ; for `aa2u'
84 (require 'time-date) ; for `time-subtract'
85
86 ;;;---------------------------------------------------------------------------
87 ;;; Political arts
88
89 (defconst gnugo-version "2.3.1"
90 "Version of gnugo.el currently loaded.
91 This follows a MAJOR.MINOR.PATCH scheme.")
92
93 ;;;---------------------------------------------------------------------------
94 ;;; Variables for the uninquisitive programmer
95
96 (defvar gnugo-program "gnugo"
97 "Name of the GNU Go program (executable file).
98 \\[gnugo] validates this using `executable-find'.
99 This program must accept command line args:
100 --mode gtp --quiet
101 For more information on GTP and GNU Go, please visit:
102 <http://www.gnu.org/software/gnugo>")
103
104 (defvar gnugo-board-mode-map nil
105 "Keymap for GNUGO Board mode.")
106
107 (defvar gnugo-frolic-mode-map nil
108 "Keymap for GNUGO Frolic mode.")
109
110 (defvar gnugo-board-mode-hook nil
111 "Hook run when entering GNUGO Board mode.")
112
113 (defvar gnugo-start-game-hook nil
114 "Normal hook run immediately before the first move of the game.
115 To find out who is to move first, use `gnugo-current-player'.
116 See also `gnugo-board-mode'.")
117
118 (defvar gnugo-post-move-hook nil
119 "Normal hook run after a move and before the board is refreshed.
120 Initially, when `run-hooks' is called, the current buffer is the GNUGO
121 Board buffer of the game. Hook functions that switch buffers must take
122 care not to call (directly or indirectly through some other function)
123 `gnugo-put' or `gnugo-get' after the switch.")
124
125 (defvar gnugo-animation-string
126 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
127 (concat jam jam jam jam jam
128 ;; "SECRET MESSAGE HERE"
129 blink blink blink blink blink blink blink blink
130 ;; Playing go is like fighting ignorance: when you think you have
131 ;; surrounded something by knowing it very well it often turns
132 ;; out that in the time you spent deepening this understanding,
133 ;; other areas of ignorance have surrounded you.
134 spin spin spin spin spin spin spin spin spin
135 ;; Playing go is not like fighting ignorance: what one person
136 ;; knows many people may come to know; knowledge does not build
137 ;; solely move by move. Wisdom, on the other hand...
138 yada yada yada))
139 "String whose individual characters are used for animation.
140 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
141 render the stones in their respective result groups as the first character
142 in the string, then the next, and so on.")
143
144 (defvar gnugo-mode-line "~b ~w :~m :~u"
145 "A `mode-line-format'-compliant value for GNUGO Board mode.
146 If a single string, the following special escape sequences are
147 replaced with their associated information:
148 ~b,~w black,white captures (a number)
149 ~p current player (black or white)
150 ~m move number
151 ~t time waiting for the current move
152 ~u time taken for the Ultimate (most recent) move
153 The times are in seconds, or \"-\" if that information is not available.
154 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
155
156 (defvar gnugo-X-face 'font-lock-string-face
157 "Name of face to use for X (black) stones.")
158
159 (defvar gnugo-O-face 'font-lock-builtin-face
160 "Name of face to use for O (white) stones.")
161
162 (defvar gnugo-grid-face 'default
163 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
164
165 ;;;---------------------------------------------------------------------------
166 ;;; Variables for the inquisitive programmer
167
168 (defconst gnugo-font-lock-keywords
169 '(("X" . gnugo-X-face)
170 ("O" . gnugo-O-face))
171 "Font lock keywords for `gnugo-board-mode'.")
172
173 (defvar gnugo-option-history nil)
174
175 (defvar gnugo-state nil) ; hint: C-c C-p
176
177 (eval-when-compile
178 (defvar gnugo-xpms nil))
179
180 (defvar gnugo-frolic-parent-buffer nil)
181 (defvar gnugo-frolic-origin nil)
182
183 (defvar gnugo-btw nil)
184
185 ;;;---------------------------------------------------------------------------
186 ;;; Support functions
187
188 (defsubst gnugo--mkht (&rest etc)
189 (apply 'make-hash-table :test 'eq etc))
190
191 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
192 (compare-strings s1 beg1 nil s2 beg2 nil))
193
194 (defun gnugo-put (key value)
195 "Associate move/game/board-specific property KEY with VALUE.
196
197 There are many properties, each named by a keyword, that record and control
198 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
199 of properties, stored in the hash table `gnugo-state'. Here we document
200 some of the more stable properties. You may wish to use them as part of
201 a `gnugo-post-move-hook' function, for example. Be careful to preserve
202 the current buffer as `gnugo-state' is made into a buffer-local variable.
203 NOTE: In the following, \"see foo\" actually means \"see foo source or
204 you may never really understand to any degree of personal satisfaction\".
205
206 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
207
208 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
209
210 :game-over -- nil until game over at which time its value is set to
211 the alist `((live GROUP ...) (dead GROUP ...))'
212
213 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
214 a simple list of one or more gametrees, updated in
215 conjunction w/ :sgf-gametree and :monkey
216
217 :sgf-gametree -- one of the gametrees in :sgf-collection
218
219 :monkey -- vector of two elements:
220 MEM, a pointer to one of the branches in the gametree;
221 BIDX, the index of the \"current branch\"
222
223 :gnugo-color -- either \"black\" or \"white\"
224 :user-color
225 :last-mover
226
227 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
228 :waiting-start
229
230 :black-captures -- these are strings since gnugo.el doesn't do anything
231 :white-captures w/ the information besides display it in the mode line;
232 gory details in functions `gnugo-propertize-board-buffer'
233 and `gnugo-merge-showboard-results' (almost more effort
234 than they are worth!)
235
236 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
237 `gnugo-toggle-image-display' and `gnugo-refresh',
238 as well as gnugo-xpms.el (available elsewhere)
239
240 :all-yy -- list of 46 keywords used as the `category' text property
241 (so that their plists, typically w/ property `display' or
242 `do-not-display') are consulted by the Emacs display engine;
243 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
244 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
245
246 :paren-ov -- a pair (left and right) of overlays shuffled about to indicate
247 the last move; only one is used when displaying using images
248
249 :last-user-bpos -- board position; keep the hapless human happy
250
251 As things stabilize probably more info will be added to this docstring."
252 (declare (indent 1))
253 (puthash key value gnugo-state))
254
255 (defun gnugo-get (key)
256 "Return the move/game/board-specific value for KEY.
257 See `gnugo-put'."
258 (gethash key gnugo-state))
259
260 (defun gnugo--forget (&rest keys)
261 (dolist (key keys)
262 (remhash key gnugo-state)))
263
264 (defun gnugo--instant-karma (color add/del)
265 (assert (string= color (gnugo-get :user-color)))
266 (setq gnugo-btw (when add/del
267 " Abd"))
268 (force-mode-line-update))
269
270 (defsubst gnugo--tree-mnum (tree)
271 (aref tree 1))
272
273 (defsubst gnugo--tree-ends (tree)
274 (aref tree 0))
275
276 (defsubst gnugo--set-tree-ends (tree ls)
277 (aset tree 0 (apply 'vector ls))
278 (gnugo--tree-ends tree))
279
280 (defun gnugo--root-node (&optional tree)
281 (aref (or tree (gnugo-get :sgf-gametree))
282 2))
283
284 (defun gnugo-describe-internal-properties ()
285 "Pretty-print `gnugo-state' properties in another buffer.
286 Handle the big, slow-to-render, and/or uninteresting ones specially."
287 (interactive)
288 (let ((buf (current-buffer))
289 (d (gnugo-get :diamond))
290 acc)
291 (loop for key being the hash-keys of gnugo-state
292 using (hash-values val)
293 do (push (cons key
294 (case key
295 ((:xpms :local-xpms)
296 (format "hash: %X (%d images)"
297 (sxhash val)
298 (length val)))
299 (:sgf-collection
300 (length val))
301 (:sgf-gametree
302 (list (hash-table-count
303 (gnugo--tree-mnum val))
304 (gnugo--root-node val)
305 (gnugo--tree-ends val)))
306 (:monkey
307 (let ((mem (aref val 0)))
308 (list (aref val 1)
309 (car mem))))
310 (t val)))
311 acc))
312 (switch-to-buffer (get-buffer-create
313 (format "%s*GNUGO Board Properties*"
314 (gnugo-get :diamond))))
315 (erase-buffer)
316 (emacs-lisp-mode)
317 (setq truncate-lines t)
318 (save-excursion
319 (pp acc
320 (current-buffer))
321 (goto-char (point-min))
322 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
323 (if (string= "" d)
324 ".+\n"
325 ""))))
326 (while (re-search-forward rx (point-max) t)
327 (let ((pos (get-text-property (string-to-number (match-string 1))
328 'gnugo-position buf)))
329 (delete-region (+ 2 (match-beginning 0)) (point))
330 (insert (format " %S" pos))))))
331 (message "%d properties" (length acc))))
332
333 (defun gnugo-board-buffer-p (&optional buffer)
334 "Return non-nil if BUFFER is a GNUGO Board buffer."
335 (eq 'gnugo-board-mode
336 (buffer-local-value
337 'major-mode
338 (or buffer (current-buffer)))))
339
340 (defun gnugo-board-user-play-ok-p (&optional buffer)
341 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
342 (with-current-buffer (or buffer (current-buffer))
343 (and gnugo-state (not (gnugo-get :waiting)))))
344
345 (defsubst gnugo--blackp (string)
346 (string= "black" string))
347
348 (defun gnugo-other (color)
349 (if (gnugo--blackp color) "white" "black"))
350
351 (defun gnugo-current-player ()
352 "Return the current player, either \"black\" or \"white\"."
353 (gnugo-other (gnugo-get :last-mover)))
354
355 (defsubst gnugo--prop<-color (color)
356 (if (gnugo--blackp color) :B :W))
357
358 (defun gnugo-gate (&optional in-progress-p)
359 (unless (gnugo-board-buffer-p)
360 (user-error "Wrong buffer -- try M-x gnugo"))
361 (unless (gnugo-get :proc)
362 (user-error "No \"gnugo\" process!"))
363 (destructuring-bind (&optional color . suggestion)
364 (gnugo-get :waiting)
365 (when color
366 (apply 'user-error
367 "%s -- please wait for \"(%s to play)\""
368 (if suggestion
369 (list "Still thinking"
370 color)
371 (list "Not your turn yet"
372 (gnugo-other color))))))
373 (when (and in-progress-p (gnugo-get :game-over))
374 (user-error "Sorry, game over")))
375
376 (defun gnugo-sentinel (proc string)
377 (let ((status (process-status proc)))
378 (when (memq status '(exit signal))
379 (let ((buf (process-buffer proc)))
380 (when (buffer-live-p buf)
381 (with-current-buffer buf
382 (setq mode-line-process
383 (list " [%s ("
384 (propertize (car (split-string string))
385 'face 'font-lock-warning-face)
386 ")]"))
387 (when (eq proc (gnugo-get :proc))
388 (gnugo--forget :proc))))))))
389
390 (defun gnugo--begin-exchange (proc filter line)
391 (declare (indent 2)) ; good time, for a rime
392 ; nice style, for a wile...
393 (set-process-filter proc filter)
394 (process-send-string proc line)
395 (process-send-string proc "\n"))
396
397 (defun gnugo--q (fmt &rest args)
398 "Send formatted command \"FMT ARGS...\"; wait for / return response.
399 The response is a string whose first two characters indicate the
400 status of the command. See also `gnugo-query'."
401 (let ((slow (gnugo-get :waiting))
402 (proc (gnugo-get :proc)))
403 (when slow
404 (user-error "Sorry, still waiting for %s to %s"
405 (car slow) (if (cdr slow)
406 "receive a suggestion"
407 "play")))
408 (process-put proc :incomplete t)
409 (process-put proc :srs "") ; synchronous return stash
410 (gnugo--begin-exchange
411 proc (lambda (proc string)
412 (let ((full (concat (process-get proc :srs)
413 string)))
414 (process-put proc :srs full)
415 (unless (numberp (gnugo--compare-strings
416 full (max 0 (- (length full)
417 2))
418 "\n\n" nil))
419 (process-put proc :incomplete nil))))
420 (if (null args)
421 fmt
422 (apply #'format fmt args)))
423 (while (process-get proc :incomplete)
424 (accept-process-output proc 30))
425 (prog1 (substring (process-get proc :srs) 0 -2)
426 (process-put proc :srs ""))))
427
428 (defsubst gnugo--no-worries (string)
429 (= ?= (aref string 0)))
430
431 (defun gnugo--q/ue (fmt &rest args)
432 (let ((ans (apply 'gnugo--q fmt args)))
433 (unless (gnugo--no-worries ans)
434 (user-error "%s" ans))
435 (substring ans 2)))
436
437 (defun gnugo-query (message-format &rest args)
438 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
439 Return a string that omits the first two characters (corresponding
440 to the status indicator in the Go Text Protocol). Use this function
441 when you are sure the command cannot fail."
442 (substring (apply 'gnugo--q message-format args)
443 2))
444
445 (defun gnugo--nquery (cmd)
446 (string-to-number (gnugo-query cmd)))
447
448 (defun gnugo-lsquery (message-format &rest args)
449 (split-string (apply 'gnugo-query message-format args)))
450
451 (defsubst gnugo--count-query (fmt &rest args)
452 (length (apply 'gnugo-lsquery fmt args)))
453
454 (defsubst gnugo--root-prop (prop &optional tree)
455 (cdr (assq prop (gnugo--root-node tree))))
456
457 (defun gnugo--set-root-prop (prop value &optional tree)
458 (let* ((root (gnugo--root-node tree))
459 (cur (assq prop root)))
460 (if cur
461 (setcdr cur value)
462 (push (cons prop value)
463 (cdr (last root))))))
464
465 (defun gnugo-goto-pos (pos)
466 "Move point to board position POS, a letter-number string."
467 (goto-char (point-min))
468 (forward-line (- (1+ (gnugo-get :SZ))
469 (string-to-number (substring pos 1))))
470 (forward-char 1)
471 (forward-char (+ (if (= 32 (following-char)) 1 2)
472 (* 2 (- (let ((letter (aref pos 0)))
473 (if (> ?I letter)
474 letter
475 (1- letter)))
476 ?A)))))
477
478 (defun gnugo-f (frag)
479 (intern (format ":gnugo-%s%s-props" (gnugo-get :diamond) frag)))
480
481 (defun gnugo-yang (c)
482 (cdr (assq c '((?+ . hoshi)
483 (?. . empty)
484 (?X . (bmoku . bpmoku))
485 (?O . (wmoku . wpmoku))))))
486
487 (defun gnugo-yy (yin yang &optional momentaryp)
488 (gnugo-f (format "%d-%s"
489 yin (cond ((and (consp yang) momentaryp) (cdr yang))
490 ((consp yang) (car yang))
491 (t yang)))))
492
493 (defun gnugo-toggle-image-display ()
494 (unless (and (fboundp 'display-images-p) (display-images-p))
495 (user-error "Display does not support images, sorry"))
496 (require 'gnugo-xpms)
497 (unless (and (boundp 'gnugo-xpms) gnugo-xpms)
498 (user-error "Could not load `gnugo-xpms', sorry"))
499 (let ((fresh (or (gnugo-get :local-xpms) gnugo-xpms)))
500 (unless (eq fresh (gnugo-get :xpms))
501 (gnugo-put :xpms fresh)
502 (gnugo--forget :all-yy)))
503 (let* ((new (not (gnugo-get :display-using-images)))
504 (act (if new 'display 'do-not-display)))
505 (mapc (lambda (yy)
506 (setcar (symbol-plist yy) act))
507 (or (gnugo-get :all-yy)
508 (gnugo-put :all-yy
509 (prog1 (mapcar (lambda (ent)
510 (let* ((k (car ent))
511 (yy (gnugo-yy (cdr k) (car k))))
512 (setplist yy `(not-yet ,(cdr ent)))
513 yy))
514 (gnugo-get :xpms))
515 (gnugo-put :imul
516 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
517 'not-yet)))))))
518 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
519 (gnugo-put :highlight-last-move-spec
520 (if new
521 '((lambda (p)
522 (get (gnugo-yy (get-text-property p 'gnugo-yin)
523 (get-text-property p 'gnugo-yang)
524 t)
525 'display))
526 0 delete-overlay)
527 (gnugo-get :default-highlight-last-move-spec)))
528 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
529 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
530 (mapc 'delete-overlay (cdar group))
531 (setcdr (car group) nil))
532 (gnugo-put :mul (if new
533 (gnugo-get :imul)
534 '(1 . 1)))
535 (gnugo-put :display-using-images new)))
536
537 (defun gnugo-toggle-grid ()
538 "Turn the grid around the board on or off."
539 (interactive)
540 (funcall (if (memq :nogrid buffer-invisibility-spec)
541 'remove-from-invisibility-spec
542 'add-to-invisibility-spec)
543 :nogrid)
544 (save-excursion (gnugo-refresh)))
545
546 (defun gnugo-propertize-board-buffer ()
547 (erase-buffer)
548 (insert (substring (gnugo--q "showboard") 3))
549 (let* ((grid-props (list 'invisible :nogrid
550 'font-lock-face gnugo-grid-face))
551 (%gpad (gnugo-f 'gpad))
552 (%gspc (gnugo-f 'gspc))
553 (%lpad (gnugo-f 'lpad))
554 (%rpad (gnugo-f 'rpad))
555 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
556 (size (gnugo-get :SZ))
557 (size-string (number-to-string size)))
558 (goto-char (point-min))
559 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
560 (skip-chars-forward " ")
561 (put-text-property (1- (point)) (point) 'category %gpad)
562 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
563 (forward-char 1)
564 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
565 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
566 (let* ((row (match-string-no-properties 1))
567 (edge (match-end 0))
568 (other-edge (+ edge (* 2 size) -1))
569 (right-empty (+ other-edge (length row) 1))
570 (top-p (string= size-string row))
571 (bot-p (string= "1" row)))
572 (let* ((nL (- edge 1 (length size-string)))
573 (nR (- edge 1))
574 (ov (make-overlay nL nR (current-buffer) t)))
575 (add-text-properties nL nR grid-props)
576 ;; We redundantly set `invisible' in the overlay to workaround
577 ;; a display bug whereby text *following* the overlaid text is
578 ;; displayed with the face of the overlaid text, but only when
579 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
580 ;; This has something to do w/ the bletcherous `before-string'.
581 (overlay-put ov 'invisible :nogrid)
582 (overlay-put ov 'category %lpad))
583 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
584 ((< other-edge p))
585 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
586 (truncate (- p edge) 2))
587 row))
588 (yin (let ((A-p (= edge p))
589 (Z-p (= (1- other-edge) p)))
590 (cond ((and top-p A-p) 1)
591 ((and top-p Z-p) 3)
592 ((and bot-p A-p) 7)
593 ((and bot-p Z-p) 9)
594 (top-p 2)
595 (bot-p 8)
596 (A-p 4)
597 (Z-p 6)
598 (t 5))))
599 (yang (gnugo-yang (char-after p))))
600 (add-text-properties p (1+ p)
601 `(gnugo-position
602 ,position
603 gnugo-yin
604 ,yin
605 gnugo-yang
606 ,yang
607 category
608 ,(gnugo-yy yin yang)
609 front-sticky
610 (gnugo-position gnugo-yin))))
611 (unless (= (1- other-edge) p)
612 (add-text-properties (1+ p) (+ 2 p) ispc-props)
613 (put-text-property p (+ 2 p) 'intangible ival)))
614 (add-text-properties (1+ other-edge) right-empty grid-props)
615 (goto-char right-empty)
616 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
617 (let ((prop (if (string= "WH" (match-string 1))
618 :white-captures
619 :black-captures))
620 (beg (match-beginning 2))
621 (end (match-end 2)))
622 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
623 (gnugo-put prop (match-string-no-properties 2))))
624 (end-of-line)
625 (put-text-property right-empty (point) 'category %rpad)
626 (forward-char 1)))
627 (add-text-properties (1- (point)) (point-max) grid-props)
628 (skip-chars-forward " ")
629 (put-text-property (1- (point)) (point) 'category %gpad)
630 (put-text-property (point) (progn (end-of-line) (point))
631 'category %gspc)))
632
633 (defun gnugo-merge-showboard-results ()
634 (let ((aft (substring (gnugo--q "showboard") 3))
635 (adj 1) ; string to buffer position adjustment
636
637 (sync "[0-9]* stones$")
638 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
639 ;; restrictive a condition that fails in the case of:
640 ;;
641 ;; (before)
642 ;; ... WHITE has captured 1 stones
643 ;; ^
644 ;; (after)
645 ;; ... WHITE has captured 14 stones
646 ;; ^
647 ;;
648 ;; where the after count has more digits than the before count,
649 ;; but shares the same leading digits. In this case, the result
650 ;; of `compare-strings' points to the SPC following the before
651 ;; count (indicated by caret in this example).
652
653 (bef (buffer-substring-no-properties (point-min) (point-max)))
654 (bef-start 0) (bef-idx 0)
655 (aft-start 0) (aft-idx 0)
656 aft-sync-backtrack mis inc cut new very-strange
657
658 (inhibit-read-only t))
659 (while (numberp (setq mis (gnugo--compare-strings
660 bef bef-start
661 aft aft-start)))
662 (setq aft-sync-backtrack nil
663 inc (if (cl-minusp mis)
664 (- (+ 1 mis))
665 (- mis 1))
666 bef-idx (+ bef-start inc)
667 aft-idx (+ aft-start inc)
668 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
669 (match-end 0)
670 (1+ bef-idx))
671 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
672 (let ((peek (1- aft-idx)))
673 (while (not (= 32 (aref aft peek)))
674 (setq peek (1- peek)))
675 (setq aft-sync-backtrack (1+ peek))))
676 (match-end 0)
677 (1+ aft-idx))
678 cut (+ bef-idx adj
679 (if aft-sync-backtrack
680 (- aft-sync-backtrack aft-idx)
681 0)))
682 (goto-char cut)
683 (if aft-sync-backtrack
684 (let* ((asb aft-sync-backtrack)
685 (l-p (get-text-property cut :gnugo-cf))
686 (old-len (car l-p))
687 (capprop (cdr l-p))
688 (keep (text-properties-at cut)))
689 (setq new (substring aft asb (string-match " " aft asb)))
690 (plist-put keep :gnugo-cf (cons (length new) capprop))
691 (gnugo-put capprop new)
692 (delete-char old-len)
693 (insert (apply 'propertize new keep))
694 (incf adj (- (length new) old-len)))
695 (setq new (aref aft aft-idx))
696 (insert-and-inherit (char-to-string new))
697 (let ((yin (get-text-property cut 'gnugo-yin))
698 (yang (gnugo-yang new)))
699 (add-text-properties cut (1+ cut)
700 `(gnugo-yang
701 ,yang
702 category
703 ,(gnugo-yy yin yang))))
704 (delete-char 1)
705 ;; do this last to avoid complications w/ font lock
706 ;; (this also means we cannot include `intangible' in `front-sticky')
707 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
708 (put-text-property cut (1+ cut) 'intangible very-strange))))))
709
710 (defsubst gnugo--move-prop (node)
711 (or (assq :B node)
712 (assq :W node)))
713
714 (defun gnugo--as-pos-func ()
715 (lexical-let ((size (gnugo-get :SZ)))
716 ;; rv
717 (lambda (cc)
718 (if (string= "" cc)
719 "PASS"
720 (let ((col (aref cc 0)))
721 (format "%c%d"
722 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
723 (- size (- (aref cc 1) ?a))))))))
724
725 (defsubst gnugo--resignp (string)
726 (string= "resign" string))
727
728 (defsubst gnugo--passp (string)
729 (string= "PASS" string))
730
731 (defun gnugo-move-history (&optional rsel color)
732 "Determine and return the game's move history.
733 Optional arg RSEL controls side effects and return value.
734 If nil, display the history in the echo area as \"(N moves)\"
735 followed by the space-separated list of moves. When called
736 interactively with a prefix arg (i.e., RSEL is `(4)'), display
737 similarly, but suffix with the mover (either \":B\" or \":W\").
738 RSEL may also be a symbol that selects what to return:
739 car -- the most-recent move
740 cadr -- the next-to-most-recent move
741 two -- the last two moves as a list, oldest last
742 bpos -- the last stone on the board placed by COLOR
743 For all other values of RSEL, do nothing and return nil."
744 (interactive "P")
745 (let* ((monkey (gnugo-get :monkey))
746 (mem (aref monkey 0))
747 (as-pos (gnugo--as-pos-func))
748 acc node mprop move)
749 (cl-flet*
750 ((as-pos-maybe (x) (if (gnugo--resignp x)
751 x
752 (funcall as-pos x)))
753 (remem () (setq node (pop mem)
754 mprop (gnugo--move-prop node)))
755 (next (byp) (when (remem)
756 (setq move (as-pos-maybe (cdr mprop)))
757 (push (if byp
758 (format "%s%s" move (car mprop))
759 move)
760 acc)))
761 (nn () (next nil))
762 (tell () (message "(%d moves) %s"
763 (length acc)
764 (mapconcat 'identity (nreverse acc) " ")))
765 (finish (byp) (while mem (next byp)) (tell)))
766 (pcase rsel
767 (`(4) (finish t))
768 (`nil (finish nil))
769 (`car (car (nn)))
770 (`cadr (nn) (car (nn)))
771 (`two (nn) (nn) acc)
772 (`bpos (loop with prop = (gnugo--prop<-color color)
773 while mem
774 when (and (remem)
775 (eq prop (car mprop))
776 (setq move (cdr mprop))
777 ;; i.e., "normal CC" position
778 (= 2 (length move)))
779 return (funcall as-pos move)))
780 (_ nil)))))
781
782 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
783 "A special mode for manipulating a GNUGO gametree.
784
785 \\{gnugo-frolic-mode-map}"
786 (setq truncate-lines t)
787 (buffer-disable-undo))
788
789 (defun gnugo-frolic-quit ()
790 "Kill GNUGO Frolic buffer and switch to its parent buffer."
791 (interactive)
792 (let ((bye (current-buffer)))
793 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
794 gnugo-frolic-parent-buffer))
795 (kill-buffer bye)))
796
797 (defun gnugo-frolic-return-to-origin ()
798 "Move point to the board's current position."
799 (interactive)
800 (if (not gnugo-frolic-origin)
801 (message "No origin")
802 (goto-char gnugo-frolic-origin)
803 (recenter (- (count-lines (line-beginning-position)
804 (point-max))))))
805
806 (defun gnugo-frolic-in-the-leaves ()
807 "Display the game tree in a *GNUGO Frolic* buffer.
808 This looks something like:
809
810 1 B -- E7 E7 E7 E7
811 2 W -- K10 K10 K10 K10
812 3 B -- E2 E2 E2 E2
813 4 W -- J3 J3 J3 J3
814 5 B -- A6 A6 A6 A6
815 6 W -- C9 C9 C9 C9
816
817 ├─────┬─────┐
818 │ │ │
819 7 B -- H7 !B8 C8 C8
820
821 ├─────┐
822 │ │
823 8 W -- D9 D9 D9 E9
824 9 B -- H8 H8
825 10 W -- PASS PASS
826 11 B -- H5 PASS
827 12 W -- PASS
828 13 B -- *PASS
829
830 with 0, 1, ... N (in this case N is 3) in the header line
831 to indicate the branches. Branch 0 is the \"main line\".
832 Point (* in this example) indicates the current position,
833 \"!\" indicates comment properties (e.g., B8, branch 1),
834 and moves not actually on the game tree (e.g., E7, branch 3)
835 are dimmed. Type \\[describe-mode] in that buffer for details."
836 (interactive)
837 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
838 "*GNUGO Frolic*")))
839 (from (or gnugo-frolic-parent-buffer
840 (current-buffer)))
841 ;; todo: use defface once we finally succumb to ‘customize’
842 (dimmed-node-face (list :inherit 'default
843 :foreground "gray50"))
844 (tree (gnugo-get :sgf-gametree))
845 (ends (copy-sequence (gnugo--tree-ends tree)))
846 (mnum (gnugo--tree-mnum tree))
847 (seen (gnugo--mkht))
848 (soil (gnugo--mkht))
849 (width (length ends))
850 (lanes (number-sequence 0 (1- width)))
851 (monkey (gnugo-get :monkey))
852 (as-pos (gnugo--as-pos-func))
853 (at (car (aref monkey 0)))
854 (bidx (aref monkey 1))
855 (valid (map 'vector (lambda (end)
856 (gethash (car end) mnum))
857 ends))
858 (max-move-num (apply 'max (append valid nil)))
859 (inhibit-read-only t)
860 finish)
861 (cl-flet
862 ((on (node)
863 (gethash node seen))
864 (emph (s face)
865 (propertize s 'face face))
866 (fsi (properties fmt &rest args)
867 (insert (apply 'propertize
868 (apply 'format fmt args)
869 properties))))
870 ;; breathe in
871 (loop
872 for bx below width
873 do (loop
874 with fork
875 for node in (aref ends bx)
876 do (if (setq fork (on node))
877 (cl-flet
878 ((tip-p (bix)
879 ;; todo: ignore non-"move" nodes
880 (eq node (car (aref ends bix))))
881 (link (other)
882 (pushnew other (gethash node soil))))
883 (unless (tip-p bx)
884 (unless (tip-p fork)
885 (link fork))
886 (link bx)))
887 (puthash node bx seen))
888 until fork))
889 ;; breathe out
890 (switch-to-buffer buf)
891 (gnugo-frolic-mode)
892 (erase-buffer)
893 (setq header-line-format
894 (lexical-let ((full (concat
895 (make-string 11 ?\s)
896 (mapconcat (lambda (n)
897 (format "%-5s" n))
898 lanes
899 " "))))
900 `((:eval
901 (funcall
902 ,(lambda ()
903 (cl-flet
904 ((sp (w) (propertize
905 " " 'display
906 `(space :width ,w))))
907 (concat
908 (when (eq 'left scroll-bar-mode)
909 (let ((w (or scroll-bar-width
910 (frame-parameter
911 nil 'scroll-bar-width)))
912 (cw (frame-char-width)))
913 (sp (if w
914 (/ w cw)
915 2))))
916 (let ((fc (fringe-columns 'left t)))
917 (unless (zerop fc)
918 (sp fc)))
919 (condition-case nil
920 (substring full (window-hscroll))
921 (error ""))))))))))
922 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
923 (set (make-local-variable 'gnugo-state)
924 (buffer-local-value 'gnugo-state from))
925 (loop
926 with props
927 for n ; move number
928 from max-move-num downto 1
929 do (setq props (list 'n n))
930 do
931 (loop
932 with (move forks br)
933 initially (progn
934 (goto-char (point-min))
935 (fsi props
936 "%3d %s -- "
937 n (aref ["W" "B"] (logand 1 n))))
938 for bx below width
939 do (let* ((node (unless (< (aref valid bx) n)
940 ;; todo: ignore non-"move" nodes
941 (pop (aref ends bx))))
942 (zow (list* 'bx bx props))
943 (ok (when node
944 (= bx (on node))))
945 (comment (when ok
946 (cdr (assq :C node))))
947 (s (cond ((not node) "")
948 ((not (setq move (gnugo--move-prop node))) "-")
949 (t (funcall as-pos (cdr move))))))
950 (when comment
951 (push comment zow)
952 (push 'help-echo zow))
953 (when (and ok (setq br (gethash node soil)))
954 (push (cons bx (sort br '<))
955 forks))
956 (fsi zow
957 "%c%-5s"
958 (if comment ?! ?\s)
959 (cond ((and (eq at node)
960 (or ok (= bx bidx)))
961 (when (= bx bidx)
962 (setq finish (point-marker)))
963 (emph s (list :inherit 'default
964 :foreground (frame-parameter
965 nil 'cursor-color))))
966 ((not ok)
967 (emph s dimmed-node-face))
968 (t s))))
969 finally do
970 (when (progn (fsi props "\n")
971 (setq forks (nreverse forks)))
972 (let* ((margin (make-string 11 ?\s))
973 (heads (mapcar #'car forks))
974 (tails (mapcar #'cdr forks)))
975 (cl-flet*
976 ((spaced (lanes func)
977 (mapconcat func lanes " "))
978 ;; live to play ~ ~ ()
979 ;; play to learn (+) (-) . o O
980 ;; learn to live --ttn .M. _____U
981 (dashed (lanes func) ;;; _____ ^^^^
982 (mapconcat func lanes "-----"))
983 (cnxn (lanes set)
984 (spaced lanes (lambda (bx)
985 (if (memq bx set)
986 "|"
987 " "))))
988 (pad-unless (condition)
989 (if condition
990 ""
991 " "))
992 (edge (set)
993 (insert margin
994 (cnxn lanes set)
995 "\n")))
996 (edge heads)
997 (loop with bef
998 for ls on forks
999 do (let* ((one (car ls))
1000 (yes (append
1001 ;; "aft" heads
1002 (mapcar 'car (cdr ls))
1003 ;; ‘bef’ tails
1004 (apply 'append (mapcar 'cdr bef))))
1005 (ord (sort one '<))
1006 (beg (car ord))
1007 (end (car (last ord))))
1008 (cl-flet
1009 ((also (b e) (cnxn (number-sequence b e)
1010 yes)))
1011 (insert
1012 margin
1013 (also 0 (1- beg))
1014 (pad-unless (zerop beg))
1015 (dashed (number-sequence beg end)
1016 (lambda (bx)
1017 (cond ((memq bx ord) "+")
1018 ((memq bx yes) "|")
1019 (t "-"))))
1020 (pad-unless (>= end width))
1021 (also (1+ end) (1- width))
1022 "\n"))
1023 (push one bef)))
1024 (edge (apply 'append tails))
1025 (aa2u (line-beginning-position
1026 (- (1+ (length forks))))
1027 (point))))))))
1028 (when finish
1029 (set (make-local-variable 'gnugo-frolic-origin) finish)
1030 (gnugo-frolic-return-to-origin))))
1031
1032 (defun gnugo--awake (how)
1033 ;; Valid HOW elements:
1034 ;; require-valid-branch
1035 ;; (line . numeric)
1036 ;; (line . move-string)
1037 ;; Invalid elements blissfully ignored. :-D
1038 (let* ((tree (gnugo-get :sgf-gametree))
1039 (ends (gnugo--tree-ends tree))
1040 (width (length ends))
1041 (monkey (gnugo-get :monkey))
1042 (line (case (cdr (assq 'line how))
1043 (numeric
1044 (count-lines (point-min) (line-beginning-position)))
1045 (move-string
1046 (save-excursion
1047 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1048 (match-string 0))))
1049 (t nil)))
1050 (col (current-column))
1051 (a (unless (> 10 col)
1052 (let ((try (/ (- col 10)
1053 6)))
1054 (unless (<= width try)
1055 try))))
1056 (rv (list a)))
1057 (when (memq 'require-valid-branch how)
1058 (unless a
1059 (user-error "No branch here")))
1060 (loop with omit = (cdr (assq 'omit how))
1061 for (name . value) in `((line . ,line)
1062 (bidx . ,(aref monkey 1))
1063 (monkey . ,monkey)
1064 (width . ,width)
1065 (ends . ,ends)
1066 (tree . ,tree))
1067 do (unless (memq name omit)
1068 (push value rv)))
1069 rv))
1070
1071 (defmacro gnugo--awakened (how &rest body)
1072 (declare (indent 1))
1073 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1074 with ls = (list 'a)
1075 for name in '(line bidx monkey
1076 width ends
1077 tree)
1078 do (unless (memq name omit)
1079 (push name ls))
1080 finally return ls)
1081 (gnugo--awake ',how)
1082 ,@body))
1083
1084 (defsubst gnugo--move-to-bcol (bidx)
1085 (move-to-column (+ 10 (* 6 bidx))))
1086
1087 (defun gnugo--swiz (direction &optional blunt)
1088 (gnugo--awakened (require-valid-branch
1089 (omit tree)
1090 (line . numeric))
1091 (let* ((b (cond ((numberp blunt)
1092 (unless (and (< -1 blunt)
1093 (< blunt width))
1094 (user-error "No such branch: %s" blunt))
1095 blunt)
1096 (t (mod (+ direction a) width))))
1097 (flit (if blunt (lambda (n)
1098 (cond ((= n a) b)
1099 ((= n b) a)
1100 (t n)))
1101 (lambda (n)
1102 (mod (+ direction n) width))))
1103 (was (copy-sequence ends))
1104 (new-bidx (funcall flit bidx)))
1105 (loop for bx below width
1106 do (aset ends (funcall flit bx)
1107 (aref was bx)))
1108 (unless (= new-bidx bidx)
1109 (aset monkey 1 new-bidx))
1110 (gnugo-frolic-in-the-leaves)
1111 (goto-char (point-min))
1112 (forward-line line)
1113 (gnugo--move-to-bcol b))))
1114
1115 (defun gnugo-frolic-exchange-left ()
1116 "Exchange the current branch with the one to its left."
1117 (interactive)
1118 (gnugo--swiz -1 t))
1119
1120 (defun gnugo-frolic-rotate-left ()
1121 "Rotate all branches left."
1122 (interactive)
1123 (gnugo--swiz -1))
1124
1125 (defun gnugo-frolic-exchange-right ()
1126 "Exchange the current branch with the one to its right."
1127 (interactive)
1128 (gnugo--swiz 1 t))
1129
1130 (defun gnugo-frolic-rotate-right ()
1131 "Rotate all branches right."
1132 (interactive)
1133 (gnugo--swiz 1))
1134
1135 (defun gnugo-frolic-set-as-main-line ()
1136 "Make the current branch the main line."
1137 (interactive)
1138 (gnugo--swiz nil 0))
1139
1140 (defun gnugo-frolic-prune-branch ()
1141 "Remove the current branch from the gametree.
1142 This fails if there is only one branch in the tree.
1143 This fails if the monkey is on the current branch
1144 \(a restriction that will probably be lifted Real Soon Now\)."
1145 (interactive)
1146 (gnugo--awakened (require-valid-branch
1147 (line . move-string))
1148 ;; todo: define meaningful eviction semantics; remove restriction
1149 (when (= a bidx)
1150 (user-error "Cannot prune with monkey on branch"))
1151 (when (= 1 width)
1152 (user-error "Cannot prune last remaining branch"))
1153 (let ((new (append ends nil)))
1154 ;; Explicit ignorance avoids byte-compiler warning.
1155 (ignore (pop (nthcdr a new)))
1156 (gnugo--set-tree-ends tree new))
1157 (when (< a bidx)
1158 (aset monkey 1 (decf bidx)))
1159 (gnugo-frolic-in-the-leaves)
1160 (when line
1161 (goto-char (point-min))
1162 (search-forward line)
1163 (gnugo--move-to-bcol (min a (- width 2))))))
1164
1165 (defun gnugo--sideways (backwards n)
1166 (gnugo--awakened ((omit tree ends monkey bidx line))
1167 (gnugo--move-to-bcol (mod (if backwards
1168 (- (or a width) n)
1169 (+ (or a -1) n))
1170 width))))
1171
1172 (defun gnugo-frolic-backward-branch (&optional n)
1173 "Move backward N (default 1) branches."
1174 (interactive "p")
1175 (gnugo--sideways t n))
1176
1177 (defun gnugo-frolic-forward-branch (&optional n)
1178 "Move forward N (default 1) branches."
1179 (interactive "p")
1180 (gnugo--sideways nil n))
1181
1182 (defun gnugo--vertical (n direction)
1183 (when (> 0 n)
1184 (setq n (- n)
1185 direction (- direction)))
1186 (gnugo--awakened ((line . numeric)
1187 (omit tree ends width monkey bidx))
1188 (let ((stop (if (> 0 direction)
1189 0
1190 (max 0 (1- (count-lines (point-min)
1191 (point-max))))))
1192 (col (unless a
1193 (current-column))))
1194 (loop while (not (= line stop))
1195 do (loop do (progn
1196 (forward-line direction)
1197 (incf line direction))
1198 until (get-text-property (point) 'n))
1199 until (zerop (decf n)))
1200 (if a
1201 (gnugo--move-to-bcol a)
1202 (move-to-column col)))))
1203
1204 (defun gnugo-frolic-previous-move (&optional n)
1205 "Move to the Nth (default 1) previous move."
1206 (interactive "p")
1207 (gnugo--vertical n -1))
1208
1209 (defun gnugo-frolic-next-move (&optional n)
1210 "Move to the Nth (default 1) next move."
1211 (interactive "p")
1212 (gnugo--vertical n 1))
1213
1214 (defun gnugo-boss-is-near ()
1215 "Do `bury-buffer' until the current one is not a GNU Board."
1216 (interactive)
1217 (while (gnugo-board-buffer-p)
1218 (bury-buffer)))
1219
1220 (defsubst gnugo--no-regrets (monkey ends)
1221 (eq (aref ends (aref monkey 1))
1222 (aref monkey 0)))
1223
1224 (defun gnugo--as-cc-func ()
1225 (lexical-let ((size (gnugo-get :SZ)))
1226 (lambda (pos)
1227 (let* ((col (aref pos 0))
1228 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1229 (two (+ ?a (- size (string-to-number
1230 (substring pos 1))))))
1231 (format "%c%c" one two)))))
1232
1233 (defun gnugo--decorate (node &rest plist)
1234 (loop with tp = (last node)
1235 with fruit
1236 while plist
1237 do (setf
1238 fruit (list (cons ; DWR: LtR OoE assumed.
1239 (pop plist)
1240 (pop plist)))
1241 (cdr tp) fruit
1242 tp fruit)))
1243
1244 (defun gnugo-close-game (end-time resign)
1245 (gnugo-put :game-end-time end-time)
1246 (let ((now (or end-time (current-time))))
1247 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1248 (cadr now))))
1249 (gnugo-put :game-over
1250 (if (or (eq t resign)
1251 (and (stringp resign)
1252 (string-match "[BW][+][Rr]esign" resign)))
1253 (cl-flet
1254 ((ls (color) (mapcar
1255 (lambda (x)
1256 (cons (list color)
1257 (split-string x)))
1258 (split-string
1259 (gnugo-query "worm_stones %s" color)
1260 "\n"))))
1261 (let ((live (append (ls "black") (ls "white"))))
1262 `((live ,@live)
1263 (dead))))
1264 (let ((dd (gnugo-query "dragon_data"))
1265 (start 0) mem color ent live dead)
1266 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1267 dd start)
1268 (setq mem (match-string 1 dd)
1269 color (match-string 2 dd)
1270 start (match-end 0)
1271 ent (cons (list color)
1272 (sort (gnugo-lsquery "dragon_stones %s" mem)
1273 'string<)))
1274 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1275 dd start)
1276 (if (match-string 2 dd)
1277 (push ent live)
1278 (push ent dead))
1279 (setq start (match-end 0)))
1280 `((live ,@live)
1281 (dead ,@dead))))))
1282
1283 (defun gnugo--unclose-game ()
1284 (gnugo--forget :game-over ; all those in -close-game
1285 :scoring-seed
1286 :game-end-time)
1287 (let* ((root (gnugo--root-node))
1288 (cur (assq :RE root)))
1289 (when cur
1290 (assert (not (eq cur (car root))) nil
1291 ":RE at head of root node: %S"
1292 root)
1293 (delq cur root))))
1294
1295 (defun gnugo-push-move (who move)
1296 (let* ((simple (booleanp who))
1297 (ucolor (gnugo-get :user-color))
1298 (color (if simple
1299 (if who
1300 ucolor
1301 (gnugo-get :gnugo-color))
1302 who))
1303 (start (gnugo-get :waiting-start))
1304 (now (current-time))
1305 (resignp (gnugo--resignp move))
1306 (passp (gnugo--passp move))
1307 (head (gnugo-move-history 'car))
1308 (onep (and head (gnugo--passp head)))
1309 (donep (or resignp (and onep passp))))
1310 (unless resignp
1311 (gnugo--q/ue "play %s %s" color move))
1312 (unless passp
1313 (gnugo-merge-showboard-results))
1314 (gnugo-put :last-mover color)
1315 (when (if simple
1316 who
1317 (string= ucolor color))
1318 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1319 ;; update :sgf-gametree and :monkey
1320 (let* ((property (gnugo--prop<-color color))
1321 (pair (cons property (cond (resignp move)
1322 (passp "")
1323 (t (funcall (gnugo--as-cc-func)
1324 move)))))
1325 (fruit (list pair))
1326 (monkey (gnugo-get :monkey))
1327 (mem (aref monkey 0))
1328 (tip (car mem))
1329 (tree (gnugo-get :sgf-gametree))
1330 (ends (gnugo--tree-ends tree))
1331 (mnum (gnugo--tree-mnum tree))
1332 (count (length ends))
1333 (tip-move-num (gethash tip mnum))
1334 (bidx (aref monkey 1)))
1335 ;; Detect déjà-vu. That is, when placing "A", avoid:
1336 ;;
1337 ;; X---Y---A new
1338 ;; \
1339 ;; --A---B old
1340 ;;
1341 ;; (such "variations" do not actually vary!) in favor of:
1342 ;;
1343 ;; X---Y---A new
1344 ;; \
1345 ;; --B old
1346 ;;
1347 ;; This linear search loses for multiple ‘old’ w/ "A",
1348 ;; a very unusual (but not invalid, sigh) situation.
1349 (loop
1350 with (bx previous)
1351 for i
1352 ;; Start with latest / highest likelihood for hit.
1353 ;; (See "to the right" comment, below.)
1354 from (if (gnugo--no-regrets monkey ends)
1355 1
1356 0)
1357 below count
1358 if (setq bx (mod (+ bidx i) count)
1359 previous
1360 (loop with node
1361 for m on (aref ends bx)
1362 while (< tip-move-num
1363 (gethash (setq node (car m))
1364 mnum))
1365 if (eq mem (cdr m))
1366 return
1367 (when (equal pair (assq property node))
1368 m)
1369 finally return
1370 nil))
1371 ;; yes => follow
1372 return
1373 (progn
1374 (unless (= bidx bx)
1375 (rotatef (aref ends bidx)
1376 (aref ends bx)))
1377 (setq mem previous))
1378 ;; no => construct
1379 finally do
1380 (progn
1381 (unless (gnugo--no-regrets monkey ends)
1382 (setq ends (gnugo--set-tree-ends
1383 tree (let ((ls (append ends nil)))
1384 ;; copy old to the right of new
1385 (push mem (nthcdr bidx ls))
1386 ls))))
1387 (puthash fruit (1+ (gethash tip mnum)) mnum)
1388 (push fruit mem)
1389 (aset ends bidx mem)))
1390 (setf (aref monkey 0) mem))
1391 (when start
1392 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1393 (when donep
1394 (gnugo-close-game now resignp))
1395 (gnugo-put :waiting-start (and (not donep) now))
1396 donep))
1397
1398 (defun gnugo-venerate (yin yang)
1399 (let* ((fg-yy (gnugo-yy yin yang))
1400 (fg-disp (or (get fg-yy 'display)
1401 (get fg-yy 'do-not-display)))
1402 (fg-data (plist-get (cdr fg-disp) :data))
1403 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1404 (bg-disp (or (get bg-yy 'display)
1405 (get bg-yy 'do-not-display)))
1406 (bg-data (plist-get (cdr bg-disp) :data))
1407 (bop (lambda (s)
1408 (let* ((start 0)
1409 (ncolors
1410 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1411 (setq start (match-end 0))
1412 (string-to-number (match-string 1 s)))))
1413 (while (and (not (cl-minusp ncolors))
1414 (string-match ",\n" s start))
1415 (setq start (match-end 0)
1416 ncolors (1- ncolors)))
1417 (string-match "\"" s start)
1418 (match-end 0))))
1419 (new (copy-sequence fg-data))
1420 (lx (length fg-data))
1421 (sx (funcall bop fg-data))
1422 (sb (funcall bop bg-data))
1423 (color-key (aref new sx))) ; blech, heuristic
1424 (while (< sx lx)
1425 (when (and (not (= color-key (aref new sx)))
1426 (cl-plusp (random 4)))
1427 (aset new sx (aref bg-data sb)))
1428 (incf sx)
1429 (incf sb))
1430 (create-image new 'xpm t :ascent 'center)))
1431
1432 (defun gnugo-refresh (&optional nocache)
1433 "Update GNUGO Board buffer display.
1434 While a game is in progress, parenthesize the last-played stone (no parens
1435 for pass). If the buffer is currently displayed in the selected window,
1436 recenter the board (presuming there is extra space in the window). Update
1437 the mode line. Lastly, move point to the last position played by the user,
1438 if that move was not a pass.
1439
1440 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1441 be slow. (This should normally be unnecessary; specify it only if the display
1442 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1443 its move."
1444 (interactive "P")
1445 (let* ((move (gnugo-move-history 'car))
1446 (game-over (gnugo-get :game-over))
1447 (inhibit-read-only t)
1448 window last)
1449 (when (and nocache (not (gnugo-get :waiting)))
1450 (gnugo-propertize-board-buffer))
1451 ;; last move
1452 (when move
1453 (destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1454 (if (member move '("PASS" "resign"))
1455 (mapc 'delete-overlay (list l-ov r-ov))
1456 (gnugo-goto-pos move)
1457 (let* ((p (point))
1458 (hspec (gnugo-get :highlight-last-move-spec))
1459 (display-value (nth 0 hspec))
1460 (l-offset (nth 1 hspec))
1461 (l-new-pos (+ p l-offset))
1462 (r-action (nth 2 hspec)))
1463 (overlay-put l-ov 'display
1464 (if (functionp display-value)
1465 (funcall display-value p)
1466 display-value))
1467 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1468 (if r-action
1469 (funcall r-action r-ov)
1470 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1471 ;; buffer name
1472 (rename-buffer (concat (gnugo-get :diamond)
1473 (if game-over
1474 (format "%s(game over)"
1475 (if (gnugo--resignp move)
1476 (concat move "ation ")
1477 ""))
1478 (format "%s(%s to play)"
1479 (if move (concat move " ") "")
1480 (gnugo-current-player)))))
1481 ;; pall of death
1482 (when game-over
1483 (let ((live (cdr (assq 'live game-over)))
1484 (dead (cdr (assq 'dead game-over)))
1485 p pall)
1486 (unless (eq game-over (get-text-property 1 'game-over))
1487 (dolist (group (append live dead))
1488 (dolist (pos (cdr group))
1489 (gnugo-goto-pos pos)
1490 (setq p (point))
1491 (put-text-property p (1+ p) 'group group)))
1492 (put-text-property 1 2 'game-over game-over))
1493 (dolist (group live)
1494 (when (setq pall (cdar group))
1495 (mapc 'delete-overlay pall)
1496 (setcdr (car group) nil)))
1497 (dolist (group dead)
1498 (unless (cdar group)
1499 (let (ov pall c (color (caar group)))
1500 (setq c (if (gnugo--blackp color) "x" "o"))
1501 (dolist (pos (cdr group))
1502 (gnugo-goto-pos pos)
1503 (setq p (point) ov (make-overlay p (1+ p)))
1504 (overlay-put
1505 ov 'display
1506 (if (gnugo-get :display-using-images)
1507 ;; respect the dead individually; it takes more time
1508 ;; but that's not a problem (for them)
1509 (gnugo-venerate (get-text-property p 'gnugo-yin)
1510 (gnugo-yang (aref (upcase c) 0)))
1511 (propertize c 'face 'font-lock-warning-face)))
1512 (push ov pall))
1513 (setcdr (car group) pall))))))
1514 ;; window update
1515 (when (setq window (get-buffer-window (current-buffer)))
1516 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1517 (size (gnugo-get :SZ))
1518 (under10p (< size 10))
1519 (mul (gnugo-get :mul))
1520 (h (- (truncate (- (window-height window)
1521 (* size (cdr mul))
1522 (if gridp 2 0))
1523 2)
1524 (if gridp 0 1)))
1525 (edges (window-edges window))
1526 (right-w-edge (nth 2 edges))
1527 (avail-width (- right-w-edge (nth 0 edges)))
1528 (wmul (car mul))
1529 (imagesp (symbol-plist (gnugo-f 'ispc)))
1530 (w (/ (- avail-width
1531 (* size wmul)
1532 (if imagesp
1533 0
1534 (1- size))
1535 2 ; between board and grid
1536 (if gridp
1537 (if under10p 2 4)
1538 0))
1539 2.0)))
1540 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1541 `(display ,(make-string h 10))
1542 '(invisible :nogrid)))
1543 (gpad . (display
1544 (space :align-to
1545 ,(+ w
1546 2.0
1547 (cond (imagesp (+ (* 0.5 wmul)
1548 (if under10p
1549 -0.5
1550 0.5)))
1551 (under10p 0)
1552 (t 1))))))
1553 (gspc . ,(when imagesp
1554 `(display
1555 (space-width
1556 ,(-
1557 ;; DWR: image width alone => OBOE!
1558 ;;- wmul
1559 ;; NB: ‘(* wmul cw)’ is the same
1560 ;; as ‘(car (image-size ... t))’.
1561 (let ((cw (frame-char-width)))
1562 (/ (+ 1.0 (* wmul cw))
1563 cw))
1564 1.0)))))
1565 (lpad . ,(let ((d `(display (space :align-to ,w))))
1566 ;; We distinguish between these cases to
1567 ;; workaround a display bug whereby the
1568 ;; `before-string' is omitted entirely (not
1569 ;; rendered) when interacting w/ the text
1570 ;; mode last-move left-paren for moves in
1571 ;; column A.
1572 (if gridp
1573 `(before-string
1574 ,(apply 'propertize " " d))
1575 d)))
1576 (rpad . (display
1577 (space :align-to ,(1- avail-width))))))
1578 (setplist (gnugo-f (car pair)) (cdr pair)))))
1579 ;; mode line update
1580 (let ((cur (gnugo-get :mode-line)))
1581 (unless (equal cur gnugo-mode-line)
1582 (setq cur gnugo-mode-line)
1583 (gnugo-put :mode-line cur)
1584 (gnugo-put :mode-line-form
1585 (cond ((stringp cur)
1586 (setq cur (copy-sequence cur))
1587 (let (acc cut c)
1588 (while (setq cut (string-match "~[bwpmtu]" cur))
1589 (aset cur cut ?%)
1590 (setq c (aref cur (incf cut)))
1591 (aset cur cut ?s)
1592 (push
1593 `(,(intern (format "squig-%c" c))
1594 ,(case c
1595 (?b '(or (gnugo-get :black-captures) 0))
1596 (?w '(or (gnugo-get :white-captures) 0))
1597 (?p '(gnugo-current-player))
1598 (?t '(let ((ws (gnugo-get :waiting-start)))
1599 (if ws
1600 (cadr (time-since ws))
1601 "-")))
1602 (?u '(or (gnugo-get :last-waiting) "-"))
1603 (?m '(let ((tree (gnugo-get :sgf-gametree))
1604 (monkey (gnugo-get :monkey)))
1605 (gethash (car (aref monkey 0))
1606 (gnugo--tree-mnum tree)
1607 ;; should be unnecessary
1608 "?")))))
1609 acc))
1610 `(let ,(delete-dups (copy-sequence acc))
1611 (format ,cur ,@(reverse (mapcar 'car acc))))))
1612 (t cur))))
1613 (let ((form (gnugo-get :mode-line-form)))
1614 (setq mode-line-process
1615 (and form
1616 ;; this dynamicism is nice but excessive in its wantonness
1617 ;;- `(" [" (:eval ,form) "]")
1618 ;; this dynamicism is ok because the user triggers it
1619 (format " [%s]" (eval form)))))
1620 (force-mode-line-update))
1621 ;; last user move
1622 (when (setq last (gnugo-get :last-user-bpos))
1623 (gnugo-goto-pos last))))
1624
1625 (defun gnugo--finish-move (buf)
1626 (run-hooks 'gnugo-post-move-hook)
1627 (with-current-buffer buf
1628 (gnugo-refresh)))
1629
1630 ;;;---------------------------------------------------------------------------
1631 ;;; Game play actions
1632
1633 (defun gnugo--rename-buffer-portion (&optional back)
1634 (let ((old "to play")
1635 (new "waiting for suggestion"))
1636 (when back
1637 (rotatef old new))
1638 (let ((name (buffer-name)))
1639 (when (string-match old name)
1640 (rename-buffer (replace-match new t t name))))))
1641
1642 (defun gnugo--display-suggestion (color suggestion)
1643 (message "%sSuggestion for %s: %s"
1644 (gnugo-get :diamond)
1645 color suggestion))
1646
1647 (defun gnugo-get-move-insertion-filter (proc string)
1648 (with-current-buffer (process-buffer proc)
1649 (let* ((so-far (gnugo-get :get-move-string))
1650 (full (gnugo-put :get-move-string (concat so-far string))))
1651 (when (string-match "^= \\(.+\\)\n\n" full)
1652 (setq full (match-string 1 full)) ; POS or "PASS"
1653 (destructuring-bind (color . suggestion)
1654 (gnugo-get :waiting)
1655 (gnugo--forget :get-move-string
1656 :waiting)
1657 (if suggestion
1658 (progn
1659 (gnugo--rename-buffer-portion t)
1660 (unless (or (gnugo--passp full)
1661 (eq 'nowarp suggestion))
1662 (gnugo-goto-pos full))
1663 (gnugo--display-suggestion color full))
1664 (let* ((donep (gnugo-push-move color full))
1665 (buf (current-buffer)))
1666 (gnugo--finish-move buf)
1667 (when (gnugo-get :abd)
1668 (gnugo-put :abd
1669 (unless donep
1670 (run-at-time
1671 2 ;;; sec (frettoloso? dubioso!)
1672 nil (lambda (buf color)
1673 (with-current-buffer buf
1674 (gnugo-get-move color)))
1675 buf
1676 (gnugo-other color))))))))))))
1677
1678 (defun gnugo-get-move (color &optional suggestion)
1679 (gnugo-put :waiting (cons color suggestion))
1680 (gnugo--begin-exchange
1681 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1682 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1683 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1684 (concat "reg_genmove " color))
1685 (accept-process-output))
1686
1687 (defun gnugo-cleanup ()
1688 (when (gnugo-board-buffer-p)
1689 (unless (zerop (buffer-size))
1690 (message "Thank you for playing GNU Go."))
1691 (mapc (lambda (sym)
1692 (setplist sym nil) ; "...is next to fordliness." --Huxley
1693 ;; Sigh, "2nd arg optional" obsolete as of Emacs 23.3.
1694 ;; No worries, things will be Much Better w/ structs, RSN...
1695 (unintern sym nil))
1696 (append (gnugo-get :all-yy)
1697 (mapcar 'gnugo-f
1698 '(anim
1699 tpad
1700 gpad
1701 gspc
1702 lpad
1703 rpad
1704 ispc))))
1705 (setq gnugo-state nil)))
1706
1707 (defun gnugo-position ()
1708 (or (get-text-property (point) 'gnugo-position)
1709 (user-error "Not a proper position point")))
1710
1711 (defun gnugo-request-suggestion (&optional nowarp)
1712 "Request a move suggestion from GNU Go.
1713 After some time (during which you can do other stuff),
1714 Emacs displays the suggestion in the echo area and warps the
1715 cursor to the suggested position. Prefix arg inhibits warp."
1716 (interactive "P")
1717 (gnugo-gate t)
1718 (gnugo--rename-buffer-portion)
1719 (gnugo-get-move (gnugo-current-player)
1720 (if nowarp
1721 'nowarp
1722 t)))
1723
1724 (defun gnugo--user-play (pos-or-pass)
1725 (gnugo-gate t)
1726 ;; The "user" in this func's name used to signify both
1727 ;; who does the action and for whom the action is done.
1728 ;; Now, it signifies only the former.
1729 (let* ((gcolor (gnugo-get :gnugo-color))
1730 (userp (string= gcolor (gnugo-get :last-mover)))
1731 (donep (gnugo-push-move userp pos-or-pass))
1732 (buf (current-buffer)))
1733 (gnugo--finish-move buf)
1734 (when (and userp (not donep))
1735 (with-current-buffer buf
1736 (gnugo-get-move gcolor)))))
1737
1738 (defun gnugo-move ()
1739 "Make a move on the GNUGO Board buffer.
1740 The position is computed from current point.
1741 Signal error if done out-of-turn or if game-over.
1742 To start a game try M-x gnugo."
1743 (interactive)
1744 (gnugo--user-play (gnugo-position)))
1745
1746 (defun gnugo-mouse-move (e)
1747 "Do `gnugo-move' at mouse location."
1748 (interactive "@e")
1749 (mouse-set-point e)
1750 (when (memq (following-char) '(?. ?+))
1751 (gnugo-move)))
1752
1753 (defun gnugo-pass ()
1754 "Make a pass on the GNUGO Board buffer.
1755 Signal error if done out-of-turn or if game-over.
1756 To start a game try M-x gnugo."
1757 (interactive)
1758 (gnugo--user-play "PASS"))
1759
1760 (defun gnugo-mouse-pass (e)
1761 "Do `gnugo-pass' at mouse location."
1762 (interactive "@e")
1763 (mouse-set-point e)
1764 (gnugo-pass))
1765
1766 (defun gnugo-resign ()
1767 (interactive)
1768 (gnugo-gate t)
1769 (if (not (y-or-n-p "Resign? "))
1770 (message "(not resigning)")
1771 (gnugo-push-move t "resign")
1772 (gnugo-refresh)))
1773
1774 (defun gnugo-animate-group (w/d)
1775 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1776 (let* ((pos (gnugo-position))
1777 (orig-b-m-p (buffer-modified-p))
1778 blurb stones)
1779 (unless (memq (following-char) '(?X ?O))
1780 (user-error "No stone at %s" pos))
1781 (setq blurb (message "Computing %s stones ..." w/d)
1782 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1783 (message "%s %s in group." blurb (length stones))
1784 (setplist (gnugo-f 'anim) nil)
1785 (let* ((spec (if (gnugo-get :display-using-images)
1786 (loop with yin = (get-text-property (point) 'gnugo-yin)
1787 with yang = (gnugo-yang (following-char))
1788 with up = (get (gnugo-yy yin yang t) 'display)
1789 with dn = (get (gnugo-yy yin yang) 'display)
1790 for n below (length gnugo-animation-string)
1791 collect (if (zerop (logand 1 n))
1792 dn up))
1793 (split-string gnugo-animation-string "" t)))
1794 (cell (list spec))
1795 (ovs (save-excursion
1796 (mapcar (lambda (pos)
1797 (gnugo-goto-pos pos)
1798 (let* ((p (point))
1799 (ov (make-overlay p (1+ p))))
1800 (overlay-put ov 'category (gnugo-f 'anim))
1801 (overlay-put ov 'priority most-positive-fixnum)
1802 ov))
1803 stones))))
1804 (setplist (gnugo-f 'anim) (cons 'display cell))
1805 (while (and (cdr spec) ; let last linger lest levity lost
1806 (sit-for 0.08675309)) ; jenny jenny i got your number...
1807 (setcar cell (setq spec (cdr spec)))
1808 ;; Force redisplay of overlays.
1809 (set-buffer-modified-p orig-b-m-p))
1810 (sit-for 5)
1811 (mapc 'delete-overlay ovs)
1812 t)))
1813
1814 (defun gnugo-display-group-data (command buffer-name)
1815 (message "Computing %s ..." command)
1816 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1817 (switch-to-buffer buffer-name)
1818 (erase-buffer)
1819 (insert data))
1820 (message "Computing %s ... done." command))
1821
1822 (defun gnugo-worm-stones ()
1823 "In the GNUGO Board buffer, animate \"worm\" at current position.
1824 Signal error if done out-of-turn or if game-over.
1825 See variable `gnugo-animation-string' for customization."
1826 (interactive)
1827 (gnugo-gate)
1828 (gnugo-animate-group 'worm))
1829
1830 (defun gnugo-worm-data ()
1831 "Display in another buffer data from \"worm\" at current position.
1832 Signal error if done out-of-turn or if game-over."
1833 (interactive)
1834 (gnugo-gate)
1835 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1836
1837 (defun gnugo-dragon-stones ()
1838 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1839 Signal error if done out-of-turn or if game-over.
1840 See variable `gnugo-animation-string' for customization."
1841 (interactive)
1842 (gnugo-gate)
1843 (gnugo-animate-group 'dragon))
1844
1845 (defun gnugo-dragon-data ()
1846 "Display in another buffer data from \"dragon\" at current position.
1847 Signal error if done out-of-turn or if game-over."
1848 (interactive)
1849 (gnugo-gate)
1850 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1851
1852 (defun gnugo-estimate-score ()
1853 "Display estimated score of a game of GNU Go.
1854 Output includes number of stones on the board and number of stones
1855 captured by each player, and the estimate of who has the advantage (and
1856 by how many stones)."
1857 (interactive)
1858 (message "Est.score ...")
1859 (let ((black (gnugo--count-query "list_stones black"))
1860 (white (gnugo--count-query "list_stones white"))
1861 (black-captures (gnugo-query "captures black"))
1862 (white-captures (gnugo-query "captures white"))
1863 (est (gnugo-query "estimate_score")))
1864 ;; might as well update this
1865 (gnugo-put :black-captures black-captures)
1866 (gnugo-put :white-captures white-captures)
1867 (message "Est.score ... B %s %s | W %s %s | %s"
1868 black black-captures white white-captures est)))
1869
1870 (defun gnugo-write-sgf-file (filename)
1871 "Save the game history to FILENAME (even if unfinished).
1872 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1873 (interactive "FWrite game as SGF file: ")
1874 (when (and (file-exists-p filename)
1875 (not (y-or-n-p "File exists. Continue? ")))
1876 (user-error "Not writing %s" filename))
1877 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1878 (set-buffer-modified-p nil))
1879
1880 (defun gnugo--who-is-who (wait play samep)
1881 (message "GNU Go %splays as %s, you as %s (%s)"
1882 (if samep "" "now ")
1883 wait play (if samep
1884 "as before"
1885 "NOTE: this is a switch!")))
1886
1887 (defsubst gnugo--nodep (x)
1888 (keywordp (caar x)))
1889
1890 (defun gnugo--SZ! (size)
1891 (gnugo-put :SZ size)
1892 (gnugo-put :center-position
1893 (funcall (gnugo--as-pos-func)
1894 (let ((c (+ -1 ?a (truncate (1+ size) 2))))
1895 (string c c)))))
1896
1897 (defun gnugo--plant-and-climb (collection &optional sel)
1898 (gnugo-put :sgf-collection collection)
1899 (let ((tree (nth (or sel 0) collection)))
1900 (gnugo-put :sgf-gametree tree)
1901 (gnugo-put :monkey (vector
1902 ;; mem
1903 (aref (gnugo--tree-ends tree) 0)
1904 ;; bidx
1905 0))
1906 tree))
1907
1908 (defun gnugo-read-sgf-file (filename)
1909 "Load the first game tree from FILENAME, a file in SGF format."
1910 (interactive "fSGF file to load: ")
1911 (when (file-directory-p filename)
1912 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1913 (let (play wait samep coll tree game-over)
1914 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1915 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1916 (setq play (gnugo--q/ue "loadsgf %s" (expand-file-name filename))
1917 wait (gnugo-other play)
1918 samep (string= (gnugo-get :user-color) play))
1919 (gnugo-put :last-mover wait)
1920 (unless samep
1921 (gnugo-put :gnugo-color wait)
1922 (gnugo-put :user-color play))
1923 (setq coll (gnugo/sgf-create filename)
1924 tree (gnugo--plant-and-climb
1925 coll (let ((n (length coll)))
1926 ;; This is better:
1927 ;; (if (= 1 n)
1928 ;; 0
1929 ;; (let* ((q (format "Which game? (1-%d)" n))
1930 ;; (choice (1- (read-number q 1))))
1931 ;; (if (and (< -1 choice) (< choice n))
1932 ;; choice
1933 ;; (message "(Selecting the first game)")
1934 ;; 0)))
1935 ;; but this is what we use (for now) to accomodate
1936 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1937 (unless (= 1 n)
1938 (message "(Selecting the first game)"))
1939 0)))
1940 ;; This is deliberately undocumented for now.
1941 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1942 (when (setq game-over (or (gnugo--root-prop :RE tree)
1943 (when (equal '("PASS" "PASS")
1944 (gnugo-move-history 'two))
1945 'two-passes)))
1946 (gnugo-close-game nil game-over))
1947 (gnugo-put :last-user-bpos
1948 (gnugo-move-history 'bpos (gnugo-get :user-color)))
1949 (gnugo-refresh t)
1950 (set-buffer-modified-p nil)
1951 (gnugo--who-is-who wait play samep)))
1952
1953 (defun gnugo--mem-with-played-stone (pos &optional noerror)
1954 (let ((color (case (following-char)
1955 (?X :B)
1956 (?O :W))))
1957 (if (not color)
1958 (unless noerror
1959 (user-error "No stone at %s" pos))
1960 (loop with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
1961 for mem on (aref (gnugo-get :monkey) 0)
1962 when (equal fruit (caar mem))
1963 return mem
1964 finally return nil))))
1965
1966 (defun gnugo--climb-towards-root (spec &optional noalt keep)
1967 (gnugo-gate)
1968 (let* ((user-color (gnugo-get :user-color))
1969 (monkey (gnugo-get :monkey))
1970 (tree (gnugo-get :sgf-gametree))
1971 (ends (gnugo--tree-ends tree))
1972 (remorseful (not (gnugo--no-regrets monkey ends)))
1973 (stop (if (numberp spec)
1974 (nthcdr (if (zerop spec)
1975 (if (string= (gnugo-get :last-mover)
1976 user-color)
1977 1
1978 2)
1979 spec)
1980 (aref monkey 0))
1981 (let* ((pos (if (stringp spec)
1982 spec
1983 (gnugo-position)))
1984 (hmm (gnugo--mem-with-played-stone pos)))
1985 ;; todo: relax ‘gnugo--user-play’ then lift restriction
1986 (unless (eq (gnugo--prop<-color user-color)
1987 (car (gnugo--move-prop (car hmm))))
1988 (user-error "%s not occupied by %s"
1989 pos user-color))
1990 (cdr hmm)))))
1991 (when (gnugo-get :game-over)
1992 (gnugo--unclose-game))
1993 (while (and (not (eq stop (aref monkey 0)))
1994 (gnugo--no-worries (gnugo--q "undo")))
1995 (pop (aref monkey 0))
1996 (gnugo-put :last-mover (gnugo-current-player))
1997 (gnugo-merge-showboard-results) ; all
1998 (gnugo-refresh) ; this
1999 (redisplay)) ; eye candy
2000 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
2001
2002 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
2003 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
2004 ubpos
2005 (gnugo-get :center-position)))
2006 (gnugo-refresh t)
2007 (unless (or keep remorseful)
2008 (aset ends (aref monkey 1) (aref monkey 0)))
2009 (when (and ulastp (not noalt))
2010 (gnugo-get-move (gnugo-get :gnugo-color))))))
2011
2012 (defun gnugo-undo-one-move (&optional me-next)
2013 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
2014 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
2015 Prefix arg ME-NEXT means to arrange for you to play
2016 the color of the next move (and GNU Go the opposite).
2017 This is useful after loading an SGF file whose last
2018 move was done by the color you prefer to play:
2019 \\[gnugo-read-sgf-file] FILENAME RET
2020 C-u \\[gnugo-undo-one-move]
2021
2022 See also `gnugo-undo-two-moves'."
2023 (interactive "P")
2024 (gnugo-gate)
2025 (when me-next
2026 (let* ((play (gnugo-get :last-mover))
2027 (wait (gnugo-other play)))
2028 (gnugo--who-is-who wait play (string= play (gnugo-get :user-color)))
2029 (gnugo-put :user-color play)
2030 (gnugo-put :gnugo-color wait)))
2031 (gnugo--climb-towards-root 1 t))
2032
2033 (defun gnugo-undo-two-moves ()
2034 "Undo a pair of moves (GNU Go's and yours).
2035 However, if you are the last mover, undo only one move.
2036 Regardless, after undoing, it is your turn to play again."
2037 (interactive)
2038 (gnugo-gate)
2039 (gnugo--climb-towards-root 0))
2040
2041 (defun gnugo-oops (&optional position)
2042 "Like `gnugo-undo-two-moves', but keep the undone moves.
2043 The kept moves become a sub-gametree (variation) when play resumes.
2044 Prefix arg means, instead, undo repeatedly up to and including
2045 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2046 (interactive "P")
2047 (gnugo-gate)
2048 (gnugo--climb-towards-root (unless position
2049 0)
2050 nil t))
2051
2052 (defun gnugo-okay (&optional full)
2053 "Redo a pair of undone moves.
2054 Prefix arg means to redo all the undone moves."
2055 (interactive "P")
2056 (gnugo-gate)
2057 (let* ((tree (gnugo-get :sgf-gametree))
2058 (ends (gnugo--tree-ends tree))
2059 (monkey (gnugo-get :monkey)))
2060 (if (gnugo--no-regrets monkey ends)
2061 (message "Oop ack!")
2062 (let* ((as-pos (gnugo--as-pos-func))
2063 (mnum (gnugo--tree-mnum tree))
2064 (mem (aref monkey 0))
2065 (bidx (aref monkey 1))
2066 (end (aref ends bidx))
2067 (ucolor (gnugo-get :user-color))
2068 (uprop (gnugo--prop<-color ucolor)))
2069 (cl-flet ((mvno (node) (gethash node mnum)))
2070 (loop
2071 with ok = (if full
2072 (mvno (car end))
2073 (+ 2 (mvno (car mem))))
2074 with (node move todo)
2075 for ls on end
2076 do (progn
2077 (setq node (car ls)
2078 move (gnugo--move-prop node))
2079 (when (and move (>= ok (mvno node)))
2080 (let ((userp (eq uprop (car move))))
2081 (push (list userp
2082 (funcall as-pos (cdr move)))
2083 todo))))
2084 until (eq mem (cdr ls))
2085 finally do
2086 (loop
2087 for (userp pos) in todo
2088 do (progn
2089 (gnugo-push-move userp pos)
2090 (gnugo-refresh)
2091 (redisplay)))))))))
2092
2093 (defun gnugo-display-final-score (&optional comment)
2094 "Display final score and other info in another buffer (when game over).
2095 If the game is still ongoing, Emacs asks if you wish to stop play (by
2096 making sure two \"pass\" moves are played consecutively, if necessary).
2097 Also, add the `:RE' SGF property to the root node of the game tree.
2098 Prefix arg COMMENT means to also attach the text (slightly compacted)
2099 to the last move, as a comment."
2100 (interactive "P")
2101 (let ((game-over (gnugo-get :game-over)))
2102 (unless (or game-over
2103 (and (not (gnugo-get :waiting))
2104 (y-or-n-p "Game still in play. Stop play now? ")))
2105 (user-error "Sorry, game still in play"))
2106 (unless game-over
2107 (cl-flet
2108 ((pass (userp)
2109 (message "Playing PASS for %s ..."
2110 (gnugo-get (if userp :user-color :gnugo-color)))
2111 (sit-for 1)
2112 (gnugo-push-move userp "PASS")))
2113 (unless (pass t)
2114 (pass nil)))
2115 (gnugo-refresh)
2116 (sit-for 3)))
2117 (let ((b= " Black = ")
2118 (w= " White = ")
2119 (res (when (gnugo--resignp (gnugo-move-history 'car))
2120 (gnugo-get :last-mover)))
2121 blurb result)
2122 (if res
2123 (setq blurb (list
2124 (format "%s wins.\n"
2125 (substring (if (= ?b (aref res 0)) w= b=)
2126 3 8))
2127 "The game is over.\n"
2128 (format "Resignation by %s.\n" res))
2129 result (concat (upcase (substring (gnugo-other res) 0 1))
2130 "+Resign"))
2131 (message "Computing final score ...")
2132 (let* ((g-over (gnugo-get :game-over))
2133 (live (cdr (assq 'live g-over)))
2134 (dead (cdr (assq 'dead g-over)))
2135 (seed (gnugo-get :scoring-seed))
2136 (terr-q (format "final_status_list %%s_territory %d" seed))
2137 (terr "territory")
2138 (capt "captures")
2139 (b-terr (gnugo--count-query terr-q "black"))
2140 (w-terr (gnugo--count-query terr-q "white"))
2141 (b-capt (string-to-number (gnugo-get :black-captures)))
2142 (w-capt (string-to-number (gnugo-get :white-captures)))
2143 (komi (gnugo--root-prop :KM)))
2144 (setq blurb (list "The game is over. Final score:\n")
2145 result (gnugo-query "final_score %d" seed))
2146 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2147 (dolist (group live)
2148 (incf (if (gnugo--blackp (caar group))
2149 b-terr
2150 w-terr)
2151 (length (cdr group))))
2152 (dolist (group dead)
2153 (incf (if (gnugo--blackp (caar group))
2154 w-terr
2155 b-terr)
2156 (length (cdr group))))
2157 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2158 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2159 w-terr terr komi 'komi (+ w-terr komi))
2160 blurb))
2161 (t
2162 (dolist (group dead)
2163 (incf (if (gnugo--blackp (caar group))
2164 w-terr
2165 b-terr)
2166 (* 2 (length (cdr group)))))
2167 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2168 b-terr terr
2169 b-capt capt
2170 (+ b-terr b-capt))
2171 blurb)
2172 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2173 w-terr terr
2174 w-capt capt
2175 komi 'komi
2176 (+ w-terr w-capt komi))
2177 blurb)))
2178 (push (if (string= "0" result)
2179 "The game is a draw.\n"
2180 (format "%s wins by %s.\n"
2181 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2182 (substring result 2)))
2183 blurb)
2184 (message "Computing final score ... done")))
2185 ;; extra info
2186 (let ((beg (gnugo-get :game-start-time))
2187 (end (gnugo-get :game-end-time)))
2188 (when end
2189 (push "\n" blurb)
2190 (cl-flet
2191 ((yep (pretty moment)
2192 (push (format-time-string
2193 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2194 moment)
2195 blurb)))
2196 (yep "Game start" beg)
2197 (yep " end" end))))
2198 (setq blurb (apply 'concat (nreverse blurb)))
2199 (gnugo--set-root-prop :RE result)
2200 (when comment
2201 (let ((node (car (aref (gnugo-get :monkey) 0))))
2202 (gnugo--decorate
2203 (delq (assq :C node) node)
2204 :C
2205 (with-temp-buffer ; lame
2206 (insert blurb)
2207 (when (search-backward "\n\nGame start:" nil t)
2208 (delete-region (point) (point-max)))
2209 (cl-flet ((rep (old new)
2210 (goto-char (point-min))
2211 (while (search-forward old nil t)
2212 (replace-match new))))
2213 (rep "The game is over. " "")
2214 (rep "territory" "T")
2215 (rep "captures" "C")
2216 (rep "komi" "K"))
2217 (buffer-string)))))
2218 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2219 (erase-buffer)
2220 (insert blurb)))
2221
2222 (defun gnugo-quit ()
2223 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2224 If the game is not over, ask for confirmation first."
2225 (interactive)
2226 (if (or (gnugo-get :game-over)
2227 (y-or-n-p "Quit? "))
2228 (kill-buffer nil)
2229 (message "(not quitting)")))
2230
2231 (defun gnugo-leave-me-alone ()
2232 "Kill the current buffer unconditionally."
2233 (interactive)
2234 (kill-buffer nil))
2235
2236 (defun gnugo-fancy-undo (count)
2237 "Rewind the game tree in various ways.
2238 Prefix arg COUNT means to undo that many moves.
2239 Otherwise, undo repeatedly up to and including the move
2240 which placed the stone at point."
2241 (interactive "P")
2242 (gnugo--climb-towards-root
2243 (cond ((numberp count) count)
2244 ((consp count) (car count)))))
2245
2246 (defun gnugo-toggle-image-display-command () ; ugh
2247 "Toggle use of images to display the board, then refresh."
2248 (interactive)
2249 (gnugo-toggle-image-display)
2250 (save-excursion (gnugo-refresh)))
2251
2252 (defsubst gnugo--node-with-played-stone (pos &optional noerror)
2253 (car (gnugo--mem-with-played-stone pos noerror)))
2254
2255 (defun gnugo-describe-position ()
2256 "Display the board position under cursor in the echo area.
2257 If there a stone at that position, also display its move number."
2258 (interactive)
2259 (let* ((pos (gnugo-position)) ; do first (can throw)
2260 (node (gnugo--node-with-played-stone pos t)))
2261 (message
2262 "%s%s" pos
2263 (or (when node
2264 (let* ((tree (gnugo-get :sgf-gametree))
2265 (mnum (gnugo--tree-mnum tree))
2266 (move-num (gethash node mnum)))
2267 (format " (move %d)" move-num)))
2268 ""))))
2269
2270 (defun gnugo-switch-to-another ()
2271 "Switch to another GNU Go game buffer (if any)."
2272 (interactive)
2273 (loop for buf in (cdr (buffer-list))
2274 if (gnugo-board-buffer-p buf)
2275 return (progn
2276 (bury-buffer)
2277 (switch-to-buffer buf))
2278 finally do (message "(only one)")))
2279
2280 (defun gnugo-comment (node comment)
2281 "Add to NODE a COMMENT (string) property.
2282 Called interactively, NODE is the one corresponding to the
2283 stone at point, and any previous comment is inserted as the
2284 initial-input (see `read-string').
2285
2286 If COMMENT is nil or the empty string, remove the property entirely."
2287 (interactive
2288 (let* ((pos (gnugo-position))
2289 (node (gnugo--node-with-played-stone pos)))
2290 (list node
2291 (read-string (format "Comment for %s: "
2292 (gnugo-describe-position))
2293 (cdr (assq :C node))))))
2294 (setq node (delq (assq :C node) node))
2295 (unless (zerop (length comment))
2296 (gnugo--decorate node :C comment)))
2297
2298 (defun gnugo-toggle-abdication ()
2299 "Toggle abdication, i.e., letting GNU Go play for you.
2300 When enabled, the mode line includes \"Abd\".
2301 Enabling signals error if the game is over.
2302 When disabling, if GNU Go has already started thinking of
2303 a move to play for you, the thinking is not cancelled but instead
2304 transformed into a move suggestion (see `gnugo-request-suggestion')."
2305 (interactive)
2306 (let ((u (gnugo-get :user-color))
2307 (abd (gnugo-get :abd)))
2308 (if abd
2309 ;; disable
2310 (let* ((gcolor (gnugo-get :gnugo-color))
2311 (waiting (gnugo-get :waiting))
2312 (userp (string= gcolor (gnugo-get :last-mover))))
2313 (when (timerp abd)
2314 (cancel-timer abd))
2315 (gnugo--forget :abd)
2316 (when (and userp waiting)
2317 (gnugo--rename-buffer-portion)
2318 (setcdr waiting
2319 ;; heuristic: Warp only if it appears
2320 ;; that the user is "following along".
2321 (or (ignore-errors
2322 (string= (gnugo-position)
2323 (gnugo-move-history 'bpos u)))
2324 'nowarp))
2325 (gnugo--display-suggestion u "forthcoming")
2326 (sleep-for 2))
2327 (unless (or userp waiting)
2328 (gnugo-get-move gcolor)))
2329 ;; enable
2330 (gnugo-gate t)
2331 (gnugo-put :abd t)
2332 (gnugo-get-move u))
2333 (gnugo--instant-karma u (not abd))))
2334
2335 ;;;---------------------------------------------------------------------------
2336 ;;; Command properties and gnugo-command
2337
2338 ;; GTP commands entered by the user are never issued directly to GNU Go;
2339 ;; instead, their behavior and output are controlled by the property
2340 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2341 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2342 ;;
2343 ;; :full -- completely interpret the command string; the value is a
2344 ;; func that takes the list of words derived from splitting the
2345 ;; command string (minus the command) and handles everything.
2346 ;;
2347 ;; :output -- either a keyword specifying the preferred output method:
2348 ;; :message -- show output in minibuffer
2349 ;; :discard -- sometimes you just don't care;
2350 ;; or a function that takes one arg, the output string, and
2351 ;; handles it completely. default is to switch to buffer
2352 ;; "*gnugo command output*" if the output has a newline,
2353 ;; otherwise use `message'.
2354 ;;
2355 ;; :post-thunk -- run after output processing (at the very end).
2356
2357 (defun gnugo-command (command)
2358 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2359 Output and Emacs behavior depend on which command is given (some
2360 commands are handled completely by Emacs w/o using the subprocess;
2361 some commands have their output displayed in specially prepared
2362 buffers or in the echo area; some commands are instrumented to do
2363 gnugo.el-specific housekeeping).
2364
2365 For example, for the command \"help\", Emacs visits the
2366 GTP command reference info page.
2367
2368 NOTE: At this time, GTP command handling specification is still
2369 incomplete. Thus, some commands WILL confuse gnugo.el."
2370 (interactive "sCommand: ")
2371 (if (string= "" command)
2372 (message "(no command given)")
2373 (let* ((split (split-string command))
2374 (cmd (intern (car split)))
2375 (spec (get cmd :gnugo-gtp-command-spec))
2376 (full (plist-get spec :full)))
2377 (if full
2378 (funcall full (cdr split))
2379 (message "Doing %s ..." command)
2380 (let* ((ans (gnugo--q command))
2381 (where (plist-get spec :output)))
2382 (if (string-match "unknown.command" ans)
2383 (message "%s" ans)
2384 (cond ((functionp where) (funcall where ans))
2385 ((eq :discard where) (message ""))
2386 ((or (eq :message where)
2387 (not (string-match "\n" ans)))
2388 (message "%s" ans))
2389 (t (switch-to-buffer "*gnugo command output*")
2390 (erase-buffer)
2391 (insert ans)
2392 (message "Doing %s ... done." command)))
2393 (let ((thunk (plist-get spec :post-thunk)))
2394 (when thunk (funcall thunk)))))))))
2395
2396 ;;;---------------------------------------------------------------------------
2397 ;;; Major mode for interacting with a GNUGO subprocess
2398
2399 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2400 "Major mode for playing GNU Go.
2401 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2402 In this mode, keys do not self insert.
2403
2404 \\{gnugo-board-mode-map}"
2405 (buffer-disable-undo) ; todo: undo undo undoing
2406 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2407 truncate-lines t)
2408 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2409 (set (make-local-variable 'gnugo-state)
2410 (gnugo--mkht :size (1- 42)))
2411 (set (make-local-variable 'gnugo-btw) nil)
2412 (add-to-list 'minor-mode-alist '(gnugo-btw gnugo-btw))
2413 (gnugo-put :highlight-last-move-spec
2414 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2415 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2416 (let ((ov (make-overlay 1 1)))
2417 (overlay-put ov 'display ")")
2418 ov)))
2419 (gnugo-put :mul '(1 . 1))
2420 (add-to-invisibility-spec :nogrid))
2421
2422 ;;;---------------------------------------------------------------------------
2423 ;;; Entry point
2424
2425 ;;;###autoload
2426 (defun gnugo (&optional new-game)
2427 "Run gnugo in a buffer, or resume a game in progress.
2428 If there is already a game in progress you may resume it instead
2429 of starting a new one. Prefix arg means skip the game-in-progress
2430 check and start a new game straight away.
2431
2432 Before starting, Emacs queries you for additional command-line
2433 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2434
2435 Note that specifying \"--infile FILENAME\" (or, \"-l FILENAME\")
2436 silently clobbers certain other options, such as \"--color\".
2437 For details, see info node `(gnugo) Invoking GNU Go'.
2438
2439 \\<gnugo-board-mode-map>
2440 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2441 See `gnugo-board-mode' for a full list of commands."
2442 (interactive "P")
2443 (let* ((all (let (acc)
2444 (dolist (buf (buffer-list))
2445 (when (gnugo-board-buffer-p buf)
2446 (push (cons (buffer-name buf) buf) acc)))
2447 acc))
2448 (n (length all)))
2449 (if (and (not new-game)
2450 (cl-plusp n)
2451 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2452 (if (= 1 n) "" "s"))))
2453 ;; resume
2454 (switch-to-buffer
2455 (cdr (if (= 1 n)
2456 (car all)
2457 (let ((sel (completing-read "Which one? " all nil t)))
2458 (if (string= "" sel)
2459 (car all)
2460 (assoc sel all))))))
2461 ;; sanity check
2462 (unless (executable-find gnugo-program)
2463 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2464 ;; set up a new board
2465 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2466 (gnugo-board-mode)
2467 (let* ((filename nil)
2468 (user-color "black")
2469 (args (loop
2470 with ls = (split-string
2471 ;; todo: grok ‘gnugo --help’; completion
2472 (read-string
2473 "GNU Go options: "
2474 (car gnugo-option-history)
2475 'gnugo-option-history))
2476 with ok
2477 while ls do
2478 (let ((arg (pop ls)))
2479 (cl-flet
2480 ((ex (opt fn)
2481 (if filename
2482 (warn "%s %s ignored" opt fn)
2483 (setq filename fn))))
2484 (cond
2485 ((string= "--color" arg)
2486 (push arg ok)
2487 (push
2488 ;; Unfortunately, GTP does not provide
2489 ;; a way to query the user color, so
2490 ;; we must resort to this weirdness.
2491 (setq user-color
2492 (pop ls))
2493 ok))
2494 ((string= "--infile" arg)
2495 (ex "--infile" (pop ls)))
2496 ((string-match "^-l" arg)
2497 (ex "-l" (if (< 2 (length arg))
2498 (substring arg 2)
2499 (pop ls))))
2500 (t (push arg ok)))))
2501 finally return (nreverse ok)))
2502 (proc (apply 'start-process "gnugo"
2503 (current-buffer)
2504 gnugo-program
2505 "--mode" "gtp" "--quiet"
2506 args))
2507 root board-size handicap komi)
2508 (gnugo-put :user-color user-color)
2509 (gnugo-put :proc proc)
2510 (set-process-sentinel proc 'gnugo-sentinel)
2511 ;; Emacs is too protective sometimes, blech.
2512 (set-process-query-on-exit-flag proc nil)
2513 (gnugo-put :diamond (substring (process-name proc) 5))
2514 (gnugo-put :gnugo-color (gnugo-other user-color))
2515 (if filename
2516 (gnugo-read-sgf-file (expand-file-name filename))
2517 (cl-flet
2518 ((r! (&rest plist) (apply 'gnugo--decorate root plist)))
2519 (gnugo--SZ!
2520 (setq root (gnugo--root-node
2521 (gnugo--plant-and-climb
2522 (gnugo/sgf-create "(;FF[4]GM[1])" t)))
2523 komi (gnugo--nquery "get_komi")
2524 handicap (gnugo--nquery "get_handicap")
2525 board-size (gnugo--nquery "query_boardsize")))
2526 ;; Work around a GNU Go 3.8 (and possibly earlier/later)
2527 ;; bug whereby GTP command ‘get_handicap’ fails to return
2528 ;; the N set by ‘--handicap N’ on the command line.
2529 (let ((actually (member "--handicap" args)))
2530 ;; Checking ‘(zerop handicap)’ first is not strictly
2531 ;; necessary; it represents a hope that some day GNU Go
2532 ;; will DTRT (or provide rationale for this weird behavior)
2533 ;; and become worthy of our trust.
2534 (when (and (zerop handicap) actually)
2535 (setq handicap (string-to-number (cadr actually)))))
2536 (r! :SZ board-size
2537 :DT (format-time-string "%Y-%m-%d")
2538 :RU (if (member "--chinese-rules" args)
2539 "Chinese"
2540 "Japanese")
2541 :AP (cons "gnugo.el" gnugo-version)
2542 :KM komi)
2543 (let ((ub (gnugo--blackp user-color)))
2544 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2545 (if ub :PB :PW) (user-full-name)))
2546 (unless (zerop handicap)
2547 (r! :HA handicap
2548 :AB (mapcar (gnugo--as-cc-func)
2549 (gnugo-lsquery "fixed_handicap %d"
2550 handicap)))))))
2551 (gnugo-put :waiting-start (current-time))
2552 (gnugo-refresh t)
2553 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2554 (gnugo-get :center-position)))
2555 ;; first move
2556 (gnugo-put :game-start-time (current-time))
2557 (let ((g (gnugo-get :gnugo-color))
2558 (n (or (gnugo--root-prop :HA) 0))
2559 (u (gnugo-get :user-color)))
2560 (unless (gnugo-get :last-mover)
2561 (gnugo-put :last-mover
2562 (if (or (and (gnugo--blackp u) (< 1 n))
2563 (and (gnugo--blackp g) (< n 2)))
2564 u
2565 g)))
2566 (run-hooks 'gnugo-start-game-hook)
2567 (when (and (not (gnugo-get :game-over))
2568 (string= g (gnugo-current-player)))
2569 (gnugo-refresh t)
2570 (gnugo-get-move g))))))
2571
2572 ;;;---------------------------------------------------------------------------
2573 ;;; Load-time actions
2574
2575 (unless gnugo-frolic-mode-map
2576 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2577 (suppress-keymap gnugo-frolic-mode-map)
2578 (mapc (lambda (pair)
2579 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2580 '(("q" . gnugo-frolic-quit)
2581 ("Q" . gnugo-frolic-quit)
2582 ("\C-q" . gnugo-frolic-quit)
2583 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2584 ("\C-b" . gnugo-frolic-backward-branch)
2585 ("\C-f" . gnugo-frolic-forward-branch)
2586 ("\C-p" . gnugo-frolic-previous-move)
2587 ("\C-n" . gnugo-frolic-next-move)
2588 ("j" . gnugo-frolic-exchange-left)
2589 ("J" . gnugo-frolic-rotate-left)
2590 ("k" . gnugo-frolic-exchange-right)
2591 ("K" . gnugo-frolic-rotate-right)
2592 ("\C-m" . gnugo-frolic-set-as-main-line)
2593 ("\C-\M-p" . gnugo-frolic-prune-branch)
2594 ("o" . gnugo-frolic-return-to-origin))))
2595
2596 (unless gnugo-board-mode-map
2597 (setq gnugo-board-mode-map (make-sparse-keymap))
2598 (suppress-keymap gnugo-board-mode-map)
2599 (mapc (lambda (pair)
2600 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2601 '(("?" . describe-mode)
2602 ("S" . gnugo-request-suggestion)
2603 ("\C-m" . gnugo-move)
2604 (" " . gnugo-move)
2605 ("P" . gnugo-pass)
2606 ("R" . gnugo-resign)
2607 ("q" . gnugo-quit)
2608 ("Q" . gnugo-leave-me-alone)
2609 ("U" . gnugo-fancy-undo)
2610 ("\M-u" . gnugo-undo-one-move)
2611 ("u" . gnugo-undo-two-moves)
2612 ("\C-?" . gnugo-undo-two-moves)
2613 ("o" . gnugo-oops)
2614 ("O" . gnugo-okay)
2615 ("\C-l" . gnugo-refresh)
2616 ("\M-_" . gnugo-boss-is-near)
2617 ("_" . gnugo-boss-is-near)
2618 ("h" . gnugo-move-history)
2619 ("L" . gnugo-frolic-in-the-leaves)
2620 ("\C-c\C-l" . gnugo-frolic-in-the-leaves)
2621 ("i" . gnugo-toggle-image-display-command)
2622 ("w" . gnugo-worm-stones)
2623 ("W" . gnugo-worm-data)
2624 ("d" . gnugo-dragon-stones)
2625 ("D" . gnugo-dragon-data)
2626 ("g" . gnugo-toggle-grid)
2627 ("!" . gnugo-estimate-score)
2628 (":" . gnugo-command)
2629 (";" . gnugo-command)
2630 ("=" . gnugo-describe-position)
2631 ("s" . gnugo-write-sgf-file)
2632 ("\C-x\C-s" . gnugo-write-sgf-file)
2633 ("\C-x\C-w" . gnugo-write-sgf-file)
2634 ("l" . gnugo-read-sgf-file)
2635 ("F" . gnugo-display-final-score)
2636 ("A" . gnugo-switch-to-another)
2637 ("C" . gnugo-comment)
2638 ("\C-c\C-a" . gnugo-toggle-abdication)
2639 ;; mouse
2640 ([(down-mouse-1)] . gnugo-mouse-move)
2641 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2642 ([(down-mouse-3)] . gnugo-mouse-pass)
2643 ;; delving into the curiosities
2644 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2645
2646 (unless (get 'help :gnugo-gtp-command-spec)
2647 (cl-flet*
2648 ((sget (x) (get x :gnugo-gtp-command-spec))
2649 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2650 (plist-put (sget cmd) prop val)))
2651 (validpos (s &optional go)
2652 (let ((pos (upcase s)))
2653 (loop with size = (gnugo-get :SZ)
2654 for c across (funcall (gnugo--as-cc-func)
2655 pos)
2656 do (let ((norm (- c ?a)))
2657 (unless (and (< -1 norm)
2658 (> size norm))
2659 (user-error "Invalid position: %s"
2660 pos))))
2661 (when go
2662 (gnugo-goto-pos pos))
2663 pos))
2664 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2665 (let ((ls props))
2666 (while ls
2667 (jam cmd (car ls) (cadr ls))
2668 (setq ls (cddr ls)))))))
2669 (cl-macrolet ((deffull (who &body body)
2670 (declare (indent 1))
2671 `(defgtp ',who :full (lambda (sel)
2672 ,@body))))
2673
2674 (deffull help
2675 (info "(gnugo)GTP command reference")
2676 (when sel (setq sel (intern (car sel))))
2677 (let (buffer-read-only pad cur spec output found)
2678 (cl-flet
2679 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2680 (goto-char (point-min))
2681 (save-excursion
2682 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2683 (point-max) t)
2684 (unless pad
2685 (setq pad (make-string (- (match-beginning 1)
2686 (match-beginning 0))
2687 32)))
2688 (when (plist-get
2689 (setq spec
2690 (get (setq cur (intern (match-string 1)))
2691 :gnugo-gtp-command-spec))
2692 :full)
2693 (note "handles this command completely"))
2694 (when (setq output (plist-get spec :output))
2695 (if (functionp output)
2696 (note "handles the output specially")
2697 (case output
2698 (:discard (note "discards the output"))
2699 (:message (note "displays the output in the echo area")))))
2700 (when (eq sel cur)
2701 (setq found (match-beginning 0))))))
2702 (cond (found (goto-char found))
2703 ((not sel))
2704 (t (message "(no such command: %s)" sel)))))
2705
2706 (deffull final_score
2707 ;; Explicit ignorance avoids byte-compiler warning.
2708 (ignore sel)
2709 (gnugo-display-final-score))
2710
2711 (defgtp '(boardsize
2712 clear_board
2713 fixed_handicap)
2714 :output :discard
2715 :post-thunk (lambda ()
2716 (gnugo--unclose-game)
2717 (gnugo--forget :last-mover)
2718 ;; ugh
2719 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2720 (gnugo-refresh t)))
2721
2722 (deffull loadsgf
2723 (gnugo-read-sgf-file (car sel)))
2724
2725 (deffull (undo gg-undo)
2726 (gnugo--climb-towards-root
2727 (let (n)
2728 (cond ((not sel) 1)
2729 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2730 (t (validpos (car sel) t)))))))))
2731
2732 (provide 'gnugo)
2733
2734 \f
2735 ;;;---------------------------------------------------------------------------
2736 ;;; The remainder of this file defines a simplified SGF-handling library.
2737 ;;; When/if it should start to attain generality, it should be split off into
2738 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2739 ;;; "gnugo/" prefix.
2740
2741 (defconst gnugo/sgf-*r4-properties*
2742 '((AB "Add Black" setup list stone)
2743 (AE "Add Empty" game list point)
2744 (AN "Annotation" game simpletext)
2745 (AP "Application" root (simpletext . simpletext))
2746 (AR "Arrow" - list (point . point))
2747 (AS "Who adds stones" - simpletext) ; (LOA)
2748 (AW "Add White" setup list stone)
2749 (B "Black" move move)
2750 (BL "Black time left" move real)
2751 (BM "Bad move" move double)
2752 (BR "Black rank" game simpletext)
2753 (BT "Black team" game simpletext)
2754 (C "Comment" - text)
2755 (CA "Charset" root simpletext)
2756 (CP "Copyright" game simpletext)
2757 (CR "Circle" - list point)
2758 (DD "Dim points" - elist point) ; (inherit)
2759 (DM "Even position" - double)
2760 (DO "Doubtful" move none)
2761 (DT "Date" game simpletext)
2762 (EV "Event" game simpletext)
2763 (FF "Fileformat" root [number (1 . 4)])
2764 (FG "Figure" - (or none (number . simpletext)))
2765 (GB "Good for Black" - double)
2766 (GC "Game comment" game text)
2767 (GM "Game" root [number (1 . 20)])
2768 (GN "Game name" game simpletext)
2769 (GW "Good for White" - double)
2770 (HA "Handicap" game number) ; (Go)
2771 (HO "Hotspot" - double)
2772 (IP "Initial pos." game simpletext) ; (LOA)
2773 (IT "Interesting" move none)
2774 (IY "Invert Y-axis" game simpletext) ; (LOA)
2775 (KM "Komi" game real) ; (Go)
2776 (KO "Ko" move none)
2777 (LB "Label" - list (point . simpletext))
2778 (LN "Line" - list (point . point))
2779 (MA "Mark" - list point)
2780 (MN "set move number" move number)
2781 (N "Nodename" - simpletext)
2782 (OB "OtStones Black" move number)
2783 (ON "Opening" game text)
2784 (OT "Overtime" game simpletext)
2785 (OW "OtStones White" move number)
2786 (PB "Player Black" game simpletext)
2787 (PC "Place" game simpletext)
2788 (PL "Player to play" setup color)
2789 (PM "Print move mode" - number) ; (inherit)
2790 (PW "Player White" game simpletext)
2791 (RE "Result" game simpletext)
2792 (RO "Round" game simpletext)
2793 (RU "Rules" game simpletext)
2794 (SE "Markup" - point) ; (LOA)
2795 (SL "Selected" - list point)
2796 (SO "Source" game simpletext)
2797 (SQ "Square" - list point)
2798 (ST "Style" root [number (0 . 3)])
2799 (SU "Setup type" game simpletext) ; (LOA)
2800 (SZ "Size" root (or number (number . number)))
2801 (TB "Territory Black" - elist point) ; (Go)
2802 (TE "Tesuji" move double)
2803 (TM "Timelimit" game real)
2804 (TR "Triangle" - list point)
2805 (TW "Territory White" - elist point) ; (Go)
2806 (UC "Unclear pos" - double)
2807 (US "User" game simpletext)
2808 (V "Value" - real)
2809 (VW "View" - elist point) ; (inherit)
2810 (W "White" move move)
2811 (WL "White time left" move real)
2812 (WR "White rank" game simpletext)
2813 (WT "White team" game simpletext)
2814 (LT "Lose on time" setup simpletext))
2815 ;; r4-specific notes
2816 ;; - changed: DT FG LB RE RU SZ
2817 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2818 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2819
2820 (defun gnugo/sgf-create (file-or-data &optional data-p)
2821 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2822 FILE-OR-DATA is a file name or SGF[4] data.
2823 Optional arg DATA-P non-nil means FILE-OR-DATA is
2824 a string containing SGF[4] data.
2825 A collection is a list of gametrees, each a vector of four elements:
2826
2827 ENDS -- a vector of node lists, with shared tails
2828 (last element of all the lists is the root node)
2829
2830 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2831 have a move number of the previous \"move\" node (or zero)
2832
2833 ROOT -- the root node"
2834 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2835 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2836 (put 'gnugo/sgf-*r4-properties* :keywords
2837 (mapcar (lambda (full)
2838 (cons (car full)
2839 (intern (format ":%s" (car full)))))
2840 gnugo/sgf-*r4-properties*))))
2841 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2842 (put 'gnugo/sgf-*r4-properties* :specs
2843 (mapcar (lambda (full)
2844 (cons (car full) (cdddr full)))
2845 gnugo/sgf-*r4-properties*))))
2846 SZ)
2847 (cl-labels
2848 ((sw () (skip-chars-forward " \t\n"))
2849 (x (end preserve-whitespace)
2850 (let ((beg (point))
2851 (endp (case end
2852 (:end (lambda (char) (= ?\] char)))
2853 (:mid (lambda (char) (= ?\: char)))
2854 (t (lambda (char) (or (= ?\: char)
2855 (= ?\] char))))))
2856 c)
2857 (while (not (funcall endp (setq c (following-char))))
2858 (cond ((= ?\\ c)
2859 (delete-char 1)
2860 (if (eolp)
2861 (kill-line 1)
2862 (forward-char 1)))
2863 ((unless preserve-whitespace
2864 (looking-at "\\s-+"))
2865 (delete-region (point) (match-end 0))
2866 (insert " "))
2867 (t (forward-char 1))))
2868 (buffer-substring-no-properties beg (point))))
2869 (one (type end) (let ((s (progn
2870 (forward-char 1)
2871 (x end (eq 'text type)))))
2872 (case type
2873 ((stone point move)
2874 ;; blech, begone bu"tt"-ugly blatherings
2875 ;; (but bide brobdingnagian boards)...
2876 (if (and (string= "tt" s)
2877 SZ
2878 (>= 19 SZ))
2879 ""
2880 s))
2881 ((simpletext color) s)
2882 ((number real double) (string-to-number s))
2883 ((text) s)
2884 ((none) "")
2885 (t (error "Unhandled type: %S" type)))))
2886 (val (spec) (cond ((symbolp spec)
2887 (one spec :end))
2888 ((vectorp spec)
2889 ;; todo: check range here.
2890 (one (aref spec 0) :end))
2891 ((eq 'or (car spec))
2892 (let ((v (one (cadr spec) t)))
2893 (if (= ?\] (following-char))
2894 v
2895 (forward-char 1)
2896 ;; todo: this assumes `spec' has the form
2897 ;; (or foo (foo . bar))
2898 ;; i.e., foo is not rescanned. e.g., `SZ'.
2899 ;; probably this assumption is consistent
2900 ;; w/ the SGF authors' desire to make the
2901 ;; parsing easy, but you never know...
2902 (cons v (one (cdaddr spec) :end)))))
2903 (t (cons (one (car spec) :mid)
2904 (one (cdr spec) :end)))))
2905 (short (who) (when (eobp)
2906 (error "Unexpected EOF while reading %s" who)))
2907 (atvalp () (= ?\[ (following-char)))
2908 (PROP () (let (name spec ltype)
2909 (sw) (short 'property)
2910 (when (looking-at "[A-Z]")
2911 (setq name (read (current-buffer))
2912 spec (cdr (assq name specs)))
2913 (sw)
2914 (cons
2915 (cdr (assq name keywords))
2916 (prog1 (if (= 1 (length spec))
2917 (val (car spec))
2918 (unless (memq (setq ltype (car spec))
2919 '(elist list))
2920 (error "Bad spec: %S" spec))
2921 (if (and (eq 'elist ltype) (sw)
2922 (not (atvalp)))
2923 nil
2924 (let ((type (cadr spec))
2925 mo ls)
2926 (while (and (sw) (atvalp)
2927 (setq mo (val type)))
2928 (push mo ls)
2929 (forward-char 1))
2930 (forward-char -1)
2931 (nreverse ls))))
2932 (forward-char 1))))))
2933 (morep () (and (sw) (not (eobp))))
2934 (seek (c) (and (morep) (= c (following-char))))
2935 (seek-into (c) (when (seek c)
2936 (forward-char 1)
2937 t))
2938 (NODE () (when (seek-into ?\;)
2939 (loop with prop
2940 while (setq prop (PROP))
2941 collect (progn
2942 (when (eq :SZ (car prop))
2943 (setq SZ (cdr prop)))
2944 prop))))
2945 (TREE (parent mnum)
2946 (let ((ls parent)
2947 prev node)
2948 (seek-into ?\()
2949 (while (seek ?\;)
2950 (setq prev (car ls)
2951 node (NODE))
2952 (puthash node (+ (if (gnugo--move-prop node)
2953 1
2954 0)
2955 (gethash prev mnum 0))
2956 mnum)
2957 (push node
2958 ls))
2959 (prog1
2960 (if (not (seek ?\())
2961 ;; singular
2962 (list ls)
2963 ;; multiple
2964 (loop while (seek ?\()
2965 append (TREE ls mnum)))
2966 (seek-into ?\))))))
2967 (with-temp-buffer
2968 (if (not data-p)
2969 (insert-file-contents file-or-data)
2970 (insert file-or-data)
2971 (goto-char (point-min)))
2972 (loop while (morep)
2973 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2974 (ends (TREE nil mnum))
2975 (root (car (last (car ends)))))
2976 (vector (apply 'vector ends)
2977 mnum
2978 root)))))))
2979
2980 (defun gnugo/sgf-write-file (collection filename)
2981 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2982 (me (cons "gnugo.el" gnugo-version))
2983 (specs (mapcar (lambda (full)
2984 (cons (intern (format ":%s" (car full)))
2985 (cdddr full)))
2986 gnugo/sgf-*r4-properties*))
2987 p name v spec)
2988 (cl-labels
2989 ((esc (composed fmt arg)
2990 (mapconcat (lambda (c)
2991 (case c
2992 ;; ‘?\[’ is not strictly required
2993 ;; but neither is it forbidden.
2994 ((?\[ ?\] ?\\) (format "\\%c" c))
2995 (?: (concat (if composed "\\" "") ":"))
2996 (t (string c))))
2997 (string-to-list (format fmt arg))
2998 ""))
2999 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
3000 (>>two (v) (insert "["
3001 (esc t "%s" (car v))
3002 ":"
3003 (esc t "%s" (cdr v))
3004 "]"))
3005 (>>nl () (cond ((memq name aft-newline-appreciated)
3006 (insert "\n"))
3007 ((< 60 (current-column))
3008 (save-excursion
3009 (goto-char p)
3010 (insert "\n")))))
3011 (>>prop (prop)
3012 (setq p (point)
3013 name (car prop)
3014 v (cdr prop))
3015 (insert (substring (symbol-name name) 1))
3016 (cond ((not v))
3017 ((and (consp v)
3018 (setq spec (cdr (assq name specs)))
3019 (memq (car spec)
3020 '(list elist)))
3021 (>>nl)
3022 (let ((>> (if (consp (cadr spec))
3023 #'>>two
3024 #'>>one)))
3025 (dolist (little-v v)
3026 (setq p (point))
3027 (funcall >> little-v)
3028 (>>nl))))
3029 ((consp v)
3030 (>>two v) (>>nl))
3031 (t
3032 (>>one v) (>>nl))))
3033 (>>node (node)
3034 (loop initially (insert ";")
3035 for prop in node
3036 do (>>prop prop)))
3037 (>>tree (tree)
3038 (unless (zerop (current-column))
3039 (newline))
3040 (insert "(")
3041 (dolist (x tree)
3042 (funcall (if (gnugo--nodep x)
3043 #'>>node
3044 #'>>tree)
3045 x))
3046 (insert ")")))
3047 (with-temp-buffer
3048 (dolist (tree collection)
3049 ;; take responsibility for our actions
3050 (gnugo--set-root-prop :AP me tree)
3051 ;; write it out
3052 (let ((ht (gnugo--mkht))
3053 (leaves (append (gnugo--tree-ends tree) nil)))
3054 (cl-flet
3055 ((hang (stack)
3056 (loop
3057 with rh ; rectified history
3058 with bp ; branch point
3059 for node in stack
3060 until (setq bp (gethash node ht))
3061 do (puthash node
3062 (push node rh) ; good for now: ½τ
3063 ht)
3064 finally return
3065 (if (not bp)
3066 ;; first run: main line
3067 rh
3068 ;; subsequent runs: grafts (value discarded)
3069 (setcdr bp (nconc
3070 ;; Maintain order of ‘leaves’.
3071 (let ((was (cdr bp)))
3072 (if (gnugo--nodep (car was))
3073 (list was)
3074 was))
3075 (list rh)))))))
3076 (setq tree (hang (pop leaves)))
3077 (mapc #'hang leaves)
3078 (>>tree tree))))
3079 (newline)
3080 (write-file filename)))))
3081
3082 ;;; gnugo.el ends here