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") (xpm "1.0.1") (cl-lib "0.5"))
9 ;; Keywords: games, processes
10 ;; URL: http://www.gnuvola.org/software/gnugo/
12 ;; This program is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
30 ;; This file provides the command `gnugo' which allows you to play the game of
31 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
32 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
33 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
34 ;; Go" to refer to the process object created by running the external program.
36 ;; At the start of a new game, you can pass additional command-line arguments
37 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
38 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
39 ;; both komi and handicap.
41 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
42 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
43 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
44 ;; back through an arbitrary stone that you played, place the cursor on a
45 ;; stone and type `U' (note: uppercase).
47 ;; There are a great many other commands. Other keybindings are described in
48 ;; the `gnugo-board-mode' documentation, which you may view with the command
49 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
50 ;; the last move and who is currently to play. Capture counts and other info
51 ;; are shown on the mode line immediately following the major mode name.
53 ;; While GNU Go is pondering its next move, certain commands that rely on its
54 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
55 ;; is normal. When it is your turn again you may retry the command. In the
56 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
57 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
59 ;; If GNU Go should crash during a game the mode line will show "no process".
60 ;; Please report the event to the GNU Go maintainers so that they can improve
64 ;; Meta-Playing (aka Customizing)
65 ;; ------------------------------
67 ;; Customization is presently limited to
68 ;; vars: `gnugo-program'
69 ;; `gnugo-animation-string'
71 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
72 ;; `gnugo-undo-reaction'
73 ;; `gnugo-xpms' (see also gnugo-imgen.el)
74 ;; normal hooks: `gnugo-board-mode-hook'
75 ;; `gnugo-frolic-mode-hook'
76 ;; `gnugo-start-game-hook'
77 ;; `gnugo-post-move-hook'
78 ;; and the keymaps: `gnugo-board-mode-map'
79 ;; `gnugo-frolic-mode-map'
82 ;; Meta-Meta-Playing (aka Hacking)
83 ;; -------------------------------
85 ;; <http://git.sv.gnu.org/cgit/emacs/elpa.git/tree/packages/gnugo/>
89 (require 'cl-lib) ; use the source luke!
90 (require 'time-date) ; for `time-subtract'
92 ;;;---------------------------------------------------------------------------
95 (defconst gnugo-version "3.0.0"
96 "Version of gnugo.el currently loaded.
97 This follows a MAJOR.MINOR.PATCH scheme.")
99 ;;;---------------------------------------------------------------------------
100 ;;; Variables for the uninquisitive programmer
102 (defvar gnugo-program "gnugo"
103 "Name of the GNU Go program (executable file).
104 \\[gnugo] validates this using `executable-find'.
105 This program must accept command line args:
107 For more information on GTP and GNU Go, please visit:
108 <http://www.gnu.org/software/gnugo>")
110 (defvar gnugo-board-mode-map
111 ;; Re <http://lists.gnu.org/archive/html/emacs-devel/2014-04/msg00123.html>,
112 ;; ideally we could ‘defvar’ here w/o value and also ‘defvar’ below
113 ;; in "load-time actions" w/ value and docstring, to avoid this ugly
114 ;; (from the forward references) block early in the file. Unfortunately,
115 ;; byte-compiling such a split formulation results in the initial ‘defvar’
116 ;; being replaced by:
117 ;; (defvar VAR (make-sparse-keymap))
118 ;; and the second ‘defvar’ is ignored on load. At least, this is the case
119 ;; for Emacs built from repo (trunk) 2014-05-27. --ttn
120 (let ((map (make-sparse-keymap)))
121 (suppress-keymap map)
123 (define-key map (car pair) (cdr pair)))
124 '(("?" . describe-mode)
125 ("S" . gnugo-request-suggestion)
126 ("\C-m" . gnugo-move)
131 ("Q" . gnugo-leave-me-alone)
132 ("U" . gnugo-fancy-undo)
133 ("\M-u" . gnugo-undo-one-move)
134 ("u" . gnugo-undo-two-moves)
135 ("\C-?" . gnugo-undo-two-moves)
138 ("\C-l" . gnugo-refresh)
139 ("\M-_" . gnugo-boss-is-near)
140 ("_" . gnugo-boss-is-near)
141 ("h" . gnugo-move-history)
142 ("L" . gnugo-frolic-in-the-leaves)
143 ("\C-c\C-l" . gnugo-frolic-in-the-leaves)
144 ("i" . gnugo-image-display-mode)
145 ("w" . gnugo-worm-stones)
146 ("W" . gnugo-worm-data)
147 ("d" . gnugo-dragon-stones)
148 ("D" . gnugo-dragon-data)
149 ("g" . gnugo-grid-mode)
150 ("!" . gnugo-estimate-score)
151 (":" . gnugo-command)
152 (";" . gnugo-command)
153 ("=" . gnugo-describe-position)
154 ("s" . gnugo-write-sgf-file)
155 ("\C-x\C-s" . gnugo-write-sgf-file)
156 ("\C-x\C-w" . gnugo-write-sgf-file)
157 ("l" . gnugo-read-sgf-file)
158 ("F" . gnugo-display-final-score)
159 ("A" . gnugo-switch-to-another)
160 ("C" . gnugo-comment)
161 ("\C-c\C-a" . gnugo-assist-mode)
162 ("\C-c\C-z" . gnugo-zombie-mode)
164 ([(down-mouse-1)] . gnugo-mouse-move)
165 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
166 ([(down-mouse-3)] . gnugo-mouse-pass)
167 ;; delving into the curiosities
168 ("\C-c\C-p" . gnugo-describe-internal-properties)))
170 "Keymap for GNUGO Board mode.")
172 (defvar gnugo-board-mode-hook nil
173 "Hook run when entering GNUGO Board mode.")
175 (defvar gnugo-start-game-hook nil
176 "Normal hook run immediately before the first move of the game.
177 To find out who is to move first, use `gnugo-current-player'.
178 See also `gnugo-board-mode'.")
180 (defvar gnugo-post-move-hook nil
181 "Normal hook run after a move and before the board is refreshed.
182 Initially, when `run-hooks' is called, the current buffer is the GNUGO
183 Board buffer of the game. Hook functions that switch buffers must take
184 care not to call (directly or indirectly through some other function)
185 `gnugo-put' or `gnugo-get' after the switch.")
187 (defvar gnugo-animation-string
188 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
189 (concat jam jam jam jam jam
190 ;; "SECRET MESSAGE HERE"
191 blink blink blink blink blink blink blink blink
192 ;; Playing go is like fighting ignorance: when you think you have
193 ;; surrounded something by knowing it very well it often turns
194 ;; out that in the time you spent deepening this understanding,
195 ;; other areas of ignorance have surrounded you.
196 spin spin spin spin spin spin spin spin spin
197 ;; Playing go is not like fighting ignorance: what one person
198 ;; knows many people may come to know; knowledge does not build
199 ;; solely move by move. Wisdom, on the other hand...
201 "String whose individual characters are used for animation.
202 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
203 render the stones in their respective result groups as the first character
204 in the string, then the next, and so on.")
206 (defvar gnugo-mode-line "~b ~w :~m :~u"
207 "A `mode-line-format'-compliant value for GNUGO Board mode.
208 If a single string, the following special escape sequences are
209 replaced with their associated information:
210 ~b,~w black,white captures (a number)
211 ~p current player (black or white)
213 ~t time waiting for the current move
214 ~u time taken for the Ultimate (most recent) move
215 The times are in seconds, or \"-\" if that information is not available.
216 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
218 (defvar gnugo-X-face 'font-lock-string-face
219 "Name of face to use for X (black) stones.")
221 (defvar gnugo-O-face 'font-lock-builtin-face
222 "Name of face to use for O (white) stones.")
224 (defvar gnugo-grid-face 'default
225 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
227 (defvar gnugo-undo-reaction 'play!
228 "What to do if undo (or oops) leaves GNU Go to play.
229 After `gnugo-undo-one-move', `gnugo-undo-two-moves' or `gnugo-oops',
230 when GNU Go is to play, this can be a symbol:
231 play -- make GNU Go play (unless in Zombie mode)
232 play! -- make GNU Go play unconditionally (traditional behavior)
233 zombie -- enable Zombie mode (`gnugo-zombie-mode')
234 one-shot -- like `zombie' but valid only for the next move
235 Any other value, or (as a special case) for `gnugo-undo-one-move',
236 any value other than `zombie', is taken as `one-shot'. Note that
237 making GNU Go play will probably result in the recently-liberated
238 board position becoming re-occupied.")
240 (defvar gnugo-xpms nil
241 "List of 46 ((TYPE . LOCATION) . XPM-IMAGE) forms.
242 XPM-IMAGE is an image as returned by `create-image' with
243 inline data (i.e., property :data with string value).
245 TYPE is a symbol, one of:
246 hoshi -- unoccupied position with dot
247 empty -- unoccupied position sans dot
248 bpmoku, bmoku -- black stone with and sans highlight point
249 wpmoku, wmoku -- white stone with and sans highlight point
251 LOCATION is an integer encoding edge, corner, or center:
255 For instance, 4 means \"left edge\", 9 means \"bottom right\".
257 There is only one location for hoshi: center. The other five
258 types each have all possible locations. So (+ 1 (* 9 5)) => 46.
260 The value can also be a function (satisfying `functionp') that
261 takes one arg, the size of the board, and returns the appropriate
264 ;;;---------------------------------------------------------------------------
265 ;;; Variables for the inquisitive programmer
267 (defconst gnugo-font-lock-keywords
268 '(("X" . gnugo-X-face)
269 ("O" . gnugo-O-face))
270 "Font lock keywords for `gnugo-board-mode'.")
272 (defvar gnugo-option-history nil)
274 (defvar gnugo-state nil) ; hint: C-c C-p
276 (defvar gnugo-btw nil)
278 ;;;---------------------------------------------------------------------------
279 ;;; Support functions
281 (defsubst gnugo--mkht (&rest etc)
282 (apply 'make-hash-table :test 'eq etc))
284 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
285 (compare-strings s1 beg1 nil s2 beg2 nil))
287 (defun gnugo-put (key value)
288 "Associate move/game/board-specific property KEY with VALUE.
290 There are many properties, each named by a keyword, that record and control
291 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
292 of properties, stored in the hash table `gnugo-state'. Here we document
293 some of the more stable properties. You may wish to use them as part of
294 a `gnugo-post-move-hook' function, for example. Be careful to preserve
295 the current buffer as `gnugo-state' is made into a buffer-local variable.
296 NOTE: In the following, \"see foo\" actually means \"see foo source or
297 you may never really understand to any degree of personal satisfaction\".
299 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
301 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
303 :game-over -- nil until game over at which time its value is set to
304 the alist `((live GROUP ...) (dead GROUP ...))'
306 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
307 a simple list of one or more gametrees, updated in
308 conjunction w/ :sgf-gametree and :monkey
310 :sgf-gametree -- one of the gametrees in :sgf-collection
312 :monkey -- vector of two elements:
313 MEM, a pointer to one of the branches in the gametree;
314 BIDX, the index of the \"current branch\"
316 :gnugo-color -- either \"black\" or \"white\"
320 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
323 :black-captures -- these are strings since gnugo.el doesn't do anything
324 :white-captures w/ the information besides display it in the mode line;
325 gory details in functions `gnugo-propertize-board-buffer'
326 and `gnugo-merge-showboard-results' (almost more effort
327 than they are worth!)
329 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
330 `gnugo-toggle-image-display' and `gnugo-refresh',
331 as well as gnugo-xpms.el (available elsewhere)
333 :all-yy -- list of 46 symbols used as the `category' text property
334 (so that their plists, typically w/ property `display' or
335 `do-not-display') are consulted by the Emacs display engine;
336 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
337 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
339 :paren-ov -- a pair (left and right) of overlays shuffled about to indicate
340 the last move; only one is used when displaying using images
342 :last-user-bpos -- board position; keep the hapless human happy
344 As things stabilize probably more info will be added to this docstring."
346 (puthash key value gnugo-state))
348 (defun gnugo-get (key)
349 "Return the move/game/board-specific value for KEY.
351 (gethash key gnugo-state))
353 (defun gnugo--forget (&rest keys)
355 (remhash key gnugo-state)))
357 (defsubst gnugo--tree-mnum (tree)
360 (defsubst gnugo--tree-ends (tree)
363 (defsubst gnugo--set-tree-ends (tree ls)
364 (aset tree 0 (apply 'vector ls))
365 (gnugo--tree-ends tree))
367 (defun gnugo--root-node (&optional tree)
368 (aref (or tree (gnugo-get :sgf-gametree))
371 (defun gnugo-describe-internal-properties ()
372 "Pretty-print `gnugo-state' properties in another buffer.
373 Handle the big, slow-to-render, and/or uninteresting ones specially."
375 (let ((buf (current-buffer))
376 (d (gnugo-get :diamond))
378 for key being the hash-keys of gnugo-state
379 using (hash-values val)
383 (format "hash: %X (%d images)"
389 (list (hash-table-count
390 (gnugo--tree-mnum val))
391 (gnugo--root-node val)
392 (gnugo--tree-ends val)))
394 (let ((mem (aref val 0)))
398 (switch-to-buffer (get-buffer-create
399 (format "%s*GNUGO Board Properties*"
403 (setq truncate-lines t)
407 (goto-char (point-min))
408 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
412 (while (re-search-forward rx nil t)
413 (let ((pos (get-text-property (string-to-number (match-string 1))
414 'gnugo-position buf)))
415 (delete-region (+ 2 (match-beginning 0)) (point))
416 (insert (format " %S" pos))))))
417 (message "%d properties" (length acc))))
419 (defun gnugo-board-buffer-p (&optional buffer)
420 "Return non-nil if BUFFER is a GNUGO Board buffer."
421 (eq 'gnugo-board-mode
424 (or buffer (current-buffer)))))
426 (defun gnugo-board-user-play-ok-p (&optional buffer)
427 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
428 (with-current-buffer (or buffer (current-buffer))
429 (and gnugo-state (not (gnugo-get :waiting)))))
431 (defsubst gnugo--blackp (string)
432 (string= "black" string))
434 (defun gnugo-other (color)
435 (if (gnugo--blackp color) "white" "black"))
437 (defun gnugo-current-player ()
438 "Return the current player, either \"black\" or \"white\"."
439 (gnugo-other (gnugo-get :last-mover)))
441 (defsubst gnugo--prop<-color (color)
442 (if (gnugo--blackp color) :B :W))
444 (defun gnugo-gate (&optional in-progress-p)
445 (unless (gnugo-board-buffer-p)
446 (user-error "Wrong buffer -- try M-x gnugo"))
447 (unless (gnugo-get :proc)
448 (user-error "No \"gnugo\" process!"))
449 (cl-destructuring-bind (&optional color . suggestion)
453 "%s -- please wait for \"(%s to play)\""
455 (list "Still thinking"
457 (list "Not your turn yet"
458 (gnugo-other color))))))
459 (when (and in-progress-p (gnugo-get :game-over))
460 (user-error "Sorry, game over")))
462 (defun gnugo-sentinel (proc string)
463 (let ((status (process-status proc)))
464 (when (memq status '(exit signal))
465 (let ((buf (process-buffer proc)))
466 (when (buffer-live-p buf)
467 (with-current-buffer buf
468 (setq mode-line-process
470 (propertize (car (split-string string))
471 'face 'font-lock-warning-face)
473 (when (eq proc (gnugo-get :proc))
474 (gnugo--forget :proc))))))))
476 (defun gnugo--begin-exchange (proc filter line)
477 (declare (indent 2)) ; good time, for a rime
478 ; nice style, for a wile...
479 (set-process-filter proc filter)
480 (process-send-string proc line)
481 (process-send-string proc "\n"))
483 (defun gnugo--q (fmt &rest args)
484 "Send formatted command \"FMT ARGS...\"; wait for / return response.
485 The response is a string whose first two characters indicate the
486 status of the command. See also `gnugo-query'."
487 (let ((slow (gnugo-get :waiting))
488 (proc (gnugo-get :proc)))
490 (user-error "Sorry, still waiting for %s to %s"
491 (car slow) (if (cdr slow)
492 "receive a suggestion"
494 (process-put proc :incomplete t)
495 (process-put proc :srs "") ; synchronous return stash
496 (gnugo--begin-exchange
497 proc (lambda (proc string)
498 (let ((full (concat (process-get proc :srs)
500 (process-put proc :srs full)
501 (unless (numberp (gnugo--compare-strings
502 full (max 0 (- (length full)
505 (process-put proc :incomplete nil))))
508 (apply #'format fmt args)))
509 (while (process-get proc :incomplete)
510 (accept-process-output proc 30))
511 (prog1 (substring (process-get proc :srs) 0 -2)
512 (process-put proc :srs ""))))
514 (defsubst gnugo--no-worries (string)
515 (= ?= (aref string 0)))
517 (defun gnugo--q/ue (fmt &rest args)
518 (let ((ans (apply 'gnugo--q fmt args)))
519 (unless (gnugo--no-worries ans)
520 (user-error "%s" ans))
523 (defun gnugo-query (message-format &rest args)
524 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
525 Return a string that omits the first two characters (corresponding
526 to the status indicator in the Go Text Protocol). Use this function
527 when you are sure the command cannot fail."
528 (substring (apply 'gnugo--q message-format args)
531 (defun gnugo--nquery (cmd)
532 (string-to-number (gnugo-query cmd)))
534 (defun gnugo-lsquery (message-format &rest args)
535 (split-string (apply 'gnugo-query message-format args)))
537 (defsubst gnugo--count-query (fmt &rest args)
538 (length (apply 'gnugo-lsquery fmt args)))
540 (defsubst gnugo--root-prop (prop &optional tree)
541 (cdr (assq prop (gnugo--root-node tree))))
543 (defun gnugo--set-root-prop (prop value &optional tree)
544 (let* ((root (gnugo--root-node tree))
545 (cur (assq prop root)))
548 (push (cons prop value)
549 (cdr (last root))))))
551 (defun gnugo-goto-pos (pos)
552 "Move point to board position POS, a letter-number string."
553 (goto-char (point-min))
554 (forward-line (- (1+ (gnugo-get :SZ))
555 (string-to-number (substring pos 1))))
557 (forward-char (+ (if (= 32 (following-char)) 1 2)
558 (* 2 (- (let ((letter (aref pos 0)))
565 (intern (if (symbolp id)
568 (gnugo-get :obarray)))
570 (defun gnugo-yang (c)
571 (cdr (assq c '((?+ . hoshi)
573 (?X . (bmoku . bpmoku))
574 (?O . (wmoku . wpmoku))))))
576 (defun gnugo-yy (yin yang &optional momentaryp)
577 (gnugo-f (format "%d-%s"
578 yin (cond ((symbolp yang) yang)
579 (momentaryp (cdr yang))
582 (defun gnugo-toggle-image-display ()
583 (unless (display-images-p)
584 (user-error "Display does not support images, sorry"))
585 (let ((fresh (if (functionp gnugo-xpms)
586 (funcall gnugo-xpms (gnugo-get :SZ))
589 (user-error "Sorry, `gnugo-xpms' unset"))
590 (unless (eq fresh (gnugo-get :xpms))
591 (gnugo-put :xpms fresh)
592 (gnugo--forget :all-yy)))
593 (let* ((new (not (gnugo-get :display-using-images)))
594 (act (if new 'display 'do-not-display)))
596 (setcar (symbol-plist yy) act))
597 (or (gnugo-get :all-yy)
599 (prog1 (mapcar (lambda (ent)
601 (yy (gnugo-yy (cdr k) (car k))))
602 (setplist yy `(not-yet ,(cdr ent)))
606 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
608 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
609 (gnugo-put :highlight-last-move-spec
612 (get (gnugo-yy (get-text-property p 'gnugo-yin)
613 (get-text-property p 'gnugo-yang)
617 (gnugo-get :default-highlight-last-move-spec)))
618 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
619 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
620 (mapc 'delete-overlay (cdar group))
621 (setcdr (car group) nil))
622 (gnugo-put :mul (if new
625 (gnugo-put :display-using-images new)))
627 (define-minor-mode gnugo-grid-mode
628 "If enabled, display grid around the board."
630 ((not (memq :nogrid buffer-invisibility-spec))
634 'remove-from-invisibility-spec
635 'add-to-invisibility-spec)
637 (save-excursion (gnugo-refresh)))))
639 (defun gnugo-propertize-board-buffer ()
641 (insert (substring (gnugo--q "showboard") 3))
642 (let* ((grid-props (list 'invisible :nogrid
643 'font-lock-face gnugo-grid-face))
644 (%gpad (gnugo-f 'gpad))
645 (%gspc (gnugo-f 'gspc))
646 (%lpad (gnugo-f 'lpad))
647 (%rpad (gnugo-f 'rpad))
648 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
649 (size (gnugo-get :SZ))
650 (size-string (number-to-string size)))
651 (goto-char (point-min))
652 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
653 (skip-chars-forward " ")
654 (put-text-property (1- (point)) (point) 'category %gpad)
655 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
657 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
658 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
659 (let* ((row (match-string-no-properties 1))
661 (other-edge (+ edge (* 2 size) -1))
662 (right-empty (+ other-edge (length row) 1))
663 (top-p (string= size-string row))
664 (bot-p (string= "1" row)))
665 (let* ((nL (- edge 1 (length size-string)))
667 (ov (make-overlay nL nR (current-buffer) t)))
668 (add-text-properties nL nR grid-props)
669 ;; We redundantly set `invisible' in the overlay to workaround
670 ;; a display bug whereby text *following* the overlaid text is
671 ;; displayed with the face of the overlaid text, but only when
672 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
673 ;; This has something to do w/ the bletcherous `before-string'.
674 (overlay-put ov 'invisible :nogrid)
675 (overlay-put ov 'category %lpad))
676 (cl-do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
678 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
679 (truncate (- p edge) 2))
681 (yin (let ((A-p (= edge p))
682 (Z-p (= (1- other-edge) p)))
683 (cond ((and top-p A-p) 1)
692 (yang (gnugo-yang (char-after p))))
693 (add-text-properties p (1+ p)
703 (gnugo-position gnugo-yin))))
704 (unless (= (1- other-edge) p)
705 (add-text-properties (1+ p) (+ 2 p) ispc-props)
706 (put-text-property p (+ 2 p) 'intangible ival)))
707 (add-text-properties (1+ other-edge) right-empty grid-props)
708 (goto-char right-empty)
709 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
710 (let ((prop (if (string= "WH" (match-string 1))
713 (beg (match-beginning 2))
715 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
716 (gnugo-put prop (match-string-no-properties 2))))
718 (put-text-property right-empty (point) 'category %rpad)
720 (add-text-properties (1- (point)) (point-max) grid-props)
721 (skip-chars-forward " ")
722 (put-text-property (1- (point)) (point) 'category %gpad)
723 (put-text-property (point) (progn (end-of-line) (point))
726 (defun gnugo-merge-showboard-results ()
727 (let ((aft (substring (gnugo--q "showboard") 3))
728 (adj 1) ; string to buffer position adjustment
730 (sync "[0-9]* stones$")
731 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
732 ;; restrictive a condition that fails in the case of:
735 ;; ... WHITE has captured 1 stones
738 ;; ... WHITE has captured 14 stones
741 ;; where the after count has more digits than the before count,
742 ;; but shares the same leading digits. In this case, the result
743 ;; of `compare-strings' points to the SPC following the before
744 ;; count (indicated by caret in this example).
746 (bef (buffer-substring-no-properties (point-min) (point-max)))
747 (bef-start 0) (bef-idx 0)
748 (aft-start 0) (aft-idx 0)
749 aft-sync-backtrack mis inc cut new very-strange
751 (inhibit-read-only t))
752 (while (numberp (setq mis (gnugo--compare-strings
755 (setq aft-sync-backtrack nil
756 inc (if (cl-minusp mis)
759 bef-idx (+ bef-start inc)
760 aft-idx (+ aft-start inc)
761 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
764 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
765 (let ((peek (1- aft-idx)))
766 (while (not (= 32 (aref aft peek)))
767 (setq peek (1- peek)))
768 (setq aft-sync-backtrack (1+ peek))))
772 (if aft-sync-backtrack
773 (- aft-sync-backtrack aft-idx)
776 (if aft-sync-backtrack
777 (let* ((asb aft-sync-backtrack)
778 (l-p (get-text-property cut :gnugo-cf))
781 (keep (text-properties-at cut)))
782 (setq new (substring aft asb (string-match " " aft asb)))
783 (plist-put keep :gnugo-cf (cons (length new) capprop))
784 (gnugo-put capprop new)
785 (delete-char old-len)
786 (insert (apply 'propertize new keep))
787 (cl-incf adj (- (length new) old-len)))
788 (setq new (aref aft aft-idx))
789 (insert-and-inherit (char-to-string new))
790 (let ((yin (get-text-property cut 'gnugo-yin))
791 (yang (gnugo-yang new)))
792 (add-text-properties cut (1+ cut)
796 ,(gnugo-yy yin yang))))
798 ;; do this last to avoid complications w/ font lock
799 ;; (this also means we cannot include `intangible' in `front-sticky')
800 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
801 (put-text-property cut (1+ cut) 'intangible very-strange))))))
803 (defsubst gnugo--move-prop (node)
807 (defun gnugo--as-pos-func ()
808 (let ((size (gnugo-get :SZ)))
813 (let ((col (aref cc 0)))
815 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
816 (- size (- (aref cc 1) ?a))))))))
818 (defsubst gnugo--resignp (string)
819 (string= "resign" string))
821 (defsubst gnugo--passp (string)
822 (string= "PASS" string))
824 (defun gnugo-move-history (&optional rsel color)
825 "Determine and return the game's move history.
826 Optional arg RSEL controls side effects and return value.
827 If nil, display the history in the echo area as \"(N moves)\"
828 followed by the space-separated list of moves. When called
829 interactively with a prefix arg (i.e., RSEL is `(4)'), display
830 similarly, but suffix with the mover (either \":B\" or \":W\").
831 RSEL may also be a symbol that selects what to return:
832 car -- the most-recent move
833 cadr -- the next-to-most-recent move
834 two -- the last two moves as a list, oldest last
835 bpos -- the last stone on the board placed by COLOR
836 For all other values of RSEL, do nothing and return nil."
838 (let* ((monkey (gnugo-get :monkey))
839 (mem (aref monkey 0))
840 (as-pos (gnugo--as-pos-func))
843 ((as-pos-maybe (x) (if (gnugo--resignp x)
846 (remem () (setq node (pop mem)
847 mprop (gnugo--move-prop node)))
848 (next (byp) (when (remem)
849 (setq move (as-pos-maybe (cdr mprop)))
851 (format "%s%s" move (car mprop))
855 (tell () (message "(%d moves) %s"
857 (mapconcat 'identity (nreverse acc) " ")))
858 (finish (byp) (while mem (next byp)) (tell)))
863 (`cadr (nn) (car (nn)))
866 with prop = (gnugo--prop<-color color)
869 (eq prop (car mprop))
870 (setq move (cdr mprop))
871 ;; i.e., "normal CC" position
873 return (funcall as-pos move)))
876 (defun gnugo-boss-is-near ()
877 "Do `bury-buffer' until the current one is not a GNU Board."
879 (while (gnugo-board-buffer-p)
882 (defsubst gnugo--no-regrets (monkey ends)
883 (eq (aref ends (aref monkey 1))
886 (defun gnugo--as-cc-func ()
887 (let ((size (gnugo-get :SZ)))
889 (let* ((col (aref pos 0))
890 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
891 (two (+ ?a (- size (string-to-number
892 (substring pos 1))))))
893 (format "%c%c" one two)))))
895 (defun gnugo--decorate (node &rest plist)
897 with tp = (last node)
901 fruit (list (cons ; DWR: LtR OoE assumed.
907 (defun gnugo-close-game (end-time resign)
908 (gnugo-put :game-end-time end-time)
909 (let ((now (or end-time (current-time))))
910 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
912 (gnugo-put :game-over
913 (if (or (eq t resign)
914 (and (stringp resign)
915 (string-match "[BW][+][Rr]esign" resign)))
922 (gnugo-query "worm_stones %s" color)
924 (let ((live (append (ls "black") (ls "white"))))
927 (let ((dd (gnugo-query "dragon_data"))
928 (start 0) mem color ent live dead)
929 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
931 (setq mem (match-string 1 dd)
932 color (match-string 2 dd)
934 ent (cons (list color)
935 (sort (gnugo-lsquery "dragon_stones %s" mem)
937 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
939 (if (match-string 2 dd)
942 (setq start (match-end 0)))
946 (defun gnugo--unclose-game ()
947 (gnugo--forget :game-over ; all those in -close-game
950 (let* ((root (gnugo--root-node))
951 (cur (assq :RE root)))
953 (cl-assert (not (eq cur (car root))) nil
954 ":RE at head of root node: %S"
958 (defun gnugo-push-move (who move)
959 (let* ((simple (booleanp who))
960 (ucolor (gnugo-get :user-color))
964 (gnugo-get :gnugo-color))
966 (start (gnugo-get :waiting-start))
968 (resignp (gnugo--resignp move))
969 (passp (gnugo--passp move))
970 (head (gnugo-move-history 'car))
971 (onep (and head (gnugo--passp head)))
972 (donep (or resignp (and onep passp))))
974 (gnugo--q/ue "play %s %s" color move))
976 (gnugo-merge-showboard-results))
977 (gnugo-put :last-mover color)
980 (string= ucolor color))
981 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
982 ;; update :sgf-gametree and :monkey
983 (let* ((property (gnugo--prop<-color color))
984 (pair (cons property (cond (resignp move)
986 (t (funcall (gnugo--as-cc-func)
989 (monkey (gnugo-get :monkey))
990 (mem (aref monkey 0))
992 (tree (gnugo-get :sgf-gametree))
993 (ends (gnugo--tree-ends tree))
994 (mnum (gnugo--tree-mnum tree))
995 (count (length ends))
996 (tip-move-num (gethash tip mnum))
997 (bidx (aref monkey 1)))
998 ;; Detect déjà-vu. That is, when placing "A", avoid:
1004 ;; (such "variations" do not actually vary!) in favor of:
1010 ;; This linear search loses for multiple ‘old’ w/ "A",
1011 ;; a very unusual (but not invalid, sigh) situation.
1015 ;; Start with latest / highest likelihood for hit.
1016 ;; (See "to the right" comment, below.)
1017 from (if (gnugo--no-regrets monkey ends)
1021 if (setq bx (mod (+ bidx i) count)
1025 for m on (aref ends bx)
1026 while (< tip-move-num
1027 (gethash (setq node (car m))
1030 return (when (equal pair (assq property node))
1032 finally return nil))
1037 (cl-rotatef (aref ends bidx)
1039 (setq mem previous))
1043 (unless (gnugo--no-regrets monkey ends)
1044 (setq ends (gnugo--set-tree-ends
1045 tree (let ((ls (append ends nil)))
1046 ;; copy old to the right of new
1047 (push mem (nthcdr bidx ls))
1049 (puthash fruit (1+ (gethash tip mnum)) mnum)
1051 (aset ends bidx mem)))
1052 (setf (aref monkey 0) mem))
1054 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1056 (gnugo-close-game now resignp))
1057 (gnugo-put :waiting-start (and (not donep) now))
1060 (defun gnugo-venerate (yin yang)
1061 (let* ((fg-yy (gnugo-yy yin yang))
1062 (fg-disp (or (get fg-yy 'display)
1063 (get fg-yy 'do-not-display)))
1064 (fg-props (cdr fg-disp))
1065 (fg-data (plist-get fg-props :data))
1066 (c-symbs (plist-get fg-props :color-symbols))
1067 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1068 (bg-disp (or (get bg-yy 'display)
1069 (get bg-yy 'do-not-display)))
1070 (bg-data (plist-get (cdr bg-disp) :data))
1074 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1075 (setq start (match-end 0))
1076 (string-to-number (match-string 1 s)))))
1077 (while (and (not (cl-minusp ncolors))
1078 (string-match ",\n" s start))
1079 (setq start (match-end 0)
1080 ncolors (1- ncolors)))
1081 (string-match "\"" s start)
1083 (new (copy-sequence fg-data))
1084 (lx (length fg-data))
1085 (sx (funcall bop fg-data))
1086 (sb (funcall bop bg-data))
1087 (color-key (aref new sx))) ; blech, heuristic
1089 (when (and (not (= color-key (aref new sx)))
1090 (cl-plusp (random 4)))
1091 (aset new sx (aref bg-data sb)))
1094 (apply 'create-image new 'xpm t
1095 :ascent 'center (when c-symbs
1096 (list :color-symbols
1099 (defun gnugo-refresh (&optional nocache)
1100 "Update GNUGO Board buffer display.
1101 While a game is in progress, parenthesize the last-played stone (no parens
1102 for pass). If the buffer is currently displayed in the selected window,
1103 recenter the board (presuming there is extra space in the window). Update
1104 the mode line. Lastly, move point to the last position played by the user,
1105 if that move was not a pass.
1107 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1108 be slow. (This should normally be unnecessary; specify it only if the display
1109 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1112 (let* ((move (gnugo-move-history 'car))
1113 (game-over (gnugo-get :game-over))
1114 (inhibit-read-only t)
1116 (when (and nocache (not (gnugo-get :waiting)))
1117 (gnugo-propertize-board-buffer))
1120 (cl-destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1121 (if (member move '("PASS" "resign"))
1122 (mapc 'delete-overlay (list l-ov r-ov))
1123 (gnugo-goto-pos move)
1125 (hspec (gnugo-get :highlight-last-move-spec))
1126 (display-value (nth 0 hspec))
1127 (l-offset (nth 1 hspec))
1128 (l-new-pos (+ p l-offset))
1129 (r-action (nth 2 hspec)))
1130 (overlay-put l-ov 'display
1131 (if (functionp display-value)
1132 (funcall display-value p)
1134 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1136 (funcall r-action r-ov)
1137 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1139 (rename-buffer (concat (gnugo-get :diamond)
1141 (format "%s(game over)"
1142 (if (gnugo--resignp move)
1143 (concat move "ation ")
1145 (format "%s(%s to play)"
1146 (if move (concat move " ") "")
1147 (gnugo-current-player)))))
1150 (let ((live (cdr (assq 'live game-over)))
1151 (dead (cdr (assq 'dead game-over)))
1153 (unless (eq game-over (get-text-property 1 'game-over))
1154 (dolist (group (append live dead))
1155 (dolist (pos (cdr group))
1156 (gnugo-goto-pos pos)
1158 (put-text-property p (1+ p) 'group group)))
1159 (put-text-property 1 2 'game-over game-over))
1160 (dolist (group live)
1161 (when (setq pall (cdar group))
1162 (mapc 'delete-overlay pall)
1163 (setcdr (car group) nil)))
1164 (dolist (group dead)
1165 (unless (cdar group)
1166 (let (ov pall c (color (caar group)))
1167 (setq c (if (gnugo--blackp color) "x" "o"))
1168 (dolist (pos (cdr group))
1169 (gnugo-goto-pos pos)
1170 (setq p (point) ov (make-overlay p (1+ p)))
1173 (if (gnugo-get :display-using-images)
1174 ;; respect the dead individually; it takes more time
1175 ;; but that's not a problem (for them)
1176 (gnugo-venerate (get-text-property p 'gnugo-yin)
1177 (gnugo-yang (aref (upcase c) 0)))
1178 (propertize c 'face 'font-lock-warning-face)))
1180 (setcdr (car group) pall))))))
1182 (when (setq window (get-buffer-window (current-buffer)))
1183 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1184 (size (gnugo-get :SZ))
1185 (under10p (< size 10))
1186 (mul (gnugo-get :mul))
1187 (h (- (truncate (- (window-height window)
1192 (edges (window-edges window))
1193 (right-w-edge (nth 2 edges))
1194 (avail-width (- right-w-edge (nth 0 edges)))
1196 (imagesp (symbol-plist (gnugo-f 'ispc)))
1197 (w (/ (- avail-width
1202 2 ; between board and grid
1207 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1208 `(display ,(make-string h 10))
1209 '(invisible :nogrid)))
1214 (cond (imagesp (+ (* 0.5 wmul)
1220 (gspc . ,(when imagesp
1224 ;; DWR: image width alone => OBOE!
1226 ;; NB: ‘(* wmul cw)’ is the same
1227 ;; as ‘(car (image-size ... t))’.
1228 (let ((cw (frame-char-width)))
1229 (/ (+ 1.0 (* wmul cw))
1232 (lpad . ,(let ((d `(display (space :align-to ,w))))
1233 ;; We distinguish between these cases to
1234 ;; workaround a display bug whereby the
1235 ;; `before-string' is omitted entirely (not
1236 ;; rendered) when interacting w/ the text
1237 ;; mode last-move left-paren for moves in
1241 ,(apply 'propertize " " d))
1244 (space :align-to ,(1- avail-width))))))
1245 (setplist (gnugo-f (car pair)) (cdr pair)))))
1247 (let ((cur (gnugo-get :mode-line)))
1248 (unless (equal cur gnugo-mode-line)
1249 (setq cur gnugo-mode-line)
1250 (gnugo-put :mode-line cur)
1251 (gnugo-put :mode-line-form
1252 (cond ((stringp cur)
1253 (setq cur (copy-sequence cur))
1255 (while (setq cut (string-match "~[bwpmtu]" cur))
1257 (setq c (aref cur (cl-incf cut)))
1260 `(,(intern (format "squig-%c" c))
1262 (?b '(or (gnugo-get :black-captures) 0))
1263 (?w '(or (gnugo-get :white-captures) 0))
1264 (?p '(gnugo-current-player))
1265 (?t '(let ((ws (gnugo-get :waiting-start)))
1267 (cadr (time-since ws))
1269 (?u '(or (gnugo-get :last-waiting) "-"))
1270 (?m '(let ((tree (gnugo-get :sgf-gametree))
1271 (monkey (gnugo-get :monkey)))
1272 (gethash (car (aref monkey 0))
1273 (gnugo--tree-mnum tree)
1274 ;; should be unnecessary
1277 `(let ,(delete-dups (copy-sequence acc))
1278 (format ,cur ,@(reverse (mapcar 'car acc))))))
1280 (let ((form (gnugo-get :mode-line-form)))
1281 (setq mode-line-process
1283 ;; this dynamicism is nice but excessive in its wantonness
1284 ;;- `(" [" (:eval ,form) "]")
1285 ;; this dynamicism is ok because the user triggers it
1286 (format " [%s]" (eval form)))))
1287 (force-mode-line-update))
1289 (when (setq last (gnugo-get :last-user-bpos))
1290 (gnugo-goto-pos last))))
1292 (defun gnugo--turn-the-wheel (&optional now)
1293 (unless (gnugo-get :waiting)
1294 (let ((color (gnugo-current-player))
1295 (wheel (gnugo-get :wheel)))
1297 (when (and (not (gnugo-get :game-over))
1298 (member color (cdr wheel)))
1302 2) ;;; sec (frettoloso? dubioso!)
1304 (lambda (buf color wheel)
1306 (with-current-buffer buf
1307 (gnugo-get-move color)))
1311 (defun gnugo--finish-move (&optional now)
1312 (let ((buf (current-buffer)))
1313 (run-hooks 'gnugo-post-move-hook)
1316 (gnugo--turn-the-wheel now))
1318 ;;;---------------------------------------------------------------------------
1319 ;;; Game play actions
1321 (defun gnugo--rename-buffer-portion (&optional back)
1322 (let ((old "to play")
1323 (new "waiting for suggestion"))
1325 (cl-rotatef old new))
1326 (let ((name (buffer-name)))
1327 (when (string-match old name)
1328 (rename-buffer (replace-match new t t name))))))
1330 (defun gnugo--display-suggestion (color suggestion)
1331 (message "%sSuggestion for %s: %s"
1332 (gnugo-get :diamond)
1335 (defun gnugo-get-move-insertion-filter (proc string)
1336 (with-current-buffer (process-buffer proc)
1337 (let* ((so-far (gnugo-get :get-move-string))
1338 (full (gnugo-put :get-move-string (concat so-far string))))
1339 (when (string-match "^= \\(.+\\)\n\n" full)
1340 (setq full (match-string 1 full)) ; POS or "PASS"
1341 (cl-destructuring-bind (color . suggestion)
1342 (gnugo-get :waiting)
1343 (gnugo--forget :get-move-string
1347 (gnugo--rename-buffer-portion t)
1348 (unless (or (gnugo--passp full)
1349 (eq 'nowarp suggestion))
1350 (gnugo-goto-pos full))
1351 (gnugo--display-suggestion color full))
1352 (gnugo-push-move color full)
1353 (gnugo--finish-move)))))))
1355 (defun gnugo-get-move (color &optional suggestion)
1356 (gnugo-put :waiting (cons color suggestion))
1357 (gnugo--begin-exchange
1358 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1359 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1360 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1361 (concat "reg_genmove " color))
1362 (accept-process-output))
1364 (defun gnugo-cleanup ()
1365 (when (gnugo-board-buffer-p)
1366 (unless (zerop (buffer-size))
1367 (message "Thank you for playing GNU Go."))
1368 (setq gnugo-state nil)))
1370 (defun gnugo-position ()
1371 (or (get-text-property (point) 'gnugo-position)
1372 (user-error "Not a proper position point")))
1374 (defun gnugo-request-suggestion (&optional nowarp)
1375 "Request a move suggestion from GNU Go.
1376 After some time (during which you can do other stuff),
1377 Emacs displays the suggestion in the echo area and warps the
1378 cursor to the suggested position. Prefix arg inhibits warp."
1381 (gnugo--rename-buffer-portion)
1382 (gnugo-get-move (gnugo-current-player)
1387 (defun gnugo--karma (color) ; => BOOL
1388 (when (member color (cdr (gnugo-get :wheel)))
1391 (defsubst gnugo--:karma (role)
1392 (gnugo--karma (gnugo-get role)))
1394 (defun gnugo--assist-state (&optional gate)
1395 (let ((bool (gnugo--:karma :user-color)))
1397 (user-error "Sorry, Assist mode enabled")
1400 (defun gnugo--user-play (pos-or-pass)
1402 ;; The "user" in this func's name used to signify both
1403 ;; who does the action and for whom the action is done.
1404 ;; Now, it signifies only the former.
1405 (let ((color (gnugo-current-player)))
1406 ;; Don't get confused by mixed signals.
1407 (when (gnugo--karma color)
1408 (if (equal color (gnugo-get :one-shot))
1409 (gnugo--forget :one-shot)
1410 (user-error "Sorry, you cannot play for %s at this time"
1412 (gnugo-push-move color pos-or-pass))
1413 (gnugo--finish-move t))
1415 (defun gnugo-move ()
1416 "Make a move on the GNUGO Board buffer.
1417 The position is computed from current point.
1418 Signal error if done out-of-turn or if game-over.
1419 To start a game try M-x gnugo."
1421 (gnugo--user-play (gnugo-position)))
1423 (defun gnugo-mouse-move (e)
1424 "Do `gnugo-move' at mouse location."
1427 (when (memq (following-char) '(?. ?+))
1430 (defun gnugo-pass ()
1431 "Make a pass on the GNUGO Board buffer.
1432 Signal error if done out-of-turn or if game-over.
1433 To start a game try M-x gnugo."
1435 (gnugo--user-play "PASS"))
1437 (defun gnugo-mouse-pass (e)
1438 "Do `gnugo-pass' at mouse location."
1443 (defun gnugo-resign ()
1446 (if (not (y-or-n-p "Resign? "))
1447 (message "(not resigning)")
1448 (gnugo-push-move t "resign")
1451 (defun gnugo-animate-group (w/d)
1452 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1454 (let* ((pos (gnugo-position))
1455 (orig-b-m-p (buffer-modified-p))
1457 (unless (memq (following-char) '(?X ?O))
1458 (user-error "No stone at %s" pos))
1459 (setq blurb (message "Computing %s stones ..." w/d)
1460 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1461 (message "%s %s in group." blurb (length stones))
1462 (setplist (gnugo-f 'anim) nil)
1463 (let* ((spec (if (gnugo-get :display-using-images)
1465 with yin = (get-text-property (point) 'gnugo-yin)
1466 with yang = (gnugo-yang (following-char))
1467 with up = (get (gnugo-yy yin yang t) 'display)
1468 with dn = (get (gnugo-yy yin yang) 'display)
1469 for n below (length gnugo-animation-string)
1470 collect (if (zerop (logand 1 n))
1472 (split-string gnugo-animation-string "" t)))
1474 (ovs (save-excursion
1475 (mapcar (lambda (pos)
1476 (gnugo-goto-pos pos)
1478 (ov (make-overlay p (1+ p))))
1479 (overlay-put ov 'category (gnugo-f 'anim))
1480 (overlay-put ov 'priority most-positive-fixnum)
1483 (setplist (gnugo-f 'anim) (cons 'display cell))
1484 (while (and (cdr spec) ; let last linger lest levity lost
1485 (sit-for 0.08675309)) ; jenny jenny i got your number...
1486 (setcar cell (setq spec (cdr spec)))
1487 ;; Force redisplay of overlays.
1488 (set-buffer-modified-p orig-b-m-p))
1490 (mapc 'delete-overlay ovs)
1493 (defun gnugo-display-group-data (command buffer-name)
1495 (message "Computing %s ..." command)
1496 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1497 (switch-to-buffer buffer-name)
1500 (message "Computing %s ... done." command))
1502 (defun gnugo-worm-stones ()
1503 "In the GNUGO Board buffer, animate \"worm\" at current position.
1504 Signal error if done out-of-turn or if game-over.
1505 See variable `gnugo-animation-string' for customization."
1507 (gnugo-animate-group 'worm))
1509 (defun gnugo-worm-data ()
1510 "Display in another buffer data from \"worm\" at current position.
1511 Signal error if done out-of-turn or if game-over."
1513 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1515 (defun gnugo-dragon-stones ()
1516 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1517 Signal error if done out-of-turn or if game-over.
1518 See variable `gnugo-animation-string' for customization."
1520 (gnugo-animate-group 'dragon))
1522 (defun gnugo-dragon-data ()
1523 "Display in another buffer data from \"dragon\" at current position.
1524 Signal error if done out-of-turn or if game-over."
1526 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1528 (defun gnugo-estimate-score ()
1529 "Display estimated score of a game of GNU Go.
1530 Output includes number of stones on the board and number of stones
1531 captured by each player, and the estimate of who has the advantage (and
1532 by how many stones)."
1534 (message "Est.score ...")
1535 (let ((black (gnugo--count-query "list_stones black"))
1536 (white (gnugo--count-query "list_stones white"))
1537 (black-captures (gnugo-query "captures black"))
1538 (white-captures (gnugo-query "captures white"))
1539 (est (gnugo-query "estimate_score")))
1540 ;; might as well update this
1541 (gnugo-put :black-captures black-captures)
1542 (gnugo-put :white-captures white-captures)
1543 (message "Est.score ... B %s %s | W %s %s | %s"
1544 black black-captures white white-captures est)))
1546 (defun gnugo--ok-file (filename)
1547 (setq default-directory
1548 (file-name-directory
1549 (expand-file-name filename)))
1550 (set-buffer-modified-p nil))
1552 (defun gnugo-write-sgf-file (filename)
1553 "Save the game history to FILENAME (even if unfinished).
1554 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1555 (interactive "FWrite game as SGF file: ")
1556 (when (and (file-exists-p filename)
1557 (not (y-or-n-p "File exists. Continue? ")))
1558 (user-error "Not writing %s" filename))
1559 (when (buffer-modified-p)
1560 ;; take responsibility for our actions
1561 (gnugo--set-root-prop :AP (cons "gnugo.el" gnugo-version)))
1562 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1563 (gnugo--ok-file filename))
1565 (defun gnugo--dance-dance (karma)
1566 (cl-destructuring-bind (dance btw)
1567 (aref [(moshpit " Zombie")
1569 (reverse " Zombie Assist") ; "Assist Zombie"? no thanks! :-D
1570 (stilted " Assist")]
1573 (if (member (gnugo-get prop)
1577 (+ (try 2 :user-color)
1578 (try 1 :gnugo-color))))
1579 (gnugo-put :dance dance) ; pure cruft (for now)
1580 (setq gnugo-btw btw)))
1582 (defun gnugo--who-is-who (wait play samep)
1584 (let ((wheel (gnugo-get :wheel)))
1587 (setcdr wheel (mapcar 'gnugo-other
1589 (message "GNU Go %splays as %s, you as %s (%s)"
1590 (if samep "" "now ")
1593 "NOTE: this is a switch!")))
1595 (defsubst gnugo--nodep (x)
1596 (keywordp (caar x)))
1598 (defun gnugo--SZ! (size)
1599 (gnugo-put :SZ size)
1600 (gnugo-put :center-position
1601 (funcall (gnugo--as-pos-func)
1602 (let ((c (+ -1 ?a (truncate (1+ size) 2))))
1605 (defun gnugo--plant-and-climb (collection &optional sel)
1606 (gnugo-put :sgf-collection collection)
1607 (let ((tree (nth (or sel 0) collection)))
1608 (gnugo-put :sgf-gametree tree)
1609 (gnugo-put :monkey (vector
1611 (aref (gnugo--tree-ends tree) 0)
1616 (defun gnugo-read-sgf-file (filename)
1617 "Load the first game tree from FILENAME, a file in SGF format."
1618 (interactive "fSGF file to load: ")
1619 (when (file-directory-p filename)
1620 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1621 (let (play wait samep coll tree game-over)
1622 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1623 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1624 (setq play (gnugo--q/ue "loadsgf %s" (expand-file-name filename))
1625 wait (gnugo-other play)
1626 samep (string= (gnugo-get :user-color) play))
1627 (gnugo-put :last-mover wait)
1629 (gnugo-put :gnugo-color wait)
1630 (gnugo-put :user-color play))
1631 (setq coll (gnugo/sgf-create filename)
1632 tree (gnugo--plant-and-climb
1633 coll (let ((n (length coll)))
1637 ;; (let* ((q (format "Which game? (1-%d)" n))
1638 ;; (choice (1- (read-number q 1))))
1639 ;; (if (and (< -1 choice) (< choice n))
1641 ;; (message "(Selecting the first game)")
1643 ;; but this is what we use (for now) to accomodate
1644 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1646 (message "(Selecting the first game)"))
1648 ;; This is deliberately undocumented for now.
1649 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1650 (when (setq game-over (or (gnugo--root-prop :RE tree)
1651 (when (equal '("PASS" "PASS")
1652 (gnugo-move-history 'two))
1654 (gnugo-close-game nil game-over))
1655 (gnugo-put :last-user-bpos
1656 (gnugo-move-history 'bpos (gnugo-get :user-color)))
1658 (gnugo--ok-file filename)
1659 (gnugo--who-is-who wait play samep)))
1661 (defun gnugo--mem-with-played-stone (pos &optional noerror)
1662 (let ((color (cl-case (following-char)
1667 (user-error "No stone at %s" pos))
1669 with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
1670 for mem on (aref (gnugo-get :monkey) 0)
1671 when (equal fruit (caar mem))
1673 finally return nil))))
1675 (defun gnugo--climb-towards-root (spec &optional reaction keep)
1677 (gnugo--assist-state t)
1678 (let* ((user-color (gnugo-get :user-color))
1679 (monkey (gnugo-get :monkey))
1680 (tree (gnugo-get :sgf-gametree))
1681 (ends (gnugo--tree-ends tree))
1682 (remorseful (not (gnugo--no-regrets monkey ends)))
1683 (stop (if (numberp spec)
1684 (nthcdr (if (zerop spec)
1685 (if (string= (gnugo-get :last-mover)
1691 (cdr (gnugo--mem-with-played-stone
1694 (gnugo-position)))))))
1695 (when (gnugo-get :game-over)
1696 (gnugo--unclose-game))
1697 (while (and (not (eq stop (aref monkey 0)))
1698 (gnugo--no-worries (gnugo--q "undo")))
1699 (pop (aref monkey 0))
1700 (gnugo-put :last-mover (gnugo-current-player))
1701 (gnugo-merge-showboard-results) ; all
1702 (gnugo-refresh) ; this
1703 (redisplay)) ; eye candy
1704 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1705 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1706 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1708 (gnugo-get :center-position)))
1710 (unless (or keep remorseful)
1711 (aset ends (aref monkey 1) (aref monkey 0)))
1713 (let ((g (gnugo-get :gnugo-color)))
1714 (cl-flet ((turn () (gnugo--turn-the-wheel t)))
1715 (cl-case (or reaction gnugo-undo-reaction)
1717 (play! (let ((wheel (gnugo-get :wheel)))
1718 (cl-letf (((cdr wheel) (cons g (cdr wheel))))
1720 (zombie (gnugo-zombie-mode 1))
1721 (t (gnugo-put :one-shot g)))))))))
1723 (defun gnugo-undo-one-move (&optional me-next)
1724 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1725 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1726 Prefix arg ME-NEXT means to arrange for you to play
1727 the color of the next move (and GNU Go the opposite).
1728 This is useful after loading an SGF file whose last
1729 move was done by the color you prefer to play:
1730 \\[gnugo-read-sgf-file] FILENAME RET
1731 C-u \\[gnugo-undo-one-move]
1733 See also `gnugo-undo-two-moves'."
1737 (let* ((play (gnugo-get :last-mover))
1738 (wait (gnugo-other play))
1739 (samep (string= play (gnugo-get :user-color))))
1740 (gnugo-put :user-color play)
1741 (gnugo-put :gnugo-color wait)
1742 (gnugo--who-is-who wait play samep)))
1743 (gnugo--climb-towards-root 1 (cl-case gnugo-undo-reaction
1744 (zombie gnugo-undo-reaction)
1747 (defun gnugo-undo-two-moves ()
1748 "Undo a pair of moves (GNU Go's and yours).
1749 However, if you are the last mover, undo only one move.
1750 Regardless, after undoing, it is your turn to play again."
1752 (gnugo--climb-towards-root 0))
1754 (defun gnugo-oops (&optional position)
1755 "Like `gnugo-undo-two-moves', but keep the undone moves.
1756 The kept moves become a sub-gametree (variation) when play resumes.
1757 Prefix arg means, instead, undo repeatedly up to and including
1758 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
1760 (gnugo--climb-towards-root (unless position
1764 (defun gnugo-okay (&optional full)
1765 "Redo a pair of undone moves.
1766 Prefix arg means to redo all the undone moves."
1769 (let* ((tree (gnugo-get :sgf-gametree))
1770 (ends (gnugo--tree-ends tree))
1771 (monkey (gnugo-get :monkey)))
1772 (if (gnugo--no-regrets monkey ends)
1773 (message "Oop ack!")
1774 (let* ((as-pos (gnugo--as-pos-func))
1775 (mnum (gnugo--tree-mnum tree))
1776 (mem (aref monkey 0))
1777 (bidx (aref monkey 1))
1778 (end (aref ends bidx))
1779 (ucolor (gnugo-get :user-color))
1780 (uprop (gnugo--prop<-color ucolor)))
1781 (cl-flet ((mvno (node) (gethash node mnum)))
1785 (+ 2 (mvno (car mem))))
1786 with (node move todo)
1790 move (gnugo--move-prop node))
1791 (when (and move (>= ok (mvno node)))
1792 (let ((userp (eq uprop (car move))))
1794 (funcall as-pos (cdr move)))
1796 until (eq mem (cdr ls))
1799 for (userp pos) in todo
1801 (gnugo-push-move userp pos)
1805 (defun gnugo-display-final-score (&optional comment)
1806 "Display final score and other info in another buffer (when game over).
1807 If the game is still ongoing, Emacs asks if you wish to stop play (by
1808 making sure two \"pass\" moves are played consecutively, if necessary).
1809 Also, add the `:RE' SGF property to the root node of the game tree.
1810 Prefix arg COMMENT means to also attach the text (slightly compacted)
1811 to the last move, as a comment."
1813 (let ((game-over (gnugo-get :game-over)))
1814 (unless (or game-over
1815 (and (not (gnugo-get :waiting))
1816 (y-or-n-p "Game still in play. Stop play now? ")))
1817 (user-error "Sorry, game still in play"))
1821 (message "Playing PASS for %s ..."
1822 (gnugo-get (if userp :user-color :gnugo-color)))
1824 (gnugo-push-move userp "PASS")))
1829 (let ((b= " Black = ")
1831 (res (when (gnugo--resignp (gnugo-move-history 'car))
1832 (gnugo-get :last-mover)))
1836 (format "%s wins.\n"
1837 (substring (if (= ?b (aref res 0)) w= b=)
1839 "The game is over.\n"
1840 (format "Resignation by %s.\n" res))
1841 result (concat (upcase (substring (gnugo-other res) 0 1))
1843 (message "Computing final score ...")
1844 (let* ((g-over (gnugo-get :game-over))
1845 (live (cdr (assq 'live g-over)))
1846 (dead (cdr (assq 'dead g-over)))
1847 (seed (gnugo-get :scoring-seed))
1848 (terr-q (format "final_status_list %%s_territory %d" seed))
1851 (b-terr (gnugo--count-query terr-q "black"))
1852 (w-terr (gnugo--count-query terr-q "white"))
1853 (b-capt (string-to-number (gnugo-get :black-captures)))
1854 (w-capt (string-to-number (gnugo-get :white-captures)))
1855 (komi (gnugo--root-prop :KM)))
1856 (setq blurb (list "The game is over. Final score:\n")
1857 result (gnugo-query "final_score %d" seed))
1858 (cond ((string= "Chinese" (gnugo--root-prop :RU))
1859 (dolist (group live)
1860 (cl-incf (if (gnugo--blackp (caar group))
1863 (length (cdr group))))
1864 (dolist (group dead)
1865 (cl-incf (if (gnugo--blackp (caar group))
1868 (length (cdr group))))
1869 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1870 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1871 w-terr terr komi 'komi (+ w-terr komi))
1874 (dolist (group dead)
1875 (cl-incf (if (gnugo--blackp (caar group))
1878 (* 2 (length (cdr group)))))
1879 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1884 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1888 (+ w-terr w-capt komi))
1890 (push (if (string= "0" result)
1891 "The game is a draw.\n"
1892 (format "%s wins by %s.\n"
1893 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1894 (substring result 2)))
1896 (message "Computing final score ... done")))
1898 (let ((beg (gnugo-get :game-start-time))
1899 (end (gnugo-get :game-end-time)))
1903 ((yep (pretty moment)
1904 (push (format-time-string
1905 (concat pretty ": %F %T %z\n")
1908 (yep "Game start" beg)
1910 (setq blurb (apply 'concat (nreverse blurb)))
1911 (gnugo--set-root-prop :RE result)
1913 (let ((node (car (aref (gnugo-get :monkey) 0))))
1915 (delq (assq :C node) node)
1917 (with-temp-buffer ; lame
1919 (when (search-backward "\n\nGame start:" nil t)
1920 (delete-region (point) (point-max)))
1921 (cl-flet ((rep (old new)
1922 (goto-char (point-min))
1923 (while (search-forward old nil t)
1924 (replace-match new))))
1925 (rep "The game is over. " "")
1926 (rep "territory" "T")
1927 (rep "captures" "C")
1930 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
1934 (defun gnugo-quit ()
1935 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
1936 If the game is not over, ask for confirmation first."
1938 (if (or (gnugo-get :game-over)
1939 (y-or-n-p "Quit? "))
1941 (message "(not quitting)")))
1943 (defun gnugo-leave-me-alone ()
1944 "Kill the current buffer unconditionally."
1948 (defun gnugo-fancy-undo (count)
1949 "Rewind the game tree in various ways.
1950 Prefix arg COUNT means to undo that many moves.
1951 Otherwise, undo repeatedly up to and including the move
1952 which placed the stone at point."
1954 (gnugo--climb-towards-root
1959 (define-minor-mode gnugo-image-display-mode
1960 "If enabled, display the board using images.
1961 See function `display-images-p' and variable `gnugo-xpms'."
1963 ((gnugo-get :display-using-images)
1966 (unless (eq bool (gnugo-get :display-using-images))
1967 (gnugo-toggle-image-display)
1968 (save-excursion (gnugo-refresh))))))
1970 (defsubst gnugo--node-with-played-stone (pos &optional noerror)
1971 (car (gnugo--mem-with-played-stone pos noerror)))
1973 (defun gnugo-describe-position ()
1974 "Display the board position under cursor in the echo area.
1975 If there a stone at that position, also display its move number."
1977 (let* ((pos (gnugo-position)) ; do first (can throw)
1978 (node (gnugo--node-with-played-stone pos t)))
1982 (let* ((tree (gnugo-get :sgf-gametree))
1983 (mnum (gnugo--tree-mnum tree))
1984 (move-num (gethash node mnum)))
1985 (format " (move %d)" move-num)))
1988 (defun gnugo-switch-to-another ()
1989 "Switch to another GNU Go game buffer (if any)."
1992 for buf in (cdr (buffer-list))
1993 if (gnugo-board-buffer-p buf)
1996 (switch-to-buffer buf))
1997 finally do (message "(only one)")))
1999 (defun gnugo-comment (node comment)
2000 "Add to NODE a COMMENT (string) property.
2001 Called interactively, NODE is the one corresponding to the
2002 stone at point, and any previous comment is inserted as the
2003 initial-input (see `read-string').
2005 If COMMENT is nil or the empty string, remove the property entirely."
2007 (let* ((pos (gnugo-position))
2008 (node (gnugo--node-with-played-stone pos)))
2010 (read-string (format "Comment for %s: "
2011 (gnugo-describe-position))
2012 (cdr (assq :C node))))))
2013 (setq node (delq (assq :C node) node))
2014 (unless (zerop (length comment))
2015 (gnugo--decorate node :C comment)))
2017 (defun gnugo--struggle (prop updn)
2018 (unless (eq updn (gnugo--:karma prop)) ; drudgery avoidance
2019 (let ((color (gnugo-get prop)))
2024 (let ((waiting (gnugo-get :waiting)))
2025 (when (and waiting (string= color (car waiting)))
2026 (gnugo--rename-buffer-portion)
2028 ;; heuristic: Warp only if it appears
2029 ;; that the user is "following along".
2031 (string= (gnugo-position)
2032 (gnugo-move-history 'bpos color)))
2034 (gnugo--display-suggestion color "forthcoming")
2036 (let* ((wheel (gnugo-get :wheel))
2038 (karma (cdr wheel)))
2039 (when (timerp timer)
2040 (cancel-timer timer))
2042 (setcdr wheel (setq karma
2043 ;; walk to the west, fly to the east,
2044 ;; talk and then rest, cry and then feast.
2045 ;; 99 beers down thirsty throats sloshed?
2046 ;; 500 years under pink mountains squashed?
2047 ;; balk with the best, child now re-creased!
2050 (delete color karma))))
2051 (gnugo--dance-dance karma))
2052 (gnugo--turn-the-wheel t))))
2054 (define-minor-mode gnugo-assist-mode
2055 "If enabled (\"Assist\" in mode line), GNU Go plays for you.
2056 When disabling, if GNU Go has already started thinking of
2057 a move to play for you, the thinking is not cancelled but instead
2058 transformed into a move suggestion (see `gnugo-request-suggestion')."
2060 ((gnugo--assist-state)
2063 (gnugo--struggle :user-color bool))))
2065 (define-minor-mode gnugo-zombie-mode
2066 "If enabled (\"Zombie\" in mode line), GNU Go lets you play for it.
2067 When disabling, if GNU Go has already started thinking of
2068 a move to play, the thinking is not cancelled but instead
2069 transformed into a move suggestion (see `gnugo-request-suggestion')."
2071 ((not (gnugo--:karma :gnugo-color))
2074 (gnugo--struggle :gnugo-color (not bool)))))
2076 ;;;---------------------------------------------------------------------------
2077 ;;; Command properties and gnugo-command
2079 ;; GTP commands entered by the user are never issued directly to GNU Go;
2080 ;; instead, their behavior and output are controlled by the property
2081 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2082 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2084 ;; :full -- completely interpret the command string; the value is a
2085 ;; func that takes the list of words derived from splitting the
2086 ;; command string (minus the command) and handles everything.
2088 ;; :output -- either a keyword specifying the preferred output method:
2089 ;; :message -- show output in minibuffer
2090 ;; :discard -- sometimes you just don't care;
2091 ;; or a function that takes one arg, the output string, and
2092 ;; handles it completely. default is to switch to buffer
2093 ;; "*gnugo command output*" if the output has a newline,
2094 ;; otherwise use `message'.
2096 ;; :post-thunk -- run after output processing (at the very end).
2098 (defun gnugo-command (command)
2099 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2100 Output and Emacs behavior depend on which command is given (some
2101 commands are handled completely by Emacs w/o using the subprocess;
2102 some commands have their output displayed in specially prepared
2103 buffers or in the echo area; some commands are instrumented to do
2104 gnugo.el-specific housekeeping).
2106 For example, for the command \"help\", Emacs visits the
2107 GTP command reference info page.
2109 NOTE: At this time, GTP command handling specification is still
2110 incomplete. Thus, some commands WILL confuse gnugo.el."
2111 (interactive "sCommand: ")
2112 (if (string= "" command)
2113 (message "(no command given)")
2114 (let* ((split (split-string command))
2115 (cmd (intern (car split)))
2116 (spec (get cmd :gnugo-gtp-command-spec))
2117 (full (plist-get spec :full)))
2119 (funcall full (cdr split))
2120 (message "Doing %s ..." command)
2121 (let* ((ans (gnugo--q command))
2122 (where (plist-get spec :output)))
2123 (if (string-match "unknown.command" ans)
2125 (cond ((functionp where) (funcall where ans))
2126 ((eq :discard where) (message ""))
2127 ((or (eq :message where)
2128 (not (string-match "\n" ans)))
2130 (t (switch-to-buffer "*gnugo command output*")
2133 (message "Doing %s ... done." command)))
2134 (let ((thunk (plist-get spec :post-thunk)))
2135 (when thunk (funcall thunk)))))))))
2137 ;;;---------------------------------------------------------------------------
2138 ;;; Major mode for interacting with a GNUGO subprocess
2140 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2141 "Major mode for playing GNU Go.
2142 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2143 In this mode, keys do not self insert."
2144 (buffer-disable-undo) ; todo: undo undo undoing
2145 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2147 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2148 (set (make-local-variable 'gnugo-state)
2149 (gnugo--mkht :size (1- 42)))
2150 (set (make-local-variable 'gnugo-btw) nil)
2151 (add-to-list 'minor-mode-alist '(gnugo-btw gnugo-btw))
2152 (gnugo-put :highlight-last-move-spec
2153 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2154 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2155 (let ((ov (make-overlay 1 1)))
2156 (overlay-put ov 'display ")")
2158 (gnugo-put :mul '(1 . 1))
2159 (gnugo-put :obarray (make-vector 31 nil))
2160 (add-to-invisibility-spec :nogrid))
2162 ;;;---------------------------------------------------------------------------
2166 (defun gnugo (&optional new-game)
2167 "Run gnugo in a buffer, or resume a game in progress.
2168 If there is already a game in progress you may resume it instead
2169 of starting a new one. Prefix arg means skip the game-in-progress
2170 check and start a new game straight away.
2172 Before starting, Emacs queries you for additional command-line
2173 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2175 Note that specifying \"--infile FILENAME\" (or, \"-l FILENAME\")
2176 silently clobbers certain other options, such as \"--color\".
2177 For details, see info node `(gnugo) Invoking GNU Go'.
2179 \\<gnugo-board-mode-map>
2180 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2181 See `gnugo-board-mode' for a full list of commands."
2183 (let* ((all (let (acc)
2184 (dolist (buf (buffer-list))
2185 (when (gnugo-board-buffer-p buf)
2186 (push (cons (buffer-name buf) buf) acc)))
2189 (if (and (not new-game)
2191 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2192 (if (= 1 n) "" "s"))))
2197 (let ((sel (completing-read "Which one? " all nil t)))
2198 (if (string= "" sel)
2200 (assoc sel all))))))
2202 (unless (executable-find gnugo-program)
2203 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2204 ;; set up a new board
2205 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2207 (let* ((filename nil)
2208 (user-color "black")
2210 with ls = (split-string
2211 ;; todo: grok ‘gnugo --help’; completion
2214 (car gnugo-option-history)
2215 'gnugo-option-history))
2218 (let ((arg (pop ls)))
2222 (warn "%s %s ignored" opt fn)
2223 (setq filename fn))))
2225 ((string= "--color" arg)
2228 ;; Unfortunately, GTP does not provide
2229 ;; a way to query the user color, so
2230 ;; we must resort to this weirdness.
2234 ((string= "--infile" arg)
2235 (ex "--infile" (pop ls)))
2236 ((string-match "^-l" arg)
2237 (ex "-l" (if (< 2 (length arg))
2240 (t (push arg ok)))))
2241 finally return (nreverse ok)))
2242 (proc (apply 'start-process "gnugo"
2245 "--mode" "gtp" "--quiet"
2247 root board-size handicap komi)
2248 (gnugo-put :user-color user-color)
2249 (gnugo-put :proc proc)
2250 (set-process-sentinel proc 'gnugo-sentinel)
2251 ;; Emacs is too protective sometimes, blech.
2252 (set-process-query-on-exit-flag proc nil)
2253 (gnugo-put :diamond (substring (process-name proc) 5))
2254 (gnugo-put :gnugo-color (gnugo-other user-color))
2256 (gnugo-read-sgf-file (expand-file-name filename))
2258 ((r! (&rest plist) (apply 'gnugo--decorate root plist)))
2260 (setq root (gnugo--root-node
2261 (gnugo--plant-and-climb
2262 (gnugo/sgf-create "(;FF[4]GM[1])" t)))
2263 komi (gnugo--nquery "get_komi")
2264 handicap (gnugo--nquery "get_handicap")
2265 board-size (gnugo--nquery "query_boardsize")))
2266 ;; Work around a GNU Go 3.8 (and possibly earlier/later)
2267 ;; bug whereby GTP command ‘get_handicap’ fails to return
2268 ;; the N set by ‘--handicap N’ on the command line.
2269 (let ((actually (member "--handicap" args)))
2270 ;; Checking ‘(zerop handicap)’ first is not strictly
2271 ;; necessary; it represents a hope that some day GNU Go
2272 ;; will DTRT (or provide rationale for this weird behavior)
2273 ;; and become worthy of our trust.
2274 (when (and (zerop handicap) actually)
2275 (setq handicap (string-to-number (cadr actually)))))
2277 :DT (format-time-string "%F")
2278 :RU (if (member "--chinese-rules" args)
2282 (let ((ub (gnugo--blackp user-color)))
2283 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2284 (if ub :PB :PW) (user-full-name)))
2285 (unless (zerop handicap)
2287 :AB (mapcar (gnugo--as-cc-func)
2288 (gnugo-lsquery "fixed_handicap %d"
2290 (gnugo-put :waiting-start (current-time))
2292 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2293 (gnugo-get :center-position)))
2295 (gnugo-put :game-start-time (current-time))
2296 (let ((g (gnugo-get :gnugo-color))
2297 (n (or (gnugo--root-prop :HA) 0))
2298 (u (gnugo-get :user-color)))
2299 (unless (gnugo-get :last-mover)
2300 (gnugo-put :last-mover
2301 (if (or (and (gnugo--blackp u) (< 1 n))
2302 (and (gnugo--blackp g) (< n 2)))
2305 (let ((karma (list g)))
2306 (gnugo-put :wheel (cons nil karma))
2307 (gnugo--dance-dance karma))
2308 (run-hooks 'gnugo-start-game-hook)
2309 (gnugo--turn-the-wheel)))))
2311 ;;;---------------------------------------------------------------------------
2312 ;;; Load-time actions
2314 (unless (get 'help :gnugo-gtp-command-spec)
2316 ((sget (x) (get x :gnugo-gtp-command-spec))
2317 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2318 (plist-put (sget cmd) prop val)))
2319 (validpos (s &optional go)
2320 (let ((pos (upcase s)))
2322 with size = (gnugo-get :SZ)
2323 for c across (funcall (gnugo--as-cc-func)
2325 do (let ((norm (- c ?a)))
2326 (unless (and (< -1 norm)
2328 (user-error "Invalid position: %s"
2331 (gnugo-goto-pos pos))
2333 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2336 (jam cmd (car ls) (cadr ls))
2337 (setq ls (cddr ls)))))))
2338 (cl-macrolet ((deffull (who &body body)
2339 (declare (indent 1))
2340 `(defgtp ',who :full (lambda (sel)
2344 (info "(gnugo)GTP command reference")
2345 (when sel (setq sel (intern (car sel))))
2346 (let (buffer-read-only pad cur spec output found)
2348 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2349 (goto-char (point-min))
2351 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2354 (setq pad (make-string (- (match-beginning 1)
2355 (match-beginning 0))
2359 (get (setq cur (intern (match-string 1)))
2360 :gnugo-gtp-command-spec))
2362 (note "handles this command completely"))
2363 (when (setq output (plist-get spec :output))
2364 (if (functionp output)
2365 (note "handles the output specially")
2367 (:discard (note "discards the output"))
2368 (:message (note "displays the output in the echo area")))))
2370 (setq found (make-marker))
2371 (set-marker found (match-beginning 0))))))
2372 (cond (found (goto-char found) (set-marker found nil))
2374 (t (message "(no such command: %s)" sel)))))
2376 (deffull final_score
2377 ;; Explicit ignorance avoids byte-compiler warning.
2379 (gnugo-display-final-score))
2385 :post-thunk (lambda ()
2386 (gnugo--unclose-game)
2387 (gnugo--forget :last-mover)
2389 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2393 (gnugo-read-sgf-file (car sel)))
2395 (deffull (undo gg-undo)
2396 (gnugo--climb-towards-root
2399 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2400 (t (validpos (car sel) t)))))))))
2405 ;;;---------------------------------------------------------------------------
2406 ;;; The remainder of this file defines a simplified SGF-handling library.
2407 ;;; When/if it should start to attain generality, it should be split off into
2408 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2409 ;;; "gnugo/" prefix.
2411 (defconst gnugo/sgf-*r4-properties*
2412 '((AB "Add Black" setup list stone)
2413 (AE "Add Empty" game list point)
2414 (AN "Annotation" game simpletext)
2415 (AP "Application" root (simpletext . simpletext))
2416 (AR "Arrow" - list (point . point))
2417 (AS "Who adds stones" - simpletext) ; (LOA)
2418 (AW "Add White" setup list stone)
2419 (B "Black" move move)
2420 (BL "Black time left" move real)
2421 (BM "Bad move" move double)
2422 (BR "Black rank" game simpletext)
2423 (BT "Black team" game simpletext)
2424 (C "Comment" - text)
2425 (CA "Charset" root simpletext)
2426 (CP "Copyright" game simpletext)
2427 (CR "Circle" - list point)
2428 (DD "Dim points" - elist point) ; (inherit)
2429 (DM "Even position" - double)
2430 (DO "Doubtful" move none)
2431 (DT "Date" game simpletext)
2432 (EV "Event" game simpletext)
2433 (FF "Fileformat" root [number (1 . 4)])
2434 (FG "Figure" - (or none (number . simpletext)))
2435 (GB "Good for Black" - double)
2436 (GC "Game comment" game text)
2437 (GM "Game" root [number (1 . 20)])
2438 (GN "Game name" game simpletext)
2439 (GW "Good for White" - double)
2440 (HA "Handicap" game number) ; (Go)
2441 (HO "Hotspot" - double)
2442 (IP "Initial pos." game simpletext) ; (LOA)
2443 (IT "Interesting" move none)
2444 (IY "Invert Y-axis" game simpletext) ; (LOA)
2445 (KM "Komi" game real) ; (Go)
2447 (LB "Label" - list (point . simpletext))
2448 (LN "Line" - list (point . point))
2449 (MA "Mark" - list point)
2450 (MN "set move number" move number)
2451 (N "Nodename" - simpletext)
2452 (OB "OtStones Black" move number)
2453 (ON "Opening" game text)
2454 (OT "Overtime" game simpletext)
2455 (OW "OtStones White" move number)
2456 (PB "Player Black" game simpletext)
2457 (PC "Place" game simpletext)
2458 (PL "Player to play" setup color)
2459 (PM "Print move mode" - number) ; (inherit)
2460 (PW "Player White" game simpletext)
2461 (RE "Result" game simpletext)
2462 (RO "Round" game simpletext)
2463 (RU "Rules" game simpletext)
2464 (SE "Markup" - point) ; (LOA)
2465 (SL "Selected" - list point)
2466 (SO "Source" game simpletext)
2467 (SQ "Square" - list point)
2468 (ST "Style" root [number (0 . 3)])
2469 (SU "Setup type" game simpletext) ; (LOA)
2470 (SZ "Size" root (or number (number . number)))
2471 (TB "Territory Black" - elist point) ; (Go)
2472 (TE "Tesuji" move double)
2473 (TM "Timelimit" game real)
2474 (TR "Triangle" - list point)
2475 (TW "Territory White" - elist point) ; (Go)
2476 (UC "Unclear pos" - double)
2477 (US "User" game simpletext)
2479 (VW "View" - elist point) ; (inherit)
2480 (W "White" move move)
2481 (WL "White time left" move real)
2482 (WR "White rank" game simpletext)
2483 (WT "White team" game simpletext)
2484 (LT "Lose on time" setup simpletext))
2485 ;; r4-specific notes
2486 ;; - changed: DT FG LB RE RU SZ
2487 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2488 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2490 (defun gnugo/sgf-create (file-or-data &optional data-p)
2491 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2492 FILE-OR-DATA is a file name or SGF[4] data.
2493 Optional arg DATA-P non-nil means FILE-OR-DATA is
2494 a string containing SGF[4] data.
2495 A collection is a list of gametrees, each a vector of four elements:
2497 ENDS -- a vector of node lists, with shared tails
2498 (last element of all the lists is the root node)
2500 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2501 have a move number of the previous \"move\" node (or zero)
2503 ROOT -- the root node"
2504 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2505 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2506 (put 'gnugo/sgf-*r4-properties* :keywords
2507 (mapcar (lambda (full)
2509 (intern (format ":%s" (car full)))))
2510 gnugo/sgf-*r4-properties*))))
2511 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2512 (put 'gnugo/sgf-*r4-properties* :specs
2513 (mapcar (lambda (full)
2514 (cons (car full) (cl-cdddr full)))
2515 gnugo/sgf-*r4-properties*))))
2518 ((sw () (skip-chars-forward " \t\n"))
2519 (x (end preserve-whitespace)
2522 (:end (lambda (char) (= ?\] char)))
2523 (:mid (lambda (char) (= ?\: char)))
2524 (t (lambda (char) (or (= ?\: char)
2527 (while (not (funcall endp (setq c (following-char))))
2533 ((unless preserve-whitespace
2534 (looking-at "\\s-+"))
2535 (delete-region (point) (match-end 0))
2537 (t (forward-char 1))))
2538 (buffer-substring-no-properties beg (point))))
2539 (one (type end) (let ((s (progn
2541 (x end (eq 'text type)))))
2544 ;; blech, begone bu"tt"-ugly blatherings
2545 ;; (but bide brobdingnagian boards)...
2546 (if (and (string= "tt" s)
2551 ((simpletext color) s)
2552 ((number real double) (string-to-number s))
2555 (t (error "Unhandled type: %S" type)))))
2556 (val (spec) (cond ((symbolp spec)
2559 ;; todo: check range here.
2560 (one (aref spec 0) :end))
2561 ((eq 'or (car spec))
2562 (let ((v (one (cadr spec) t)))
2563 (if (= ?\] (following-char))
2566 ;; todo: this assumes `spec' has the form
2567 ;; (or foo (foo . bar))
2568 ;; i.e., foo is not rescanned. e.g., `SZ'.
2569 ;; probably this assumption is consistent
2570 ;; w/ the SGF authors' desire to make the
2571 ;; parsing easy, but you never know...
2572 (cons v (one (cl-cdaddr spec) :end)))))
2573 (t (cons (one (car spec) :mid)
2574 (one (cdr spec) :end)))))
2575 (short (who) (when (eobp)
2576 (error "Unexpected EOF while reading %s" who)))
2577 (atvalp () (= ?\[ (following-char)))
2578 (PROP () (let (name spec ltype)
2579 (sw) (short 'property)
2580 (when (looking-at "[A-Z]")
2581 (setq name (read (current-buffer))
2582 spec (cdr (assq name specs)))
2585 (cdr (assq name keywords))
2586 (prog1 (if (= 1 (length spec))
2588 (unless (memq (setq ltype (car spec))
2590 (error "Bad spec: %S" spec))
2591 (if (and (eq 'elist ltype) (sw)
2594 (let ((type (cadr spec))
2596 (while (and (sw) (atvalp)
2597 (setq mo (val type)))
2602 (forward-char 1))))))
2603 (morep () (and (sw) (not (eobp))))
2604 (seek (c) (and (morep) (= c (following-char))))
2605 (seek-into (c) (when (seek c)
2608 (NODE () (when (seek-into ?\;)
2611 while (setq prop (PROP))
2613 (when (eq :SZ (car prop))
2614 (setq SZ (cdr prop)))
2623 (puthash node (+ (if (gnugo--move-prop node)
2626 (gethash prev mnum 0))
2631 (if (not (seek ?\())
2637 append (TREE ls mnum)))
2641 (insert-file-contents file-or-data)
2642 (insert file-or-data)
2643 (goto-char (point-min)))
2646 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2647 (ends (TREE nil mnum))
2648 (root (car (last (car ends)))))
2649 (vector (apply 'vector ends)
2653 (defun gnugo/sgf-write-file (collection filename)
2654 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2655 (specs (mapcar (lambda (full)
2656 (cons (intern (format ":%s" (car full)))
2658 gnugo/sgf-*r4-properties*))
2661 ((esc (composed fmt arg)
2662 (mapconcat (lambda (c)
2664 ;; ‘?\[’ is not strictly required
2665 ;; but neither is it forbidden.
2666 ((?\[ ?\] ?\\) (format "\\%c" c))
2667 (?: (concat (if composed "\\" "") ":"))
2669 (string-to-list (format fmt arg))
2671 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2672 (>>two (v) (insert "["
2673 (esc t "%s" (car v))
2675 (esc t "%s" (cdr v))
2677 (>>nl () (cond ((memq name aft-newline-appreciated)
2679 ((< 60 (current-column))
2687 (insert (substring (symbol-name name) 1))
2690 (setq spec (cdr (assq name specs)))
2694 (let ((>> (if (consp (cadr spec))
2697 (dolist (little-v v)
2699 (funcall >> little-v)
2707 initially (insert ";")
2711 (unless (zerop (current-column))
2715 (funcall (if (gnugo--nodep x)
2721 (dolist (tree collection)
2723 (let ((ht (gnugo--mkht))
2724 (leaves (append (gnugo--tree-ends tree) nil)))
2728 with rh ; rectified history
2729 with bp ; branch point
2731 until (setq bp (gethash node ht))
2733 (push node rh) ; good for now: ½τ
2737 ;; first run: main line
2739 ;; subsequent runs: grafts (value discarded)
2741 ;; Maintain order of ‘leaves’.
2742 (let ((was (cdr bp)))
2743 (if (gnugo--nodep (car was))
2747 (setq tree (hang (pop leaves)))
2748 (mapc #'hang leaves)
2751 (write-file filename)))))
2753 ;;; gnugo.el ends here