1 ;;; gnugo.el --- play GNU Go in a buffer -*- lexical-binding: t -*-
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
6 ;; Maintainer: Thien-Thi Nguyen <ttn@gnu.org>
8 ;; Package-Requires: ((ascii-art-to-unicode "1.5"))
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
28 ;; This file provides the command `gnugo' which allows you to play the game of
29 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
30 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
31 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
32 ;; Go" to refer to the process object created by running the external program.
34 ;; At the start of a new game, you can pass additional command-line arguments
35 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
36 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
37 ;; both komi and handicap.
39 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
40 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
41 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
42 ;; back through an arbitrary stone that you played, place the cursor on a
43 ;; stone and type `U' (note: uppercase).
45 ;; There are a great many other commands. Other keybindings are described in
46 ;; the `gnugo-board-mode' documentation, which you may view with the command
47 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
48 ;; the last move and who is currently to play. Capture counts and other info
49 ;; are shown on the mode line immediately following the major mode name.
51 ;; While GNU Go is pondering its next move, certain commands that rely on its
52 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
53 ;; is normal. When it is your turn again you may retry the command. In the
54 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
55 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
57 ;; If GNU Go should crash during a game the mode line will show "no process".
58 ;; Please report the event to the GNU Go maintainers so that they can improve
62 ;; Meta-Playing (aka Customizing)
63 ;; ------------------------------
65 ;; Customization is presently limited to
66 ;; vars: `gnugo-program'
67 ;; `gnugo-animation-string'
69 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
70 ;; `gnugo-undo-reaction'
72 ;; normal hooks: `gnugo-board-mode-hook'
73 ;; `gnugo-frolic-mode-hook'
74 ;; `gnugo-start-game-hook'
75 ;; `gnugo-post-move-hook'
76 ;; and the keymaps: `gnugo-board-mode-map'
77 ;; `gnugo-frolic-mode-map'
80 ;; Meta-Meta-Playing (aka Hacking)
81 ;; -------------------------------
83 ;; <http://git.sv.gnu.org/cgit/emacs/elpa.git/tree/packages/gnugo/HACKING>
89 ;; <http://www.gnuvola.org/software/gnugo/>
93 (eval-when-compile (require 'cl)) ; use the source luke!
94 (require 'ascii-art-to-unicode) ; for `aa2u'
95 (require 'time-date) ; for `time-subtract'
97 ;;;---------------------------------------------------------------------------
100 (defconst gnugo-version "2.3.1"
101 "Version of gnugo.el currently loaded.
102 This follows a MAJOR.MINOR.PATCH scheme.")
104 ;;;---------------------------------------------------------------------------
105 ;;; Variables for the uninquisitive programmer
107 (defvar gnugo-program "gnugo"
108 "Name of the GNU Go program (executable file).
109 \\[gnugo] validates this using `executable-find'.
110 This program must accept command line args:
112 For more information on GTP and GNU Go, please visit:
113 <http://www.gnu.org/software/gnugo>")
115 (defvar gnugo-board-mode-map nil
116 "Keymap for GNUGO Board mode.")
118 (defvar gnugo-frolic-mode-map nil
119 "Keymap for GNUGO Frolic mode.")
121 (defvar gnugo-board-mode-hook nil
122 "Hook run when entering GNUGO Board mode.")
124 (defvar gnugo-start-game-hook nil
125 "Normal hook run immediately before the first move of the game.
126 To find out who is to move first, use `gnugo-current-player'.
127 See also `gnugo-board-mode'.")
129 (defvar gnugo-post-move-hook nil
130 "Normal hook run after a move and before the board is refreshed.
131 Initially, when `run-hooks' is called, the current buffer is the GNUGO
132 Board buffer of the game. Hook functions that switch buffers must take
133 care not to call (directly or indirectly through some other function)
134 `gnugo-put' or `gnugo-get' after the switch.")
136 (defvar gnugo-animation-string
137 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
138 (concat jam jam jam jam jam
139 ;; "SECRET MESSAGE HERE"
140 blink blink blink blink blink blink blink blink
141 ;; Playing go is like fighting ignorance: when you think you have
142 ;; surrounded something by knowing it very well it often turns
143 ;; out that in the time you spent deepening this understanding,
144 ;; other areas of ignorance have surrounded you.
145 spin spin spin spin spin spin spin spin spin
146 ;; Playing go is not like fighting ignorance: what one person
147 ;; knows many people may come to know; knowledge does not build
148 ;; solely move by move. Wisdom, on the other hand...
150 "String whose individual characters are used for animation.
151 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
152 render the stones in their respective result groups as the first character
153 in the string, then the next, and so on.")
155 (defvar gnugo-mode-line "~b ~w :~m :~u"
156 "A `mode-line-format'-compliant value for GNUGO Board mode.
157 If a single string, the following special escape sequences are
158 replaced with their associated information:
159 ~b,~w black,white captures (a number)
160 ~p current player (black or white)
162 ~t time waiting for the current move
163 ~u time taken for the Ultimate (most recent) move
164 The times are in seconds, or \"-\" if that information is not available.
165 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
167 (defvar gnugo-X-face 'font-lock-string-face
168 "Name of face to use for X (black) stones.")
170 (defvar gnugo-O-face 'font-lock-builtin-face
171 "Name of face to use for O (white) stones.")
173 (defvar gnugo-grid-face 'default
174 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
176 (defvar gnugo-undo-reaction 'play!
177 "What to do if undo (or oops) leaves GNU Go to play.
178 After `gnugo-undo-one-move', `gnugo-undo-two-moves' or `gnugo-oops',
179 when GNU Go is to play, this can be a symbol:
180 play -- make GNU Go play (unless in Zombie mode)
181 play! -- make GNU Go play unconditionally (traditional behavior)
182 zombie -- enable Zombie mode (`gnugo-zombie-mode')
183 one-shot -- like `zombie' but valid only for the next move
184 Any other value, or (as a special case) for `gnugo-undo-one-move',
185 any value other than `zombie', is taken as `one-shot'. Note that
186 making GNU Go play will probably result in the recently-liberated
187 board position becoming re-occupied.")
189 (defvar gnugo-xpms nil
190 "List of 46 ((TYPE . LOCATION) . XPM-IMAGE) forms.
191 XPM-IMAGE is an image as returned by `create-image' with
192 inline data (i.e., property :data with string value).
194 TYPE is a symbol, one of:
195 hoshi -- unoccupied position with dot
196 empty -- unoccupied position sans dot
197 bpmoku, bmoku -- black stone with and sans highlight point
198 wpmoku, wmoku -- white stone with and sans highlight point
200 LOCATION is an integer encoding edge, corner, or center:
204 For instance, 4 means \"left edge\", 9 means \"bottom right\".
206 There is only one location for hoshi: center. The other five
207 types each have all possible locations. So (+ 1 (* 9 5)) => 46.
209 The value can also be a function (satisfying `functionp') that
210 takes one arg, the size of the board, and returns the appropriate
213 ;;;---------------------------------------------------------------------------
214 ;;; Variables for the inquisitive programmer
216 (defconst gnugo-font-lock-keywords
217 '(("X" . gnugo-X-face)
218 ("O" . gnugo-O-face))
219 "Font lock keywords for `gnugo-board-mode'.")
221 (defvar gnugo-option-history nil)
223 (defvar gnugo-state nil) ; hint: C-c C-p
225 (defvar gnugo-frolic-parent-buffer nil)
226 (defvar gnugo-frolic-origin nil)
228 (defvar gnugo-btw nil)
230 ;;;---------------------------------------------------------------------------
231 ;;; Support functions
233 (defsubst gnugo--mkht (&rest etc)
234 (apply 'make-hash-table :test 'eq etc))
236 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
237 (compare-strings s1 beg1 nil s2 beg2 nil))
239 (defun gnugo-put (key value)
240 "Associate move/game/board-specific property KEY with VALUE.
242 There are many properties, each named by a keyword, that record and control
243 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
244 of properties, stored in the hash table `gnugo-state'. Here we document
245 some of the more stable properties. You may wish to use them as part of
246 a `gnugo-post-move-hook' function, for example. Be careful to preserve
247 the current buffer as `gnugo-state' is made into a buffer-local variable.
248 NOTE: In the following, \"see foo\" actually means \"see foo source or
249 you may never really understand to any degree of personal satisfaction\".
251 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
253 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
255 :game-over -- nil until game over at which time its value is set to
256 the alist `((live GROUP ...) (dead GROUP ...))'
258 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
259 a simple list of one or more gametrees, updated in
260 conjunction w/ :sgf-gametree and :monkey
262 :sgf-gametree -- one of the gametrees in :sgf-collection
264 :monkey -- vector of two elements:
265 MEM, a pointer to one of the branches in the gametree;
266 BIDX, the index of the \"current branch\"
268 :gnugo-color -- either \"black\" or \"white\"
272 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
275 :black-captures -- these are strings since gnugo.el doesn't do anything
276 :white-captures w/ the information besides display it in the mode line;
277 gory details in functions `gnugo-propertize-board-buffer'
278 and `gnugo-merge-showboard-results' (almost more effort
279 than they are worth!)
281 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
282 `gnugo-toggle-image-display' and `gnugo-refresh',
283 as well as gnugo-xpms.el (available elsewhere)
285 :all-yy -- list of 46 symbols used as the `category' text property
286 (so that their plists, typically w/ property `display' or
287 `do-not-display') are consulted by the Emacs display engine;
288 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
289 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
291 :paren-ov -- a pair (left and right) of overlays shuffled about to indicate
292 the last move; only one is used when displaying using images
294 :last-user-bpos -- board position; keep the hapless human happy
296 As things stabilize probably more info will be added to this docstring."
298 (puthash key value gnugo-state))
300 (defun gnugo-get (key)
301 "Return the move/game/board-specific value for KEY.
303 (gethash key gnugo-state))
305 (defun gnugo--forget (&rest keys)
307 (remhash key gnugo-state)))
309 (defsubst gnugo--tree-mnum (tree)
312 (defsubst gnugo--tree-ends (tree)
315 (defsubst gnugo--set-tree-ends (tree ls)
316 (aset tree 0 (apply 'vector ls))
317 (gnugo--tree-ends tree))
319 (defun gnugo--root-node (&optional tree)
320 (aref (or tree (gnugo-get :sgf-gametree))
323 (defun gnugo-describe-internal-properties ()
324 "Pretty-print `gnugo-state' properties in another buffer.
325 Handle the big, slow-to-render, and/or uninteresting ones specially."
327 (let ((buf (current-buffer))
328 (d (gnugo-get :diamond))
329 (acc (loop for key being the hash-keys of gnugo-state
330 using (hash-values val)
334 (format "hash: %X (%d images)"
340 (list (hash-table-count
341 (gnugo--tree-mnum val))
342 (gnugo--root-node val)
343 (gnugo--tree-ends val)))
345 (let ((mem (aref val 0)))
349 (switch-to-buffer (get-buffer-create
350 (format "%s*GNUGO Board Properties*"
354 (setq truncate-lines t)
358 (goto-char (point-min))
359 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
363 (while (re-search-forward rx (point-max) t)
364 (let ((pos (get-text-property (string-to-number (match-string 1))
365 'gnugo-position buf)))
366 (delete-region (+ 2 (match-beginning 0)) (point))
367 (insert (format " %S" pos))))))
368 (message "%d properties" (length acc))))
370 (defun gnugo-board-buffer-p (&optional buffer)
371 "Return non-nil if BUFFER is a GNUGO Board buffer."
372 (eq 'gnugo-board-mode
375 (or buffer (current-buffer)))))
377 (defun gnugo-board-user-play-ok-p (&optional buffer)
378 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
379 (with-current-buffer (or buffer (current-buffer))
380 (and gnugo-state (not (gnugo-get :waiting)))))
382 (defsubst gnugo--blackp (string)
383 (string= "black" string))
385 (defun gnugo-other (color)
386 (if (gnugo--blackp color) "white" "black"))
388 (defun gnugo-current-player ()
389 "Return the current player, either \"black\" or \"white\"."
390 (gnugo-other (gnugo-get :last-mover)))
392 (defsubst gnugo--prop<-color (color)
393 (if (gnugo--blackp color) :B :W))
395 (defun gnugo-gate (&optional in-progress-p)
396 (unless (gnugo-board-buffer-p)
397 (user-error "Wrong buffer -- try M-x gnugo"))
398 (unless (gnugo-get :proc)
399 (user-error "No \"gnugo\" process!"))
400 (destructuring-bind (&optional color . suggestion)
404 "%s -- please wait for \"(%s to play)\""
406 (list "Still thinking"
408 (list "Not your turn yet"
409 (gnugo-other color))))))
410 (when (and in-progress-p (gnugo-get :game-over))
411 (user-error "Sorry, game over")))
413 (defun gnugo-sentinel (proc string)
414 (let ((status (process-status proc)))
415 (when (memq status '(exit signal))
416 (let ((buf (process-buffer proc)))
417 (when (buffer-live-p buf)
418 (with-current-buffer buf
419 (setq mode-line-process
421 (propertize (car (split-string string))
422 'face 'font-lock-warning-face)
424 (when (eq proc (gnugo-get :proc))
425 (gnugo--forget :proc))))))))
427 (defun gnugo--begin-exchange (proc filter line)
428 (declare (indent 2)) ; good time, for a rime
429 ; nice style, for a wile...
430 (set-process-filter proc filter)
431 (process-send-string proc line)
432 (process-send-string proc "\n"))
434 (defun gnugo--q (fmt &rest args)
435 "Send formatted command \"FMT ARGS...\"; wait for / return response.
436 The response is a string whose first two characters indicate the
437 status of the command. See also `gnugo-query'."
438 (let ((slow (gnugo-get :waiting))
439 (proc (gnugo-get :proc)))
441 (user-error "Sorry, still waiting for %s to %s"
442 (car slow) (if (cdr slow)
443 "receive a suggestion"
445 (process-put proc :incomplete t)
446 (process-put proc :srs "") ; synchronous return stash
447 (gnugo--begin-exchange
448 proc (lambda (proc string)
449 (let ((full (concat (process-get proc :srs)
451 (process-put proc :srs full)
452 (unless (numberp (gnugo--compare-strings
453 full (max 0 (- (length full)
456 (process-put proc :incomplete nil))))
459 (apply #'format fmt args)))
460 (while (process-get proc :incomplete)
461 (accept-process-output proc 30))
462 (prog1 (substring (process-get proc :srs) 0 -2)
463 (process-put proc :srs ""))))
465 (defsubst gnugo--no-worries (string)
466 (= ?= (aref string 0)))
468 (defun gnugo--q/ue (fmt &rest args)
469 (let ((ans (apply 'gnugo--q fmt args)))
470 (unless (gnugo--no-worries ans)
471 (user-error "%s" ans))
474 (defun gnugo-query (message-format &rest args)
475 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
476 Return a string that omits the first two characters (corresponding
477 to the status indicator in the Go Text Protocol). Use this function
478 when you are sure the command cannot fail."
479 (substring (apply 'gnugo--q message-format args)
482 (defun gnugo--nquery (cmd)
483 (string-to-number (gnugo-query cmd)))
485 (defun gnugo-lsquery (message-format &rest args)
486 (split-string (apply 'gnugo-query message-format args)))
488 (defsubst gnugo--count-query (fmt &rest args)
489 (length (apply 'gnugo-lsquery fmt args)))
491 (defsubst gnugo--root-prop (prop &optional tree)
492 (cdr (assq prop (gnugo--root-node tree))))
494 (defun gnugo--set-root-prop (prop value &optional tree)
495 (let* ((root (gnugo--root-node tree))
496 (cur (assq prop root)))
499 (push (cons prop value)
500 (cdr (last root))))))
502 (defun gnugo-goto-pos (pos)
503 "Move point to board position POS, a letter-number string."
504 (goto-char (point-min))
505 (forward-line (- (1+ (gnugo-get :SZ))
506 (string-to-number (substring pos 1))))
508 (forward-char (+ (if (= 32 (following-char)) 1 2)
509 (* 2 (- (let ((letter (aref pos 0)))
516 (intern (if (symbolp id)
519 (gnugo-get :obarray)))
521 (defun gnugo-yang (c)
522 (cdr (assq c '((?+ . hoshi)
524 (?X . (bmoku . bpmoku))
525 (?O . (wmoku . wpmoku))))))
527 (defun gnugo-yy (yin yang &optional momentaryp)
528 (gnugo-f (format "%d-%s"
529 yin (cond ((symbolp yang) yang)
530 (momentaryp (cdr yang))
533 (defun gnugo-toggle-image-display ()
534 (unless (display-images-p)
535 (user-error "Display does not support images, sorry"))
536 (let ((fresh (if (functionp gnugo-xpms)
537 (funcall gnugo-xpms (gnugo-get :SZ))
540 (user-error "Sorry, `gnugo-xpms' unset"))
541 (unless (eq fresh (gnugo-get :xpms))
542 (gnugo-put :xpms fresh)
543 (gnugo--forget :all-yy)))
544 (let* ((new (not (gnugo-get :display-using-images)))
545 (act (if new 'display 'do-not-display)))
547 (setcar (symbol-plist yy) act))
548 (or (gnugo-get :all-yy)
550 (prog1 (mapcar (lambda (ent)
552 (yy (gnugo-yy (cdr k) (car k))))
553 (setplist yy `(not-yet ,(cdr ent)))
557 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
559 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
560 (gnugo-put :highlight-last-move-spec
563 (get (gnugo-yy (get-text-property p 'gnugo-yin)
564 (get-text-property p 'gnugo-yang)
568 (gnugo-get :default-highlight-last-move-spec)))
569 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
570 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
571 (mapc 'delete-overlay (cdar group))
572 (setcdr (car group) nil))
573 (gnugo-put :mul (if new
576 (gnugo-put :display-using-images new)))
578 (define-minor-mode gnugo-grid-mode
579 "If enabled, display grid around the board."
581 ((not (memq :nogrid buffer-invisibility-spec))
585 'remove-from-invisibility-spec
586 'add-to-invisibility-spec)
588 (save-excursion (gnugo-refresh)))))
590 (defun gnugo-propertize-board-buffer ()
592 (insert (substring (gnugo--q "showboard") 3))
593 (let* ((grid-props (list 'invisible :nogrid
594 'font-lock-face gnugo-grid-face))
595 (%gpad (gnugo-f 'gpad))
596 (%gspc (gnugo-f 'gspc))
597 (%lpad (gnugo-f 'lpad))
598 (%rpad (gnugo-f 'rpad))
599 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
600 (size (gnugo-get :SZ))
601 (size-string (number-to-string size)))
602 (goto-char (point-min))
603 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
604 (skip-chars-forward " ")
605 (put-text-property (1- (point)) (point) 'category %gpad)
606 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
608 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
609 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
610 (let* ((row (match-string-no-properties 1))
612 (other-edge (+ edge (* 2 size) -1))
613 (right-empty (+ other-edge (length row) 1))
614 (top-p (string= size-string row))
615 (bot-p (string= "1" row)))
616 (let* ((nL (- edge 1 (length size-string)))
618 (ov (make-overlay nL nR (current-buffer) t)))
619 (add-text-properties nL nR grid-props)
620 ;; We redundantly set `invisible' in the overlay to workaround
621 ;; a display bug whereby text *following* the overlaid text is
622 ;; displayed with the face of the overlaid text, but only when
623 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
624 ;; This has something to do w/ the bletcherous `before-string'.
625 (overlay-put ov 'invisible :nogrid)
626 (overlay-put ov 'category %lpad))
627 (do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
629 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
630 (truncate (- p edge) 2))
632 (yin (let ((A-p (= edge p))
633 (Z-p (= (1- other-edge) p)))
634 (cond ((and top-p A-p) 1)
643 (yang (gnugo-yang (char-after p))))
644 (add-text-properties p (1+ p)
654 (gnugo-position gnugo-yin))))
655 (unless (= (1- other-edge) p)
656 (add-text-properties (1+ p) (+ 2 p) ispc-props)
657 (put-text-property p (+ 2 p) 'intangible ival)))
658 (add-text-properties (1+ other-edge) right-empty grid-props)
659 (goto-char right-empty)
660 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
661 (let ((prop (if (string= "WH" (match-string 1))
664 (beg (match-beginning 2))
666 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
667 (gnugo-put prop (match-string-no-properties 2))))
669 (put-text-property right-empty (point) 'category %rpad)
671 (add-text-properties (1- (point)) (point-max) grid-props)
672 (skip-chars-forward " ")
673 (put-text-property (1- (point)) (point) 'category %gpad)
674 (put-text-property (point) (progn (end-of-line) (point))
677 (defun gnugo-merge-showboard-results ()
678 (let ((aft (substring (gnugo--q "showboard") 3))
679 (adj 1) ; string to buffer position adjustment
681 (sync "[0-9]* stones$")
682 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
683 ;; restrictive a condition that fails in the case of:
686 ;; ... WHITE has captured 1 stones
689 ;; ... WHITE has captured 14 stones
692 ;; where the after count has more digits than the before count,
693 ;; but shares the same leading digits. In this case, the result
694 ;; of `compare-strings' points to the SPC following the before
695 ;; count (indicated by caret in this example).
697 (bef (buffer-substring-no-properties (point-min) (point-max)))
698 (bef-start 0) (bef-idx 0)
699 (aft-start 0) (aft-idx 0)
700 aft-sync-backtrack mis inc cut new very-strange
702 (inhibit-read-only t))
703 (while (numberp (setq mis (gnugo--compare-strings
706 (setq aft-sync-backtrack nil
707 inc (if (cl-minusp mis)
710 bef-idx (+ bef-start inc)
711 aft-idx (+ aft-start inc)
712 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
715 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
716 (let ((peek (1- aft-idx)))
717 (while (not (= 32 (aref aft peek)))
718 (setq peek (1- peek)))
719 (setq aft-sync-backtrack (1+ peek))))
723 (if aft-sync-backtrack
724 (- aft-sync-backtrack aft-idx)
727 (if aft-sync-backtrack
728 (let* ((asb aft-sync-backtrack)
729 (l-p (get-text-property cut :gnugo-cf))
732 (keep (text-properties-at cut)))
733 (setq new (substring aft asb (string-match " " aft asb)))
734 (plist-put keep :gnugo-cf (cons (length new) capprop))
735 (gnugo-put capprop new)
736 (delete-char old-len)
737 (insert (apply 'propertize new keep))
738 (incf adj (- (length new) old-len)))
739 (setq new (aref aft aft-idx))
740 (insert-and-inherit (char-to-string new))
741 (let ((yin (get-text-property cut 'gnugo-yin))
742 (yang (gnugo-yang new)))
743 (add-text-properties cut (1+ cut)
747 ,(gnugo-yy yin yang))))
749 ;; do this last to avoid complications w/ font lock
750 ;; (this also means we cannot include `intangible' in `front-sticky')
751 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
752 (put-text-property cut (1+ cut) 'intangible very-strange))))))
754 (defsubst gnugo--move-prop (node)
758 (defun gnugo--as-pos-func ()
759 (lexical-let ((size (gnugo-get :SZ)))
764 (let ((col (aref cc 0)))
766 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
767 (- size (- (aref cc 1) ?a))))))))
769 (defsubst gnugo--resignp (string)
770 (string= "resign" string))
772 (defsubst gnugo--passp (string)
773 (string= "PASS" string))
775 (defun gnugo-move-history (&optional rsel color)
776 "Determine and return the game's move history.
777 Optional arg RSEL controls side effects and return value.
778 If nil, display the history in the echo area as \"(N moves)\"
779 followed by the space-separated list of moves. When called
780 interactively with a prefix arg (i.e., RSEL is `(4)'), display
781 similarly, but suffix with the mover (either \":B\" or \":W\").
782 RSEL may also be a symbol that selects what to return:
783 car -- the most-recent move
784 cadr -- the next-to-most-recent move
785 two -- the last two moves as a list, oldest last
786 bpos -- the last stone on the board placed by COLOR
787 For all other values of RSEL, do nothing and return nil."
789 (let* ((monkey (gnugo-get :monkey))
790 (mem (aref monkey 0))
791 (as-pos (gnugo--as-pos-func))
794 ((as-pos-maybe (x) (if (gnugo--resignp x)
797 (remem () (setq node (pop mem)
798 mprop (gnugo--move-prop node)))
799 (next (byp) (when (remem)
800 (setq move (as-pos-maybe (cdr mprop)))
802 (format "%s%s" move (car mprop))
806 (tell () (message "(%d moves) %s"
808 (mapconcat 'identity (nreverse acc) " ")))
809 (finish (byp) (while mem (next byp)) (tell)))
814 (`cadr (nn) (car (nn)))
816 (`bpos (loop with prop = (gnugo--prop<-color color)
819 (eq prop (car mprop))
820 (setq move (cdr mprop))
821 ;; i.e., "normal CC" position
823 return (funcall as-pos move)))
826 (define-derived-mode gnugo-frolic-mode special-mode "GNUGO Frolic"
827 "A special mode for manipulating a GNUGO gametree.
829 \\{gnugo-frolic-mode-map}"
830 (setq truncate-lines t)
831 (buffer-disable-undo))
833 (defun gnugo-frolic-quit ()
834 "Kill GNUGO Frolic buffer and switch to its parent buffer."
836 (let ((bye (current-buffer)))
837 (switch-to-buffer (when (buffer-live-p gnugo-frolic-parent-buffer)
838 gnugo-frolic-parent-buffer))
841 (defun gnugo-frolic-return-to-origin ()
842 "Move point to the board's current position."
844 (if (not gnugo-frolic-origin)
845 (message "No origin")
846 (goto-char gnugo-frolic-origin)
847 (recenter (- (count-lines (line-beginning-position)
850 (defun gnugo-frolic-in-the-leaves ()
851 "Display the game tree in a *GNUGO Frolic* buffer.
852 This looks something like:
855 2 W -- K10 K10 K10 K10
874 with 0, 1, ... N (in this case N is 3) in the header line
875 to indicate the branches. Branch 0 is the \"main line\".
876 Point (* in this example) indicates the current position,
877 \"!\" indicates comment properties (e.g., B8, branch 1),
878 and moves not actually on the game tree (e.g., E7, branch 3)
879 are dimmed. Type \\[describe-mode] in that buffer for details."
881 (let* ((buf (get-buffer-create (concat (gnugo-get :diamond)
883 (from (or gnugo-frolic-parent-buffer
885 ;; todo: use defface once we finally succumb to ‘customize’
886 (dimmed-node-face (list :inherit 'default
887 :foreground "gray50"))
888 (tree (gnugo-get :sgf-gametree))
889 (ends (copy-sequence (gnugo--tree-ends tree)))
890 (mnum (gnugo--tree-mnum tree))
893 (width (length ends))
894 (lanes (number-sequence 0 (1- width)))
895 (monkey (gnugo-get :monkey))
896 (as-pos (gnugo--as-pos-func))
897 (at (car (aref monkey 0)))
898 (bidx (aref monkey 1))
899 (valid (map 'vector (lambda (end)
900 (gethash (car end) mnum))
902 (max-move-num (apply 'max (append valid nil)))
903 (inhibit-read-only t)
909 (propertize s 'face face))
910 (fsi (properties fmt &rest args)
911 (insert (apply 'propertize
912 (apply 'format fmt args)
919 for node in (aref ends bx)
920 do (if (setq fork (on node))
923 ;; todo: ignore non-"move" nodes
924 (eq node (car (aref ends bix))))
926 (pushnew other (gethash node soil))))
931 (puthash node bx seen))
934 (switch-to-buffer buf)
937 (setq header-line-format
938 (lexical-let ((full (concat
940 (mapconcat (lambda (n)
950 `(space :width ,w))))
952 (when (eq 'left scroll-bar-mode)
953 (let ((w (or scroll-bar-width
955 nil 'scroll-bar-width)))
956 (cw (frame-char-width)))
960 (let ((fc (fringe-columns 'left t)))
964 (substring full (window-hscroll))
966 (set (make-local-variable 'gnugo-frolic-parent-buffer) from)
967 (set (make-local-variable 'gnugo-state)
968 (buffer-local-value 'gnugo-state from))
972 from max-move-num downto 1
973 do (setq props (list 'n n))
978 (goto-char (point-min))
981 n (aref ["W" "B"] (logand 1 n))))
983 do (let* ((node (unless (< (aref valid bx) n)
984 ;; todo: ignore non-"move" nodes
985 (pop (aref ends bx))))
986 (zow (list* 'bx bx props))
990 (cdr (assq :C node))))
991 (s (cond ((not node) "")
992 ((not (setq move (gnugo--move-prop node))) "-")
993 (t (funcall as-pos (cdr move))))))
996 (push 'help-echo zow))
997 (when (and ok (setq br (gethash node soil)))
998 (push (cons bx (sort br '<))
1003 (cond ((and (eq at node)
1004 (or ok (= bx bidx)))
1006 (setq finish (point-marker)))
1007 (emph s (list :inherit 'default
1008 :foreground (frame-parameter
1009 nil 'cursor-color))))
1011 (emph s dimmed-node-face))
1014 (when (progn (fsi props "\n")
1015 (setq forks (nreverse forks)))
1016 (let* ((margin (make-string 11 ?\s))
1017 (heads (mapcar #'car forks))
1018 (tails (mapcar #'cdr forks)))
1020 ((spaced (lanes func)
1021 (mapconcat func lanes " "))
1022 ;; live to play ~ ~ ()
1023 ;; play to learn (+) (-) . o O
1024 ;; learn to live --ttn .M. _____U
1025 (dashed (lanes func) ;;; _____ ^^^^
1026 (mapconcat func lanes "-----"))
1028 (spaced lanes (lambda (bx)
1032 (pad-unless (condition)
1043 do (let* ((one (car ls))
1046 (mapcar 'car (cdr ls))
1048 (apply 'append (mapcar 'cdr bef))))
1051 (end (car (last ord))))
1053 ((also (b e) (cnxn (number-sequence b e)
1058 (pad-unless (zerop beg))
1059 (dashed (number-sequence beg end)
1061 (cond ((memq bx ord) "+")
1064 (pad-unless (>= end width))
1065 (also (1+ end) (1- width))
1068 (edge (apply 'append tails))
1069 (aa2u (line-beginning-position
1070 (- (1+ (length forks))))
1073 (set (make-local-variable 'gnugo-frolic-origin) finish)
1074 (gnugo-frolic-return-to-origin))))
1076 (defun gnugo--awake (how)
1077 ;; Valid HOW elements:
1078 ;; require-valid-branch
1080 ;; (line . move-string)
1081 ;; (omit . [VAR...])
1082 ;; Invalid elements blissfully ignored. :-D
1083 (let* ((tree (gnugo-get :sgf-gametree))
1084 (ends (gnugo--tree-ends tree))
1085 (width (length ends))
1086 (monkey (gnugo-get :monkey))
1087 (line (case (cdr (assq 'line how))
1089 (count-lines (point-min) (line-beginning-position)))
1092 (when (re-search-backward "^ *[0-9]+ [BW]" nil t)
1095 (col (current-column))
1096 (a (unless (> 10 col)
1097 (let ((try (/ (- col 10)
1099 (unless (<= width try)
1102 (when (memq 'require-valid-branch how)
1104 (user-error "No branch here")))
1105 (loop with omit = (cdr (assq 'omit how))
1106 for (name . value) in `((line . ,line)
1107 (bidx . ,(aref monkey 1))
1112 do (unless (memq name omit)
1116 (defmacro gnugo--awakened (how &rest body)
1117 (declare (indent 1))
1118 `(destructuring-bind ,(loop with omit = (cdr (assq 'omit how))
1120 for name in '(line bidx monkey
1123 do (unless (memq name omit)
1126 (gnugo--awake ',how)
1129 (defsubst gnugo--move-to-bcol (bidx)
1130 (move-to-column (+ 10 (* 6 bidx))))
1132 (defun gnugo--swiz (direction &optional blunt)
1133 (gnugo--awakened (require-valid-branch
1136 (let* ((b (cond ((numberp blunt)
1137 (unless (and (< -1 blunt)
1139 (user-error "No such branch: %s" blunt))
1141 (t (mod (+ direction a) width))))
1142 (flit (if blunt (lambda (n)
1147 (mod (+ direction n) width))))
1148 (was (copy-sequence ends))
1149 (new-bidx (funcall flit bidx)))
1150 (loop for bx below width
1151 do (aset ends (funcall flit bx)
1153 (unless (= new-bidx bidx)
1154 (aset monkey 1 new-bidx))
1155 (gnugo-frolic-in-the-leaves)
1156 (goto-char (point-min))
1158 (gnugo--move-to-bcol b))))
1160 (defun gnugo-frolic-exchange-left ()
1161 "Exchange the current branch with the one to its left."
1165 (defun gnugo-frolic-rotate-left ()
1166 "Rotate all branches left."
1170 (defun gnugo-frolic-exchange-right ()
1171 "Exchange the current branch with the one to its right."
1175 (defun gnugo-frolic-rotate-right ()
1176 "Rotate all branches right."
1180 (defun gnugo-frolic-set-as-main-line ()
1181 "Make the current branch the main line."
1183 (gnugo--swiz nil 0))
1185 (defun gnugo-frolic-prune-branch ()
1186 "Remove the current branch from the gametree.
1187 This fails if there is only one branch in the tree.
1188 This fails if the monkey is on the current branch
1189 \(a restriction that will probably be lifted Real Soon Now\)."
1191 (gnugo--awakened (require-valid-branch
1192 (line . move-string))
1193 ;; todo: define meaningful eviction semantics; remove restriction
1195 (user-error "Cannot prune with monkey on branch"))
1197 (user-error "Cannot prune last remaining branch"))
1198 (let ((new (append ends nil)))
1199 ;; Explicit ignorance avoids byte-compiler warning.
1200 (ignore (pop (nthcdr a new)))
1201 (gnugo--set-tree-ends tree new))
1203 (aset monkey 1 (decf bidx)))
1204 (gnugo-frolic-in-the-leaves)
1206 (goto-char (point-min))
1207 (search-forward line)
1208 (gnugo--move-to-bcol (min a (- width 2))))))
1210 (defun gnugo--sideways (backwards n)
1211 (gnugo--awakened ((omit tree ends monkey bidx line))
1212 (gnugo--move-to-bcol (mod (if backwards
1217 (defun gnugo-frolic-backward-branch (&optional n)
1218 "Move backward N (default 1) branches."
1220 (gnugo--sideways t n))
1222 (defun gnugo-frolic-forward-branch (&optional n)
1223 "Move forward N (default 1) branches."
1225 (gnugo--sideways nil n))
1227 (defun gnugo--vertical (n direction)
1230 direction (- direction)))
1231 (gnugo--awakened ((line . numeric)
1232 (omit tree ends width monkey bidx))
1233 (let ((stop (if (> 0 direction)
1235 (max 0 (1- (count-lines (point-min)
1239 (loop while (not (= line stop))
1241 (forward-line direction)
1242 (incf line direction))
1243 until (get-text-property (point) 'n))
1244 until (zerop (decf n)))
1246 (gnugo--move-to-bcol a)
1247 (move-to-column col)))))
1249 (defun gnugo-frolic-previous-move (&optional n)
1250 "Move to the Nth (default 1) previous move."
1252 (gnugo--vertical n -1))
1254 (defun gnugo-frolic-next-move (&optional n)
1255 "Move to the Nth (default 1) next move."
1257 (gnugo--vertical n 1))
1259 (defun gnugo-frolic-tip-move ()
1260 "Move to the tip of the current branch."
1262 (gnugo--awakened ((omit line bidx monkey width)
1263 require-valid-branch)
1264 (goto-char (point-max))
1265 (let ((mnum (gnugo--tree-mnum tree))
1266 (node (car (aref ends a))))
1267 (re-search-backward (format "^%3d" (gethash node mnum)))
1268 (gnugo--move-to-bcol a))))
1270 (defun gnugo-boss-is-near ()
1271 "Do `bury-buffer' until the current one is not a GNU Board."
1273 (while (gnugo-board-buffer-p)
1276 (defsubst gnugo--no-regrets (monkey ends)
1277 (eq (aref ends (aref monkey 1))
1280 (defun gnugo--as-cc-func ()
1281 (lexical-let ((size (gnugo-get :SZ)))
1283 (let* ((col (aref pos 0))
1284 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
1285 (two (+ ?a (- size (string-to-number
1286 (substring pos 1))))))
1287 (format "%c%c" one two)))))
1289 (defun gnugo--decorate (node &rest plist)
1290 (loop with tp = (last node)
1294 fruit (list (cons ; DWR: LtR OoE assumed.
1300 (defun gnugo-close-game (end-time resign)
1301 (gnugo-put :game-end-time end-time)
1302 (let ((now (or end-time (current-time))))
1303 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
1305 (gnugo-put :game-over
1306 (if (or (eq t resign)
1307 (and (stringp resign)
1308 (string-match "[BW][+][Rr]esign" resign)))
1310 ((ls (color) (mapcar
1315 (gnugo-query "worm_stones %s" color)
1317 (let ((live (append (ls "black") (ls "white"))))
1320 (let ((dd (gnugo-query "dragon_data"))
1321 (start 0) mem color ent live dead)
1322 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
1324 (setq mem (match-string 1 dd)
1325 color (match-string 2 dd)
1327 ent (cons (list color)
1328 (sort (gnugo-lsquery "dragon_stones %s" mem)
1330 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
1332 (if (match-string 2 dd)
1335 (setq start (match-end 0)))
1339 (defun gnugo--unclose-game ()
1340 (gnugo--forget :game-over ; all those in -close-game
1343 (let* ((root (gnugo--root-node))
1344 (cur (assq :RE root)))
1346 (assert (not (eq cur (car root))) nil
1347 ":RE at head of root node: %S"
1351 (defun gnugo-push-move (who move)
1352 (let* ((simple (booleanp who))
1353 (ucolor (gnugo-get :user-color))
1357 (gnugo-get :gnugo-color))
1359 (start (gnugo-get :waiting-start))
1360 (now (current-time))
1361 (resignp (gnugo--resignp move))
1362 (passp (gnugo--passp move))
1363 (head (gnugo-move-history 'car))
1364 (onep (and head (gnugo--passp head)))
1365 (donep (or resignp (and onep passp))))
1367 (gnugo--q/ue "play %s %s" color move))
1369 (gnugo-merge-showboard-results))
1370 (gnugo-put :last-mover color)
1373 (string= ucolor color))
1374 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
1375 ;; update :sgf-gametree and :monkey
1376 (let* ((property (gnugo--prop<-color color))
1377 (pair (cons property (cond (resignp move)
1379 (t (funcall (gnugo--as-cc-func)
1382 (monkey (gnugo-get :monkey))
1383 (mem (aref monkey 0))
1385 (tree (gnugo-get :sgf-gametree))
1386 (ends (gnugo--tree-ends tree))
1387 (mnum (gnugo--tree-mnum tree))
1388 (count (length ends))
1389 (tip-move-num (gethash tip mnum))
1390 (bidx (aref monkey 1)))
1391 ;; Detect déjà-vu. That is, when placing "A", avoid:
1397 ;; (such "variations" do not actually vary!) in favor of:
1403 ;; This linear search loses for multiple ‘old’ w/ "A",
1404 ;; a very unusual (but not invalid, sigh) situation.
1408 ;; Start with latest / highest likelihood for hit.
1409 ;; (See "to the right" comment, below.)
1410 from (if (gnugo--no-regrets monkey ends)
1414 if (setq bx (mod (+ bidx i) count)
1417 for m on (aref ends bx)
1418 while (< tip-move-num
1419 (gethash (setq node (car m))
1423 (when (equal pair (assq property node))
1431 (rotatef (aref ends bidx)
1433 (setq mem previous))
1437 (unless (gnugo--no-regrets monkey ends)
1438 (setq ends (gnugo--set-tree-ends
1439 tree (let ((ls (append ends nil)))
1440 ;; copy old to the right of new
1441 (push mem (nthcdr bidx ls))
1443 (puthash fruit (1+ (gethash tip mnum)) mnum)
1445 (aset ends bidx mem)))
1446 (setf (aref monkey 0) mem))
1448 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1450 (gnugo-close-game now resignp))
1451 (gnugo-put :waiting-start (and (not donep) now))
1454 (defun gnugo-venerate (yin yang)
1455 (let* ((fg-yy (gnugo-yy yin yang))
1456 (fg-disp (or (get fg-yy 'display)
1457 (get fg-yy 'do-not-display)))
1458 (fg-props (cdr fg-disp))
1459 (fg-data (plist-get fg-props :data))
1460 (c-symbs (plist-get fg-props :color-symbols))
1461 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1462 (bg-disp (or (get bg-yy 'display)
1463 (get bg-yy 'do-not-display)))
1464 (bg-data (plist-get (cdr bg-disp) :data))
1468 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1469 (setq start (match-end 0))
1470 (string-to-number (match-string 1 s)))))
1471 (while (and (not (cl-minusp ncolors))
1472 (string-match ",\n" s start))
1473 (setq start (match-end 0)
1474 ncolors (1- ncolors)))
1475 (string-match "\"" s start)
1477 (new (copy-sequence fg-data))
1478 (lx (length fg-data))
1479 (sx (funcall bop fg-data))
1480 (sb (funcall bop bg-data))
1481 (color-key (aref new sx))) ; blech, heuristic
1483 (when (and (not (= color-key (aref new sx)))
1484 (cl-plusp (random 4)))
1485 (aset new sx (aref bg-data sb)))
1488 (apply 'create-image new 'xpm t
1489 :ascent 'center (when c-symbs
1490 (list :color-symbols
1493 (defun gnugo-refresh (&optional nocache)
1494 "Update GNUGO Board buffer display.
1495 While a game is in progress, parenthesize the last-played stone (no parens
1496 for pass). If the buffer is currently displayed in the selected window,
1497 recenter the board (presuming there is extra space in the window). Update
1498 the mode line. Lastly, move point to the last position played by the user,
1499 if that move was not a pass.
1501 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1502 be slow. (This should normally be unnecessary; specify it only if the display
1503 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1506 (let* ((move (gnugo-move-history 'car))
1507 (game-over (gnugo-get :game-over))
1508 (inhibit-read-only t)
1510 (when (and nocache (not (gnugo-get :waiting)))
1511 (gnugo-propertize-board-buffer))
1514 (destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1515 (if (member move '("PASS" "resign"))
1516 (mapc 'delete-overlay (list l-ov r-ov))
1517 (gnugo-goto-pos move)
1519 (hspec (gnugo-get :highlight-last-move-spec))
1520 (display-value (nth 0 hspec))
1521 (l-offset (nth 1 hspec))
1522 (l-new-pos (+ p l-offset))
1523 (r-action (nth 2 hspec)))
1524 (overlay-put l-ov 'display
1525 (if (functionp display-value)
1526 (funcall display-value p)
1528 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1530 (funcall r-action r-ov)
1531 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1533 (rename-buffer (concat (gnugo-get :diamond)
1535 (format "%s(game over)"
1536 (if (gnugo--resignp move)
1537 (concat move "ation ")
1539 (format "%s(%s to play)"
1540 (if move (concat move " ") "")
1541 (gnugo-current-player)))))
1544 (let ((live (cdr (assq 'live game-over)))
1545 (dead (cdr (assq 'dead game-over)))
1547 (unless (eq game-over (get-text-property 1 'game-over))
1548 (dolist (group (append live dead))
1549 (dolist (pos (cdr group))
1550 (gnugo-goto-pos pos)
1552 (put-text-property p (1+ p) 'group group)))
1553 (put-text-property 1 2 'game-over game-over))
1554 (dolist (group live)
1555 (when (setq pall (cdar group))
1556 (mapc 'delete-overlay pall)
1557 (setcdr (car group) nil)))
1558 (dolist (group dead)
1559 (unless (cdar group)
1560 (let (ov pall c (color (caar group)))
1561 (setq c (if (gnugo--blackp color) "x" "o"))
1562 (dolist (pos (cdr group))
1563 (gnugo-goto-pos pos)
1564 (setq p (point) ov (make-overlay p (1+ p)))
1567 (if (gnugo-get :display-using-images)
1568 ;; respect the dead individually; it takes more time
1569 ;; but that's not a problem (for them)
1570 (gnugo-venerate (get-text-property p 'gnugo-yin)
1571 (gnugo-yang (aref (upcase c) 0)))
1572 (propertize c 'face 'font-lock-warning-face)))
1574 (setcdr (car group) pall))))))
1576 (when (setq window (get-buffer-window (current-buffer)))
1577 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1578 (size (gnugo-get :SZ))
1579 (under10p (< size 10))
1580 (mul (gnugo-get :mul))
1581 (h (- (truncate (- (window-height window)
1586 (edges (window-edges window))
1587 (right-w-edge (nth 2 edges))
1588 (avail-width (- right-w-edge (nth 0 edges)))
1590 (imagesp (symbol-plist (gnugo-f 'ispc)))
1591 (w (/ (- avail-width
1596 2 ; between board and grid
1601 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1602 `(display ,(make-string h 10))
1603 '(invisible :nogrid)))
1608 (cond (imagesp (+ (* 0.5 wmul)
1614 (gspc . ,(when imagesp
1618 ;; DWR: image width alone => OBOE!
1620 ;; NB: ‘(* wmul cw)’ is the same
1621 ;; as ‘(car (image-size ... t))’.
1622 (let ((cw (frame-char-width)))
1623 (/ (+ 1.0 (* wmul cw))
1626 (lpad . ,(let ((d `(display (space :align-to ,w))))
1627 ;; We distinguish between these cases to
1628 ;; workaround a display bug whereby the
1629 ;; `before-string' is omitted entirely (not
1630 ;; rendered) when interacting w/ the text
1631 ;; mode last-move left-paren for moves in
1635 ,(apply 'propertize " " d))
1638 (space :align-to ,(1- avail-width))))))
1639 (setplist (gnugo-f (car pair)) (cdr pair)))))
1641 (let ((cur (gnugo-get :mode-line)))
1642 (unless (equal cur gnugo-mode-line)
1643 (setq cur gnugo-mode-line)
1644 (gnugo-put :mode-line cur)
1645 (gnugo-put :mode-line-form
1646 (cond ((stringp cur)
1647 (setq cur (copy-sequence cur))
1649 (while (setq cut (string-match "~[bwpmtu]" cur))
1651 (setq c (aref cur (incf cut)))
1654 `(,(intern (format "squig-%c" c))
1656 (?b '(or (gnugo-get :black-captures) 0))
1657 (?w '(or (gnugo-get :white-captures) 0))
1658 (?p '(gnugo-current-player))
1659 (?t '(let ((ws (gnugo-get :waiting-start)))
1661 (cadr (time-since ws))
1663 (?u '(or (gnugo-get :last-waiting) "-"))
1664 (?m '(let ((tree (gnugo-get :sgf-gametree))
1665 (monkey (gnugo-get :monkey)))
1666 (gethash (car (aref monkey 0))
1667 (gnugo--tree-mnum tree)
1668 ;; should be unnecessary
1671 `(let ,(delete-dups (copy-sequence acc))
1672 (format ,cur ,@(reverse (mapcar 'car acc))))))
1674 (let ((form (gnugo-get :mode-line-form)))
1675 (setq mode-line-process
1677 ;; this dynamicism is nice but excessive in its wantonness
1678 ;;- `(" [" (:eval ,form) "]")
1679 ;; this dynamicism is ok because the user triggers it
1680 (format " [%s]" (eval form)))))
1681 (force-mode-line-update))
1683 (when (setq last (gnugo-get :last-user-bpos))
1684 (gnugo-goto-pos last))))
1686 (defun gnugo--turn-the-wheel (&optional now)
1687 (unless (gnugo-get :waiting)
1688 (let ((color (gnugo-current-player))
1689 (wheel (gnugo-get :wheel)))
1691 (when (and (not (gnugo-get :game-over))
1692 (member color (cdr wheel)))
1696 2) ;;; sec (frettoloso? dubioso!)
1698 (lambda (buf color wheel)
1700 (with-current-buffer buf
1701 (gnugo-get-move color)))
1705 (defun gnugo--finish-move (&optional now)
1706 (let ((buf (current-buffer)))
1707 (run-hooks 'gnugo-post-move-hook)
1710 (gnugo--turn-the-wheel now))
1712 ;;;---------------------------------------------------------------------------
1713 ;;; Game play actions
1715 (defun gnugo--rename-buffer-portion (&optional back)
1716 (let ((old "to play")
1717 (new "waiting for suggestion"))
1720 (let ((name (buffer-name)))
1721 (when (string-match old name)
1722 (rename-buffer (replace-match new t t name))))))
1724 (defun gnugo--display-suggestion (color suggestion)
1725 (message "%sSuggestion for %s: %s"
1726 (gnugo-get :diamond)
1729 (defun gnugo-get-move-insertion-filter (proc string)
1730 (with-current-buffer (process-buffer proc)
1731 (let* ((so-far (gnugo-get :get-move-string))
1732 (full (gnugo-put :get-move-string (concat so-far string))))
1733 (when (string-match "^= \\(.+\\)\n\n" full)
1734 (setq full (match-string 1 full)) ; POS or "PASS"
1735 (destructuring-bind (color . suggestion)
1736 (gnugo-get :waiting)
1737 (gnugo--forget :get-move-string
1741 (gnugo--rename-buffer-portion t)
1742 (unless (or (gnugo--passp full)
1743 (eq 'nowarp suggestion))
1744 (gnugo-goto-pos full))
1745 (gnugo--display-suggestion color full))
1746 (gnugo-push-move color full)
1747 (gnugo--finish-move)))))))
1749 (defun gnugo-get-move (color &optional suggestion)
1750 (gnugo-put :waiting (cons color suggestion))
1751 (gnugo--begin-exchange
1752 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1753 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1754 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1755 (concat "reg_genmove " color))
1756 (accept-process-output))
1758 (defun gnugo-cleanup ()
1759 (when (gnugo-board-buffer-p)
1760 (unless (zerop (buffer-size))
1761 (message "Thank you for playing GNU Go."))
1762 (setq gnugo-state nil)))
1764 (defun gnugo-position ()
1765 (or (get-text-property (point) 'gnugo-position)
1766 (user-error "Not a proper position point")))
1768 (defun gnugo-request-suggestion (&optional nowarp)
1769 "Request a move suggestion from GNU Go.
1770 After some time (during which you can do other stuff),
1771 Emacs displays the suggestion in the echo area and warps the
1772 cursor to the suggested position. Prefix arg inhibits warp."
1775 (gnugo--rename-buffer-portion)
1776 (gnugo-get-move (gnugo-current-player)
1781 (defun gnugo--karma (color) ; => BOOL
1782 (when (member color (cdr (gnugo-get :wheel)))
1785 (defsubst gnugo--:karma (role)
1786 (gnugo--karma (gnugo-get role)))
1788 (defun gnugo--assist-state (&optional gate)
1789 (let ((bool (gnugo--:karma :user-color)))
1791 (user-error "Sorry, Assist mode enabled")
1794 (defun gnugo--user-play (pos-or-pass)
1796 ;; The "user" in this func's name used to signify both
1797 ;; who does the action and for whom the action is done.
1798 ;; Now, it signifies only the former.
1799 (let ((color (gnugo-current-player)))
1800 ;; Don't get confused by mixed signals.
1801 (when (gnugo--karma color)
1802 (if (equal color (gnugo-get :one-shot))
1803 (gnugo--forget :one-shot)
1804 (user-error "Sorry, you cannot play for %s at this time"
1806 (gnugo-push-move color pos-or-pass))
1807 (gnugo--finish-move t))
1809 (defun gnugo-move ()
1810 "Make a move on the GNUGO Board buffer.
1811 The position is computed from current point.
1812 Signal error if done out-of-turn or if game-over.
1813 To start a game try M-x gnugo."
1815 (gnugo--user-play (gnugo-position)))
1817 (defun gnugo-mouse-move (e)
1818 "Do `gnugo-move' at mouse location."
1821 (when (memq (following-char) '(?. ?+))
1824 (defun gnugo-pass ()
1825 "Make a pass on the GNUGO Board buffer.
1826 Signal error if done out-of-turn or if game-over.
1827 To start a game try M-x gnugo."
1829 (gnugo--user-play "PASS"))
1831 (defun gnugo-mouse-pass (e)
1832 "Do `gnugo-pass' at mouse location."
1837 (defun gnugo-resign ()
1840 (if (not (y-or-n-p "Resign? "))
1841 (message "(not resigning)")
1842 (gnugo-push-move t "resign")
1845 (defun gnugo-animate-group (w/d)
1846 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1848 (let* ((pos (gnugo-position))
1849 (orig-b-m-p (buffer-modified-p))
1851 (unless (memq (following-char) '(?X ?O))
1852 (user-error "No stone at %s" pos))
1853 (setq blurb (message "Computing %s stones ..." w/d)
1854 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1855 (message "%s %s in group." blurb (length stones))
1856 (setplist (gnugo-f 'anim) nil)
1857 (let* ((spec (if (gnugo-get :display-using-images)
1858 (loop with yin = (get-text-property (point) 'gnugo-yin)
1859 with yang = (gnugo-yang (following-char))
1860 with up = (get (gnugo-yy yin yang t) 'display)
1861 with dn = (get (gnugo-yy yin yang) 'display)
1862 for n below (length gnugo-animation-string)
1863 collect (if (zerop (logand 1 n))
1865 (split-string gnugo-animation-string "" t)))
1867 (ovs (save-excursion
1868 (mapcar (lambda (pos)
1869 (gnugo-goto-pos pos)
1871 (ov (make-overlay p (1+ p))))
1872 (overlay-put ov 'category (gnugo-f 'anim))
1873 (overlay-put ov 'priority most-positive-fixnum)
1876 (setplist (gnugo-f 'anim) (cons 'display cell))
1877 (while (and (cdr spec) ; let last linger lest levity lost
1878 (sit-for 0.08675309)) ; jenny jenny i got your number...
1879 (setcar cell (setq spec (cdr spec)))
1880 ;; Force redisplay of overlays.
1881 (set-buffer-modified-p orig-b-m-p))
1883 (mapc 'delete-overlay ovs)
1886 (defun gnugo-display-group-data (command buffer-name)
1888 (message "Computing %s ..." command)
1889 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1890 (switch-to-buffer buffer-name)
1893 (message "Computing %s ... done." command))
1895 (defun gnugo-worm-stones ()
1896 "In the GNUGO Board buffer, animate \"worm\" at current position.
1897 Signal error if done out-of-turn or if game-over.
1898 See variable `gnugo-animation-string' for customization."
1900 (gnugo-animate-group 'worm))
1902 (defun gnugo-worm-data ()
1903 "Display in another buffer data from \"worm\" at current position.
1904 Signal error if done out-of-turn or if game-over."
1906 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1908 (defun gnugo-dragon-stones ()
1909 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1910 Signal error if done out-of-turn or if game-over.
1911 See variable `gnugo-animation-string' for customization."
1913 (gnugo-animate-group 'dragon))
1915 (defun gnugo-dragon-data ()
1916 "Display in another buffer data from \"dragon\" at current position.
1917 Signal error if done out-of-turn or if game-over."
1919 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1921 (defun gnugo-estimate-score ()
1922 "Display estimated score of a game of GNU Go.
1923 Output includes number of stones on the board and number of stones
1924 captured by each player, and the estimate of who has the advantage (and
1925 by how many stones)."
1927 (message "Est.score ...")
1928 (let ((black (gnugo--count-query "list_stones black"))
1929 (white (gnugo--count-query "list_stones white"))
1930 (black-captures (gnugo-query "captures black"))
1931 (white-captures (gnugo-query "captures white"))
1932 (est (gnugo-query "estimate_score")))
1933 ;; might as well update this
1934 (gnugo-put :black-captures black-captures)
1935 (gnugo-put :white-captures white-captures)
1936 (message "Est.score ... B %s %s | W %s %s | %s"
1937 black black-captures white white-captures est)))
1939 (defun gnugo--ok-file (filename)
1940 (setq default-directory
1941 (file-name-directory
1942 (expand-file-name filename)))
1943 (set-buffer-modified-p nil))
1945 (defun gnugo-write-sgf-file (filename)
1946 "Save the game history to FILENAME (even if unfinished).
1947 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1948 (interactive "FWrite game as SGF file: ")
1949 (when (and (file-exists-p filename)
1950 (not (y-or-n-p "File exists. Continue? ")))
1951 (user-error "Not writing %s" filename))
1952 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1953 (gnugo--ok-file filename))
1955 (defun gnugo--dance-dance (karma)
1956 (destructuring-bind (dance btw)
1957 (aref [(moshpit " Zombie")
1959 (reverse " Zombie Assist") ; "Assist Zombie"? no thanks! :-D
1960 (stilted " Assist")]
1963 (if (member (gnugo-get prop)
1967 (+ (try 2 :user-color)
1968 (try 1 :gnugo-color))))
1969 (gnugo-put :dance dance) ; pure cruft (for now)
1970 (setq gnugo-btw btw)))
1972 (defun gnugo--who-is-who (wait play samep)
1974 (let ((wheel (gnugo-get :wheel)))
1977 (setcdr wheel (mapcar 'gnugo-other
1979 (message "GNU Go %splays as %s, you as %s (%s)"
1980 (if samep "" "now ")
1983 "NOTE: this is a switch!")))
1985 (defsubst gnugo--nodep (x)
1986 (keywordp (caar x)))
1988 (defun gnugo--SZ! (size)
1989 (gnugo-put :SZ size)
1990 (gnugo-put :center-position
1991 (funcall (gnugo--as-pos-func)
1992 (let ((c (+ -1 ?a (truncate (1+ size) 2))))
1995 (defun gnugo--plant-and-climb (collection &optional sel)
1996 (gnugo-put :sgf-collection collection)
1997 (let ((tree (nth (or sel 0) collection)))
1998 (gnugo-put :sgf-gametree tree)
1999 (gnugo-put :monkey (vector
2001 (aref (gnugo--tree-ends tree) 0)
2006 (defun gnugo-read-sgf-file (filename)
2007 "Load the first game tree from FILENAME, a file in SGF format."
2008 (interactive "fSGF file to load: ")
2009 (when (file-directory-p filename)
2010 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
2011 (let (play wait samep coll tree game-over)
2012 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
2013 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
2014 (setq play (gnugo--q/ue "loadsgf %s" (expand-file-name filename))
2015 wait (gnugo-other play)
2016 samep (string= (gnugo-get :user-color) play))
2017 (gnugo-put :last-mover wait)
2019 (gnugo-put :gnugo-color wait)
2020 (gnugo-put :user-color play))
2021 (setq coll (gnugo/sgf-create filename)
2022 tree (gnugo--plant-and-climb
2023 coll (let ((n (length coll)))
2027 ;; (let* ((q (format "Which game? (1-%d)" n))
2028 ;; (choice (1- (read-number q 1))))
2029 ;; (if (and (< -1 choice) (< choice n))
2031 ;; (message "(Selecting the first game)")
2033 ;; but this is what we use (for now) to accomodate
2034 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
2036 (message "(Selecting the first game)"))
2038 ;; This is deliberately undocumented for now.
2039 (gnugo--SZ! (gnugo--root-prop :SZ tree))
2040 (when (setq game-over (or (gnugo--root-prop :RE tree)
2041 (when (equal '("PASS" "PASS")
2042 (gnugo-move-history 'two))
2044 (gnugo-close-game nil game-over))
2045 (gnugo-put :last-user-bpos
2046 (gnugo-move-history 'bpos (gnugo-get :user-color)))
2048 (gnugo--ok-file filename)
2049 (gnugo--who-is-who wait play samep)))
2051 (defun gnugo--mem-with-played-stone (pos &optional noerror)
2052 (let ((color (case (following-char)
2057 (user-error "No stone at %s" pos))
2058 (loop with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
2059 for mem on (aref (gnugo-get :monkey) 0)
2060 when (equal fruit (caar mem))
2062 finally return nil))))
2064 (defun gnugo--climb-towards-root (spec &optional reaction keep)
2066 (gnugo--assist-state t)
2067 (let* ((user-color (gnugo-get :user-color))
2068 (monkey (gnugo-get :monkey))
2069 (tree (gnugo-get :sgf-gametree))
2070 (ends (gnugo--tree-ends tree))
2071 (remorseful (not (gnugo--no-regrets monkey ends)))
2072 (stop (if (numberp spec)
2073 (nthcdr (if (zerop spec)
2074 (if (string= (gnugo-get :last-mover)
2080 (cdr (gnugo--mem-with-played-stone
2083 (gnugo-position)))))))
2084 (when (gnugo-get :game-over)
2085 (gnugo--unclose-game))
2086 (while (and (not (eq stop (aref monkey 0)))
2087 (gnugo--no-worries (gnugo--q "undo")))
2088 (pop (aref monkey 0))
2089 (gnugo-put :last-mover (gnugo-current-player))
2090 (gnugo-merge-showboard-results) ; all
2091 (gnugo-refresh) ; this
2092 (redisplay)) ; eye candy
2093 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
2094 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
2095 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
2097 (gnugo-get :center-position)))
2099 (unless (or keep remorseful)
2100 (aset ends (aref monkey 1) (aref monkey 0)))
2102 (let ((g (gnugo-get :gnugo-color)))
2103 (cl-flet ((turn () (gnugo--turn-the-wheel t)))
2104 (case (or reaction gnugo-undo-reaction)
2106 (play! (let ((wheel (gnugo-get :wheel)))
2107 (letf (((cdr wheel) (cons g (cdr wheel))))
2109 (zombie (gnugo-zombie-mode 1))
2110 (t (gnugo-put :one-shot g)))))))))
2112 (defun gnugo-undo-one-move (&optional me-next)
2113 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
2114 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
2115 Prefix arg ME-NEXT means to arrange for you to play
2116 the color of the next move (and GNU Go the opposite).
2117 This is useful after loading an SGF file whose last
2118 move was done by the color you prefer to play:
2119 \\[gnugo-read-sgf-file] FILENAME RET
2120 C-u \\[gnugo-undo-one-move]
2122 See also `gnugo-undo-two-moves'."
2126 (let* ((play (gnugo-get :last-mover))
2127 (wait (gnugo-other play))
2128 (samep (string= play (gnugo-get :user-color))))
2129 (gnugo-put :user-color play)
2130 (gnugo-put :gnugo-color wait)
2131 (gnugo--who-is-who wait play samep)))
2132 (gnugo--climb-towards-root 1 (case gnugo-undo-reaction
2133 (zombie gnugo-undo-reaction)
2136 (defun gnugo-undo-two-moves ()
2137 "Undo a pair of moves (GNU Go's and yours).
2138 However, if you are the last mover, undo only one move.
2139 Regardless, after undoing, it is your turn to play again."
2141 (gnugo--climb-towards-root 0))
2143 (defun gnugo-oops (&optional position)
2144 "Like `gnugo-undo-two-moves', but keep the undone moves.
2145 The kept moves become a sub-gametree (variation) when play resumes.
2146 Prefix arg means, instead, undo repeatedly up to and including
2147 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
2149 (gnugo--climb-towards-root (unless position
2153 (defun gnugo-okay (&optional full)
2154 "Redo a pair of undone moves.
2155 Prefix arg means to redo all the undone moves."
2158 (let* ((tree (gnugo-get :sgf-gametree))
2159 (ends (gnugo--tree-ends tree))
2160 (monkey (gnugo-get :monkey)))
2161 (if (gnugo--no-regrets monkey ends)
2162 (message "Oop ack!")
2163 (let* ((as-pos (gnugo--as-pos-func))
2164 (mnum (gnugo--tree-mnum tree))
2165 (mem (aref monkey 0))
2166 (bidx (aref monkey 1))
2167 (end (aref ends bidx))
2168 (ucolor (gnugo-get :user-color))
2169 (uprop (gnugo--prop<-color ucolor)))
2170 (cl-flet ((mvno (node) (gethash node mnum)))
2174 (+ 2 (mvno (car mem))))
2175 with (node move todo)
2179 move (gnugo--move-prop node))
2180 (when (and move (>= ok (mvno node)))
2181 (let ((userp (eq uprop (car move))))
2183 (funcall as-pos (cdr move)))
2185 until (eq mem (cdr ls))
2188 for (userp pos) in todo
2190 (gnugo-push-move userp pos)
2194 (defun gnugo-display-final-score (&optional comment)
2195 "Display final score and other info in another buffer (when game over).
2196 If the game is still ongoing, Emacs asks if you wish to stop play (by
2197 making sure two \"pass\" moves are played consecutively, if necessary).
2198 Also, add the `:RE' SGF property to the root node of the game tree.
2199 Prefix arg COMMENT means to also attach the text (slightly compacted)
2200 to the last move, as a comment."
2202 (let ((game-over (gnugo-get :game-over)))
2203 (unless (or game-over
2204 (and (not (gnugo-get :waiting))
2205 (y-or-n-p "Game still in play. Stop play now? ")))
2206 (user-error "Sorry, game still in play"))
2210 (message "Playing PASS for %s ..."
2211 (gnugo-get (if userp :user-color :gnugo-color)))
2213 (gnugo-push-move userp "PASS")))
2218 (let ((b= " Black = ")
2220 (res (when (gnugo--resignp (gnugo-move-history 'car))
2221 (gnugo-get :last-mover)))
2225 (format "%s wins.\n"
2226 (substring (if (= ?b (aref res 0)) w= b=)
2228 "The game is over.\n"
2229 (format "Resignation by %s.\n" res))
2230 result (concat (upcase (substring (gnugo-other res) 0 1))
2232 (message "Computing final score ...")
2233 (let* ((g-over (gnugo-get :game-over))
2234 (live (cdr (assq 'live g-over)))
2235 (dead (cdr (assq 'dead g-over)))
2236 (seed (gnugo-get :scoring-seed))
2237 (terr-q (format "final_status_list %%s_territory %d" seed))
2240 (b-terr (gnugo--count-query terr-q "black"))
2241 (w-terr (gnugo--count-query terr-q "white"))
2242 (b-capt (string-to-number (gnugo-get :black-captures)))
2243 (w-capt (string-to-number (gnugo-get :white-captures)))
2244 (komi (gnugo--root-prop :KM)))
2245 (setq blurb (list "The game is over. Final score:\n")
2246 result (gnugo-query "final_score %d" seed))
2247 (cond ((string= "Chinese" (gnugo--root-prop :RU))
2248 (dolist (group live)
2249 (incf (if (gnugo--blackp (caar group))
2252 (length (cdr group))))
2253 (dolist (group dead)
2254 (incf (if (gnugo--blackp (caar group))
2257 (length (cdr group))))
2258 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
2259 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
2260 w-terr terr komi 'komi (+ w-terr komi))
2263 (dolist (group dead)
2264 (incf (if (gnugo--blackp (caar group))
2267 (* 2 (length (cdr group)))))
2268 (push (format "%s%d %s + %s %s = %3.1f\n" b=
2273 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
2277 (+ w-terr w-capt komi))
2279 (push (if (string= "0" result)
2280 "The game is a draw.\n"
2281 (format "%s wins by %s.\n"
2282 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
2283 (substring result 2)))
2285 (message "Computing final score ... done")))
2287 (let ((beg (gnugo-get :game-start-time))
2288 (end (gnugo-get :game-end-time)))
2292 ((yep (pretty moment)
2293 (push (format-time-string
2294 (concat pretty ": %Y-%m-%d %H:%M:%S %z\n")
2297 (yep "Game start" beg)
2299 (setq blurb (apply 'concat (nreverse blurb)))
2300 (gnugo--set-root-prop :RE result)
2302 (let ((node (car (aref (gnugo-get :monkey) 0))))
2304 (delq (assq :C node) node)
2306 (with-temp-buffer ; lame
2308 (when (search-backward "\n\nGame start:" nil t)
2309 (delete-region (point) (point-max)))
2310 (cl-flet ((rep (old new)
2311 (goto-char (point-min))
2312 (while (search-forward old nil t)
2313 (replace-match new))))
2314 (rep "The game is over. " "")
2315 (rep "territory" "T")
2316 (rep "captures" "C")
2319 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
2323 (defun gnugo-quit ()
2324 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
2325 If the game is not over, ask for confirmation first."
2327 (if (or (gnugo-get :game-over)
2328 (y-or-n-p "Quit? "))
2330 (message "(not quitting)")))
2332 (defun gnugo-leave-me-alone ()
2333 "Kill the current buffer unconditionally."
2337 (defun gnugo-fancy-undo (count)
2338 "Rewind the game tree in various ways.
2339 Prefix arg COUNT means to undo that many moves.
2340 Otherwise, undo repeatedly up to and including the move
2341 which placed the stone at point."
2343 (gnugo--climb-towards-root
2348 (define-minor-mode gnugo-image-display-mode
2349 "If enabled, display the board using images.
2350 See function `display-images-p' and variable `gnugo-xpms'."
2352 ((gnugo-get :display-using-images)
2355 (unless (eq bool (gnugo-get :display-using-images))
2356 (gnugo-toggle-image-display)
2357 (save-excursion (gnugo-refresh))))))
2359 (defsubst gnugo--node-with-played-stone (pos &optional noerror)
2360 (car (gnugo--mem-with-played-stone pos noerror)))
2362 (defun gnugo-describe-position ()
2363 "Display the board position under cursor in the echo area.
2364 If there a stone at that position, also display its move number."
2366 (let* ((pos (gnugo-position)) ; do first (can throw)
2367 (node (gnugo--node-with-played-stone pos t)))
2371 (let* ((tree (gnugo-get :sgf-gametree))
2372 (mnum (gnugo--tree-mnum tree))
2373 (move-num (gethash node mnum)))
2374 (format " (move %d)" move-num)))
2377 (defun gnugo-switch-to-another ()
2378 "Switch to another GNU Go game buffer (if any)."
2380 (loop for buf in (cdr (buffer-list))
2381 if (gnugo-board-buffer-p buf)
2384 (switch-to-buffer buf))
2385 finally do (message "(only one)")))
2387 (defun gnugo-comment (node comment)
2388 "Add to NODE a COMMENT (string) property.
2389 Called interactively, NODE is the one corresponding to the
2390 stone at point, and any previous comment is inserted as the
2391 initial-input (see `read-string').
2393 If COMMENT is nil or the empty string, remove the property entirely."
2395 (let* ((pos (gnugo-position))
2396 (node (gnugo--node-with-played-stone pos)))
2398 (read-string (format "Comment for %s: "
2399 (gnugo-describe-position))
2400 (cdr (assq :C node))))))
2401 (setq node (delq (assq :C node) node))
2402 (unless (zerop (length comment))
2403 (gnugo--decorate node :C comment)))
2405 (defun gnugo--struggle (prop updn)
2406 (unless (eq updn (gnugo--:karma prop)) ; drudgery avoidance
2407 (let ((color (gnugo-get prop)))
2412 (let ((waiting (gnugo-get :waiting)))
2413 (when (and waiting (string= color (car waiting)))
2414 (gnugo--rename-buffer-portion)
2416 ;; heuristic: Warp only if it appears
2417 ;; that the user is "following along".
2419 (string= (gnugo-position)
2420 (gnugo-move-history 'bpos color)))
2422 (gnugo--display-suggestion color "forthcoming")
2424 (let* ((wheel (gnugo-get :wheel))
2426 (karma (cdr wheel)))
2427 (when (timerp timer)
2428 (cancel-timer timer))
2430 (setcdr wheel (setq karma
2431 ;; walk to the west, fly to the east,
2432 ;; talk and then rest, cry and then feast.
2433 ;; 99 beers down thirsty throats sloshed?
2434 ;; 500 years under pink mountains squashed?
2435 ;; balk with the best, child now re-creased!
2438 (delete color karma))))
2439 (gnugo--dance-dance karma))
2440 (gnugo--turn-the-wheel t))))
2442 (define-minor-mode gnugo-assist-mode
2443 "If enabled (\"Assist\" in mode line), GNU Go plays for you.
2444 When disabling, if GNU Go has already started thinking of
2445 a move to play for you, the thinking is not cancelled but instead
2446 transformed into a move suggestion (see `gnugo-request-suggestion')."
2448 ((gnugo--assist-state)
2451 (gnugo--struggle :user-color bool))))
2453 (define-minor-mode gnugo-zombie-mode
2454 "If enabled (\"Zombie\" in mode line), GNU Go lets you play for it.
2455 When disabling, if GNU Go has already started thinking of
2456 a move to play, the thinking is not cancelled but instead
2457 transformed into a move suggestion (see `gnugo-request-suggestion')."
2459 ((not (gnugo--:karma :gnugo-color))
2462 (gnugo--struggle :gnugo-color (not bool)))))
2464 ;;;---------------------------------------------------------------------------
2465 ;;; Command properties and gnugo-command
2467 ;; GTP commands entered by the user are never issued directly to GNU Go;
2468 ;; instead, their behavior and output are controlled by the property
2469 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2470 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2472 ;; :full -- completely interpret the command string; the value is a
2473 ;; func that takes the list of words derived from splitting the
2474 ;; command string (minus the command) and handles everything.
2476 ;; :output -- either a keyword specifying the preferred output method:
2477 ;; :message -- show output in minibuffer
2478 ;; :discard -- sometimes you just don't care;
2479 ;; or a function that takes one arg, the output string, and
2480 ;; handles it completely. default is to switch to buffer
2481 ;; "*gnugo command output*" if the output has a newline,
2482 ;; otherwise use `message'.
2484 ;; :post-thunk -- run after output processing (at the very end).
2486 (defun gnugo-command (command)
2487 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2488 Output and Emacs behavior depend on which command is given (some
2489 commands are handled completely by Emacs w/o using the subprocess;
2490 some commands have their output displayed in specially prepared
2491 buffers or in the echo area; some commands are instrumented to do
2492 gnugo.el-specific housekeeping).
2494 For example, for the command \"help\", Emacs visits the
2495 GTP command reference info page.
2497 NOTE: At this time, GTP command handling specification is still
2498 incomplete. Thus, some commands WILL confuse gnugo.el."
2499 (interactive "sCommand: ")
2500 (if (string= "" command)
2501 (message "(no command given)")
2502 (let* ((split (split-string command))
2503 (cmd (intern (car split)))
2504 (spec (get cmd :gnugo-gtp-command-spec))
2505 (full (plist-get spec :full)))
2507 (funcall full (cdr split))
2508 (message "Doing %s ..." command)
2509 (let* ((ans (gnugo--q command))
2510 (where (plist-get spec :output)))
2511 (if (string-match "unknown.command" ans)
2513 (cond ((functionp where) (funcall where ans))
2514 ((eq :discard where) (message ""))
2515 ((or (eq :message where)
2516 (not (string-match "\n" ans)))
2518 (t (switch-to-buffer "*gnugo command output*")
2521 (message "Doing %s ... done." command)))
2522 (let ((thunk (plist-get spec :post-thunk)))
2523 (when thunk (funcall thunk)))))))))
2525 ;;;---------------------------------------------------------------------------
2526 ;;; Major mode for interacting with a GNUGO subprocess
2528 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2529 "Major mode for playing GNU Go.
2530 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2531 In this mode, keys do not self insert.
2533 \\{gnugo-board-mode-map}"
2534 (buffer-disable-undo) ; todo: undo undo undoing
2535 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2537 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2538 (set (make-local-variable 'gnugo-state)
2539 (gnugo--mkht :size (1- 42)))
2540 (set (make-local-variable 'gnugo-btw) nil)
2541 (add-to-list 'minor-mode-alist '(gnugo-btw gnugo-btw))
2542 (gnugo-put :highlight-last-move-spec
2543 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2544 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2545 (let ((ov (make-overlay 1 1)))
2546 (overlay-put ov 'display ")")
2548 (gnugo-put :mul '(1 . 1))
2549 (gnugo-put :obarray (make-vector 31 nil))
2550 (add-to-invisibility-spec :nogrid))
2552 ;;;---------------------------------------------------------------------------
2556 (defun gnugo (&optional new-game)
2557 "Run gnugo in a buffer, or resume a game in progress.
2558 If there is already a game in progress you may resume it instead
2559 of starting a new one. Prefix arg means skip the game-in-progress
2560 check and start a new game straight away.
2562 Before starting, Emacs queries you for additional command-line
2563 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2565 Note that specifying \"--infile FILENAME\" (or, \"-l FILENAME\")
2566 silently clobbers certain other options, such as \"--color\".
2567 For details, see info node `(gnugo) Invoking GNU Go'.
2569 \\<gnugo-board-mode-map>
2570 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2571 See `gnugo-board-mode' for a full list of commands."
2573 (let* ((all (let (acc)
2574 (dolist (buf (buffer-list))
2575 (when (gnugo-board-buffer-p buf)
2576 (push (cons (buffer-name buf) buf) acc)))
2579 (if (and (not new-game)
2581 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2582 (if (= 1 n) "" "s"))))
2587 (let ((sel (completing-read "Which one? " all nil t)))
2588 (if (string= "" sel)
2590 (assoc sel all))))))
2592 (unless (executable-find gnugo-program)
2593 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2594 ;; set up a new board
2595 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2597 (let* ((filename nil)
2598 (user-color "black")
2600 with ls = (split-string
2601 ;; todo: grok ‘gnugo --help’; completion
2604 (car gnugo-option-history)
2605 'gnugo-option-history))
2608 (let ((arg (pop ls)))
2612 (warn "%s %s ignored" opt fn)
2613 (setq filename fn))))
2615 ((string= "--color" arg)
2618 ;; Unfortunately, GTP does not provide
2619 ;; a way to query the user color, so
2620 ;; we must resort to this weirdness.
2624 ((string= "--infile" arg)
2625 (ex "--infile" (pop ls)))
2626 ((string-match "^-l" arg)
2627 (ex "-l" (if (< 2 (length arg))
2630 (t (push arg ok)))))
2631 finally return (nreverse ok)))
2632 (proc (apply 'start-process "gnugo"
2635 "--mode" "gtp" "--quiet"
2637 root board-size handicap komi)
2638 (gnugo-put :user-color user-color)
2639 (gnugo-put :proc proc)
2640 (set-process-sentinel proc 'gnugo-sentinel)
2641 ;; Emacs is too protective sometimes, blech.
2642 (set-process-query-on-exit-flag proc nil)
2643 (gnugo-put :diamond (substring (process-name proc) 5))
2644 (gnugo-put :gnugo-color (gnugo-other user-color))
2646 (gnugo-read-sgf-file (expand-file-name filename))
2648 ((r! (&rest plist) (apply 'gnugo--decorate root plist)))
2650 (setq root (gnugo--root-node
2651 (gnugo--plant-and-climb
2652 (gnugo/sgf-create "(;FF[4]GM[1])" t)))
2653 komi (gnugo--nquery "get_komi")
2654 handicap (gnugo--nquery "get_handicap")
2655 board-size (gnugo--nquery "query_boardsize")))
2656 ;; Work around a GNU Go 3.8 (and possibly earlier/later)
2657 ;; bug whereby GTP command ‘get_handicap’ fails to return
2658 ;; the N set by ‘--handicap N’ on the command line.
2659 (let ((actually (member "--handicap" args)))
2660 ;; Checking ‘(zerop handicap)’ first is not strictly
2661 ;; necessary; it represents a hope that some day GNU Go
2662 ;; will DTRT (or provide rationale for this weird behavior)
2663 ;; and become worthy of our trust.
2664 (when (and (zerop handicap) actually)
2665 (setq handicap (string-to-number (cadr actually)))))
2667 :DT (format-time-string "%Y-%m-%d")
2668 :RU (if (member "--chinese-rules" args)
2671 :AP (cons "gnugo.el" gnugo-version)
2673 (let ((ub (gnugo--blackp user-color)))
2674 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2675 (if ub :PB :PW) (user-full-name)))
2676 (unless (zerop handicap)
2678 :AB (mapcar (gnugo--as-cc-func)
2679 (gnugo-lsquery "fixed_handicap %d"
2681 (gnugo-put :waiting-start (current-time))
2683 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2684 (gnugo-get :center-position)))
2686 (gnugo-put :game-start-time (current-time))
2687 (let ((g (gnugo-get :gnugo-color))
2688 (n (or (gnugo--root-prop :HA) 0))
2689 (u (gnugo-get :user-color)))
2690 (unless (gnugo-get :last-mover)
2691 (gnugo-put :last-mover
2692 (if (or (and (gnugo--blackp u) (< 1 n))
2693 (and (gnugo--blackp g) (< n 2)))
2696 (let ((karma (list g)))
2697 (gnugo-put :wheel (cons nil karma))
2698 (gnugo--dance-dance karma))
2699 (run-hooks 'gnugo-start-game-hook)
2700 (gnugo--turn-the-wheel)))))
2702 ;;;---------------------------------------------------------------------------
2703 ;;; Load-time actions
2705 (unless gnugo-frolic-mode-map
2706 (setq gnugo-frolic-mode-map (make-sparse-keymap))
2707 (suppress-keymap gnugo-frolic-mode-map)
2708 (mapc (lambda (pair)
2709 (define-key gnugo-frolic-mode-map (car pair) (cdr pair)))
2710 '(("q" . gnugo-frolic-quit)
2711 ("Q" . gnugo-frolic-quit)
2712 ("\C-q" . gnugo-frolic-quit)
2713 ("C" . gnugo-frolic-quit) ; like ‘View-kill-and-leave’
2714 ("\C-b" . gnugo-frolic-backward-branch)
2715 ("\C-f" . gnugo-frolic-forward-branch)
2716 ("\C-p" . gnugo-frolic-previous-move)
2717 ("\C-n" . gnugo-frolic-next-move)
2718 ("t" . gnugo-frolic-tip-move)
2719 ("j" . gnugo-frolic-exchange-left)
2720 ("J" . gnugo-frolic-rotate-left)
2721 ("k" . gnugo-frolic-exchange-right)
2722 ("K" . gnugo-frolic-rotate-right)
2723 ("\C-m" . gnugo-frolic-set-as-main-line)
2724 ("\C-\M-p" . gnugo-frolic-prune-branch)
2725 ("o" . gnugo-frolic-return-to-origin))))
2727 (unless gnugo-board-mode-map
2728 (setq gnugo-board-mode-map (make-sparse-keymap))
2729 (suppress-keymap gnugo-board-mode-map)
2730 (mapc (lambda (pair)
2731 (define-key gnugo-board-mode-map (car pair) (cdr pair)))
2732 '(("?" . describe-mode)
2733 ("S" . gnugo-request-suggestion)
2734 ("\C-m" . gnugo-move)
2737 ("R" . gnugo-resign)
2739 ("Q" . gnugo-leave-me-alone)
2740 ("U" . gnugo-fancy-undo)
2741 ("\M-u" . gnugo-undo-one-move)
2742 ("u" . gnugo-undo-two-moves)
2743 ("\C-?" . gnugo-undo-two-moves)
2746 ("\C-l" . gnugo-refresh)
2747 ("\M-_" . gnugo-boss-is-near)
2748 ("_" . gnugo-boss-is-near)
2749 ("h" . gnugo-move-history)
2750 ("L" . gnugo-frolic-in-the-leaves)
2751 ("\C-c\C-l" . gnugo-frolic-in-the-leaves)
2752 ("i" . gnugo-image-display-mode)
2753 ("w" . gnugo-worm-stones)
2754 ("W" . gnugo-worm-data)
2755 ("d" . gnugo-dragon-stones)
2756 ("D" . gnugo-dragon-data)
2757 ("g" . gnugo-grid-mode)
2758 ("!" . gnugo-estimate-score)
2759 (":" . gnugo-command)
2760 (";" . gnugo-command)
2761 ("=" . gnugo-describe-position)
2762 ("s" . gnugo-write-sgf-file)
2763 ("\C-x\C-s" . gnugo-write-sgf-file)
2764 ("\C-x\C-w" . gnugo-write-sgf-file)
2765 ("l" . gnugo-read-sgf-file)
2766 ("F" . gnugo-display-final-score)
2767 ("A" . gnugo-switch-to-another)
2768 ("C" . gnugo-comment)
2769 ("\C-c\C-a" . gnugo-assist-mode)
2770 ("\C-c\C-z" . gnugo-zombie-mode)
2772 ([(down-mouse-1)] . gnugo-mouse-move)
2773 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
2774 ([(down-mouse-3)] . gnugo-mouse-pass)
2775 ;; delving into the curiosities
2776 ("\C-c\C-p" . gnugo-describe-internal-properties))))
2778 (unless (get 'help :gnugo-gtp-command-spec)
2780 ((sget (x) (get x :gnugo-gtp-command-spec))
2781 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2782 (plist-put (sget cmd) prop val)))
2783 (validpos (s &optional go)
2784 (let ((pos (upcase s)))
2785 (loop with size = (gnugo-get :SZ)
2786 for c across (funcall (gnugo--as-cc-func)
2788 do (let ((norm (- c ?a)))
2789 (unless (and (< -1 norm)
2791 (user-error "Invalid position: %s"
2794 (gnugo-goto-pos pos))
2796 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2799 (jam cmd (car ls) (cadr ls))
2800 (setq ls (cddr ls)))))))
2801 (cl-macrolet ((deffull (who &body body)
2802 (declare (indent 1))
2803 `(defgtp ',who :full (lambda (sel)
2807 (info "(gnugo)GTP command reference")
2808 (when sel (setq sel (intern (car sel))))
2809 (let (buffer-read-only pad cur spec output found)
2811 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2812 (goto-char (point-min))
2814 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2817 (setq pad (make-string (- (match-beginning 1)
2818 (match-beginning 0))
2822 (get (setq cur (intern (match-string 1)))
2823 :gnugo-gtp-command-spec))
2825 (note "handles this command completely"))
2826 (when (setq output (plist-get spec :output))
2827 (if (functionp output)
2828 (note "handles the output specially")
2830 (:discard (note "discards the output"))
2831 (:message (note "displays the output in the echo area")))))
2833 (setq found (make-marker))
2834 (set-marker found (match-beginning 0))))))
2835 (cond (found (goto-char found) (set-marker found nil))
2837 (t (message "(no such command: %s)" sel)))))
2839 (deffull final_score
2840 ;; Explicit ignorance avoids byte-compiler warning.
2842 (gnugo-display-final-score))
2848 :post-thunk (lambda ()
2849 (gnugo--unclose-game)
2850 (gnugo--forget :last-mover)
2852 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2856 (gnugo-read-sgf-file (car sel)))
2858 (deffull (undo gg-undo)
2859 (gnugo--climb-towards-root
2862 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2863 (t (validpos (car sel) t)))))))))
2868 ;;;---------------------------------------------------------------------------
2869 ;;; The remainder of this file defines a simplified SGF-handling library.
2870 ;;; When/if it should start to attain generality, it should be split off into
2871 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2872 ;;; "gnugo/" prefix.
2874 (defconst gnugo/sgf-*r4-properties*
2875 '((AB "Add Black" setup list stone)
2876 (AE "Add Empty" game list point)
2877 (AN "Annotation" game simpletext)
2878 (AP "Application" root (simpletext . simpletext))
2879 (AR "Arrow" - list (point . point))
2880 (AS "Who adds stones" - simpletext) ; (LOA)
2881 (AW "Add White" setup list stone)
2882 (B "Black" move move)
2883 (BL "Black time left" move real)
2884 (BM "Bad move" move double)
2885 (BR "Black rank" game simpletext)
2886 (BT "Black team" game simpletext)
2887 (C "Comment" - text)
2888 (CA "Charset" root simpletext)
2889 (CP "Copyright" game simpletext)
2890 (CR "Circle" - list point)
2891 (DD "Dim points" - elist point) ; (inherit)
2892 (DM "Even position" - double)
2893 (DO "Doubtful" move none)
2894 (DT "Date" game simpletext)
2895 (EV "Event" game simpletext)
2896 (FF "Fileformat" root [number (1 . 4)])
2897 (FG "Figure" - (or none (number . simpletext)))
2898 (GB "Good for Black" - double)
2899 (GC "Game comment" game text)
2900 (GM "Game" root [number (1 . 20)])
2901 (GN "Game name" game simpletext)
2902 (GW "Good for White" - double)
2903 (HA "Handicap" game number) ; (Go)
2904 (HO "Hotspot" - double)
2905 (IP "Initial pos." game simpletext) ; (LOA)
2906 (IT "Interesting" move none)
2907 (IY "Invert Y-axis" game simpletext) ; (LOA)
2908 (KM "Komi" game real) ; (Go)
2910 (LB "Label" - list (point . simpletext))
2911 (LN "Line" - list (point . point))
2912 (MA "Mark" - list point)
2913 (MN "set move number" move number)
2914 (N "Nodename" - simpletext)
2915 (OB "OtStones Black" move number)
2916 (ON "Opening" game text)
2917 (OT "Overtime" game simpletext)
2918 (OW "OtStones White" move number)
2919 (PB "Player Black" game simpletext)
2920 (PC "Place" game simpletext)
2921 (PL "Player to play" setup color)
2922 (PM "Print move mode" - number) ; (inherit)
2923 (PW "Player White" game simpletext)
2924 (RE "Result" game simpletext)
2925 (RO "Round" game simpletext)
2926 (RU "Rules" game simpletext)
2927 (SE "Markup" - point) ; (LOA)
2928 (SL "Selected" - list point)
2929 (SO "Source" game simpletext)
2930 (SQ "Square" - list point)
2931 (ST "Style" root [number (0 . 3)])
2932 (SU "Setup type" game simpletext) ; (LOA)
2933 (SZ "Size" root (or number (number . number)))
2934 (TB "Territory Black" - elist point) ; (Go)
2935 (TE "Tesuji" move double)
2936 (TM "Timelimit" game real)
2937 (TR "Triangle" - list point)
2938 (TW "Territory White" - elist point) ; (Go)
2939 (UC "Unclear pos" - double)
2940 (US "User" game simpletext)
2942 (VW "View" - elist point) ; (inherit)
2943 (W "White" move move)
2944 (WL "White time left" move real)
2945 (WR "White rank" game simpletext)
2946 (WT "White team" game simpletext)
2947 (LT "Lose on time" setup simpletext))
2948 ;; r4-specific notes
2949 ;; - changed: DT FG LB RE RU SZ
2950 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2951 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2953 (defun gnugo/sgf-create (file-or-data &optional data-p)
2954 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2955 FILE-OR-DATA is a file name or SGF[4] data.
2956 Optional arg DATA-P non-nil means FILE-OR-DATA is
2957 a string containing SGF[4] data.
2958 A collection is a list of gametrees, each a vector of four elements:
2960 ENDS -- a vector of node lists, with shared tails
2961 (last element of all the lists is the root node)
2963 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2964 have a move number of the previous \"move\" node (or zero)
2966 ROOT -- the root node"
2967 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2968 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2969 (put 'gnugo/sgf-*r4-properties* :keywords
2970 (mapcar (lambda (full)
2972 (intern (format ":%s" (car full)))))
2973 gnugo/sgf-*r4-properties*))))
2974 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2975 (put 'gnugo/sgf-*r4-properties* :specs
2976 (mapcar (lambda (full)
2977 (cons (car full) (cdddr full)))
2978 gnugo/sgf-*r4-properties*))))
2981 ((sw () (skip-chars-forward " \t\n"))
2982 (x (end preserve-whitespace)
2985 (:end (lambda (char) (= ?\] char)))
2986 (:mid (lambda (char) (= ?\: char)))
2987 (t (lambda (char) (or (= ?\: char)
2990 (while (not (funcall endp (setq c (following-char))))
2996 ((unless preserve-whitespace
2997 (looking-at "\\s-+"))
2998 (delete-region (point) (match-end 0))
3000 (t (forward-char 1))))
3001 (buffer-substring-no-properties beg (point))))
3002 (one (type end) (let ((s (progn
3004 (x end (eq 'text type)))))
3007 ;; blech, begone bu"tt"-ugly blatherings
3008 ;; (but bide brobdingnagian boards)...
3009 (if (and (string= "tt" s)
3014 ((simpletext color) s)
3015 ((number real double) (string-to-number s))
3018 (t (error "Unhandled type: %S" type)))))
3019 (val (spec) (cond ((symbolp spec)
3022 ;; todo: check range here.
3023 (one (aref spec 0) :end))
3024 ((eq 'or (car spec))
3025 (let ((v (one (cadr spec) t)))
3026 (if (= ?\] (following-char))
3029 ;; todo: this assumes `spec' has the form
3030 ;; (or foo (foo . bar))
3031 ;; i.e., foo is not rescanned. e.g., `SZ'.
3032 ;; probably this assumption is consistent
3033 ;; w/ the SGF authors' desire to make the
3034 ;; parsing easy, but you never know...
3035 (cons v (one (cdaddr spec) :end)))))
3036 (t (cons (one (car spec) :mid)
3037 (one (cdr spec) :end)))))
3038 (short (who) (when (eobp)
3039 (error "Unexpected EOF while reading %s" who)))
3040 (atvalp () (= ?\[ (following-char)))
3041 (PROP () (let (name spec ltype)
3042 (sw) (short 'property)
3043 (when (looking-at "[A-Z]")
3044 (setq name (read (current-buffer))
3045 spec (cdr (assq name specs)))
3048 (cdr (assq name keywords))
3049 (prog1 (if (= 1 (length spec))
3051 (unless (memq (setq ltype (car spec))
3053 (error "Bad spec: %S" spec))
3054 (if (and (eq 'elist ltype) (sw)
3057 (let ((type (cadr spec))
3059 (while (and (sw) (atvalp)
3060 (setq mo (val type)))
3065 (forward-char 1))))))
3066 (morep () (and (sw) (not (eobp))))
3067 (seek (c) (and (morep) (= c (following-char))))
3068 (seek-into (c) (when (seek c)
3071 (NODE () (when (seek-into ?\;)
3073 while (setq prop (PROP))
3075 (when (eq :SZ (car prop))
3076 (setq SZ (cdr prop)))
3085 (puthash node (+ (if (gnugo--move-prop node)
3088 (gethash prev mnum 0))
3093 (if (not (seek ?\())
3097 (loop while (seek ?\()
3098 append (TREE ls mnum)))
3102 (insert-file-contents file-or-data)
3103 (insert file-or-data)
3104 (goto-char (point-min)))
3106 collect (let* ((mnum (gnugo--mkht :weakness 'key))
3107 (ends (TREE nil mnum))
3108 (root (car (last (car ends)))))
3109 (vector (apply 'vector ends)
3113 (defun gnugo/sgf-write-file (collection filename)
3114 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
3115 (me (cons "gnugo.el" gnugo-version))
3116 (specs (mapcar (lambda (full)
3117 (cons (intern (format ":%s" (car full)))
3119 gnugo/sgf-*r4-properties*))
3122 ((esc (composed fmt arg)
3123 (mapconcat (lambda (c)
3125 ;; ‘?\[’ is not strictly required
3126 ;; but neither is it forbidden.
3127 ((?\[ ?\] ?\\) (format "\\%c" c))
3128 (?: (concat (if composed "\\" "") ":"))
3130 (string-to-list (format fmt arg))
3132 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
3133 (>>two (v) (insert "["
3134 (esc t "%s" (car v))
3136 (esc t "%s" (cdr v))
3138 (>>nl () (cond ((memq name aft-newline-appreciated)
3140 ((< 60 (current-column))
3148 (insert (substring (symbol-name name) 1))
3151 (setq spec (cdr (assq name specs)))
3155 (let ((>> (if (consp (cadr spec))
3158 (dolist (little-v v)
3160 (funcall >> little-v)
3167 (loop initially (insert ";")
3171 (unless (zerop (current-column))
3175 (funcall (if (gnugo--nodep x)
3181 (dolist (tree collection)
3182 ;; take responsibility for our actions
3183 (gnugo--set-root-prop :AP me tree)
3185 (let ((ht (gnugo--mkht))
3186 (leaves (append (gnugo--tree-ends tree) nil)))
3190 with rh ; rectified history
3191 with bp ; branch point
3193 until (setq bp (gethash node ht))
3195 (push node rh) ; good for now: ½τ
3199 ;; first run: main line
3201 ;; subsequent runs: grafts (value discarded)
3203 ;; Maintain order of ‘leaves’.
3204 (let ((was (cdr bp)))
3205 (if (gnugo--nodep (car was))
3209 (setq tree (hang (pop leaves)))
3210 (mapc #'hang leaves)
3213 (write-file filename)))))
3215 ;;; gnugo.el ends here