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
11 ;; This program is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; This program is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
29 ;; This file provides the command `gnugo' which allows you to play the game of
30 ;; go against the external program "gnugo" (http://www.gnu.org/software/gnugo)
31 ;; in a dedicated Emacs buffer, or to resume a game in progress. NOTE: In
32 ;; this file, to avoid confusion w/ elisp vars and funcs, we use the term "GNU
33 ;; Go" to refer to the process object created by running the external program.
35 ;; At the start of a new game, you can pass additional command-line arguments
36 ;; to GNU Go to specify level, board size, color, komi, handicap, etc. By
37 ;; default GNU Go plays at level 10, board size 19, color white, and zero for
38 ;; both komi and handicap.
40 ;; To play a stone, move the cursor to the desired vertice and type `SPC' or
41 ;; `RET'; to pass, `P' (note: uppercase); to quit, `q'; to undo one of your
42 ;; moves (as well as a possibly intervening move by GNU Go), `u'. To undo
43 ;; back through an arbitrary stone that you played, place the cursor on a
44 ;; stone and type `U' (note: uppercase).
46 ;; There are a great many other commands. Other keybindings are described in
47 ;; the `gnugo-board-mode' documentation, which you may view with the command
48 ;; `describe-mode' (normally `C-h m') in that buffer. The buffer name shows
49 ;; the last move and who is currently to play. Capture counts and other info
50 ;; are shown on the mode line immediately following the major mode name.
52 ;; While GNU Go is pondering its next move, certain commands that rely on its
53 ;; assistence will result in a "still waiting" error. Do not be alarmed; that
54 ;; is normal. When it is your turn again you may retry the command. In the
55 ;; meantime, you can use Emacs for other tasks, or start an entirely new game
56 ;; with `C-u M-x gnugo'. (NOTE: A new game will slow down all games. :-)
58 ;; If GNU Go should crash during a game the mode line will show "no process".
59 ;; Please report the event to the GNU Go maintainers so that they can improve
63 ;; Meta-Playing (aka Customizing)
64 ;; ------------------------------
66 ;; Customization is presently limited to
67 ;; vars: `gnugo-program'
68 ;; `gnugo-animation-string'
70 ;; `gnugo-X-face' `gnugo-O-face' `gnugo-grid-face'
71 ;; `gnugo-undo-reaction'
72 ;; `gnugo-xpms' (see also gnugo-imgen.el)
73 ;; normal hooks: `gnugo-board-mode-hook'
74 ;; `gnugo-frolic-mode-hook'
75 ;; `gnugo-start-game-hook'
76 ;; `gnugo-post-move-hook'
77 ;; and the keymaps: `gnugo-board-mode-map'
78 ;; `gnugo-frolic-mode-map'
81 ;; Meta-Meta-Playing (aka Hacking)
82 ;; -------------------------------
84 ;; <http://git.sv.gnu.org/cgit/emacs/elpa.git/tree/packages/gnugo/HACKING>
90 ;; <http://www.gnuvola.org/software/gnugo/>
94 (require 'cl-lib) ; use the source luke!
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
116 ;; Re <http://lists.gnu.org/archive/html/emacs-devel/2014-04/msg00123.html>,
117 ;; ideally we could ‘defvar’ here w/o value and also ‘defvar’ below
118 ;; in "load-time actions" w/ value and docstring, to avoid this ugly
119 ;; (from the forward references) block early in the file. Unfortunately,
120 ;; byte-compiling such a split formulation results in the initial ‘defvar’
121 ;; being replaced by:
122 ;; (defvar VAR (make-sparse-keymap))
123 ;; and the second ‘defvar’ is ignored on load. At least, this is the case
124 ;; for Emacs built from repo (trunk) 2014-05-27. --ttn
125 (let ((map (make-sparse-keymap)))
126 (suppress-keymap map)
128 (define-key map (car pair) (cdr pair)))
129 '(("?" . describe-mode)
130 ("S" . gnugo-request-suggestion)
131 ("\C-m" . gnugo-move)
136 ("Q" . gnugo-leave-me-alone)
137 ("U" . gnugo-fancy-undo)
138 ("\M-u" . gnugo-undo-one-move)
139 ("u" . gnugo-undo-two-moves)
140 ("\C-?" . gnugo-undo-two-moves)
143 ("\C-l" . gnugo-refresh)
144 ("\M-_" . gnugo-boss-is-near)
145 ("_" . gnugo-boss-is-near)
146 ("h" . gnugo-move-history)
147 ("L" . gnugo-frolic-in-the-leaves)
148 ("\C-c\C-l" . gnugo-frolic-in-the-leaves)
149 ("i" . gnugo-image-display-mode)
150 ("w" . gnugo-worm-stones)
151 ("W" . gnugo-worm-data)
152 ("d" . gnugo-dragon-stones)
153 ("D" . gnugo-dragon-data)
154 ("g" . gnugo-grid-mode)
155 ("!" . gnugo-estimate-score)
156 (":" . gnugo-command)
157 (";" . gnugo-command)
158 ("=" . gnugo-describe-position)
159 ("s" . gnugo-write-sgf-file)
160 ("\C-x\C-s" . gnugo-write-sgf-file)
161 ("\C-x\C-w" . gnugo-write-sgf-file)
162 ("l" . gnugo-read-sgf-file)
163 ("F" . gnugo-display-final-score)
164 ("A" . gnugo-switch-to-another)
165 ("C" . gnugo-comment)
166 ("\C-c\C-a" . gnugo-assist-mode)
167 ("\C-c\C-z" . gnugo-zombie-mode)
169 ([(down-mouse-1)] . gnugo-mouse-move)
170 ([(down-mouse-2)] . gnugo-mouse-move) ; mitigate accidents
171 ([(down-mouse-3)] . gnugo-mouse-pass)
172 ;; delving into the curiosities
173 ("\C-c\C-p" . gnugo-describe-internal-properties)))
175 "Keymap for GNUGO Board mode.")
177 (defvar gnugo-board-mode-hook nil
178 "Hook run when entering GNUGO Board mode.")
180 (defvar gnugo-start-game-hook nil
181 "Normal hook run immediately before the first move of the game.
182 To find out who is to move first, use `gnugo-current-player'.
183 See also `gnugo-board-mode'.")
185 (defvar gnugo-post-move-hook nil
186 "Normal hook run after a move and before the board is refreshed.
187 Initially, when `run-hooks' is called, the current buffer is the GNUGO
188 Board buffer of the game. Hook functions that switch buffers must take
189 care not to call (directly or indirectly through some other function)
190 `gnugo-put' or `gnugo-get' after the switch.")
192 (defvar gnugo-animation-string
193 (let ((jam "*#") (blink " #") (spin "-\\|/") (yada "*-*!"))
194 (concat jam jam jam jam jam
195 ;; "SECRET MESSAGE HERE"
196 blink blink blink blink blink blink blink blink
197 ;; Playing go is like fighting ignorance: when you think you have
198 ;; surrounded something by knowing it very well it often turns
199 ;; out that in the time you spent deepening this understanding,
200 ;; other areas of ignorance have surrounded you.
201 spin spin spin spin spin spin spin spin spin
202 ;; Playing go is not like fighting ignorance: what one person
203 ;; knows many people may come to know; knowledge does not build
204 ;; solely move by move. Wisdom, on the other hand...
206 "String whose individual characters are used for animation.
207 Specifically, the commands `gnugo-worm-stones' and `gnugo-dragon-stones'
208 render the stones in their respective result groups as the first character
209 in the string, then the next, and so on.")
211 (defvar gnugo-mode-line "~b ~w :~m :~u"
212 "A `mode-line-format'-compliant value for GNUGO Board mode.
213 If a single string, the following special escape sequences are
214 replaced with their associated information:
215 ~b,~w black,white captures (a number)
216 ~p current player (black or white)
218 ~t time waiting for the current move
219 ~u time taken for the Ultimate (most recent) move
220 The times are in seconds, or \"-\" if that information is not available.
221 For ~t, the value is a snapshot, use `gnugo-refresh' to update it.")
223 (defvar gnugo-X-face 'font-lock-string-face
224 "Name of face to use for X (black) stones.")
226 (defvar gnugo-O-face 'font-lock-builtin-face
227 "Name of face to use for O (white) stones.")
229 (defvar gnugo-grid-face 'default
230 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
232 (defvar gnugo-undo-reaction 'play!
233 "What to do if undo (or oops) leaves GNU Go to play.
234 After `gnugo-undo-one-move', `gnugo-undo-two-moves' or `gnugo-oops',
235 when GNU Go is to play, this can be a symbol:
236 play -- make GNU Go play (unless in Zombie mode)
237 play! -- make GNU Go play unconditionally (traditional behavior)
238 zombie -- enable Zombie mode (`gnugo-zombie-mode')
239 one-shot -- like `zombie' but valid only for the next move
240 Any other value, or (as a special case) for `gnugo-undo-one-move',
241 any value other than `zombie', is taken as `one-shot'. Note that
242 making GNU Go play will probably result in the recently-liberated
243 board position becoming re-occupied.")
245 (defvar gnugo-xpms nil
246 "List of 46 ((TYPE . LOCATION) . XPM-IMAGE) forms.
247 XPM-IMAGE is an image as returned by `create-image' with
248 inline data (i.e., property :data with string value).
250 TYPE is a symbol, one of:
251 hoshi -- unoccupied position with dot
252 empty -- unoccupied position sans dot
253 bpmoku, bmoku -- black stone with and sans highlight point
254 wpmoku, wmoku -- white stone with and sans highlight point
256 LOCATION is an integer encoding edge, corner, or center:
260 For instance, 4 means \"left edge\", 9 means \"bottom right\".
262 There is only one location for hoshi: center. The other five
263 types each have all possible locations. So (+ 1 (* 9 5)) => 46.
265 The value can also be a function (satisfying `functionp') that
266 takes one arg, the size of the board, and returns the appropriate
269 ;;;---------------------------------------------------------------------------
270 ;;; Variables for the inquisitive programmer
272 (defconst gnugo-font-lock-keywords
273 '(("X" . gnugo-X-face)
274 ("O" . gnugo-O-face))
275 "Font lock keywords for `gnugo-board-mode'.")
277 (defvar gnugo-option-history nil)
279 (defvar gnugo-state nil) ; hint: C-c C-p
281 (defvar gnugo-btw nil)
283 ;;;---------------------------------------------------------------------------
284 ;;; Support functions
286 (defsubst gnugo--mkht (&rest etc)
287 (apply 'make-hash-table :test 'eq etc))
289 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
290 (compare-strings s1 beg1 nil s2 beg2 nil))
292 (defun gnugo-put (key value)
293 "Associate move/game/board-specific property KEY with VALUE.
295 There are many properties, each named by a keyword, that record and control
296 how gnugo.el manages each game. Each GNUGO Board buffer has its own set
297 of properties, stored in the hash table `gnugo-state'. Here we document
298 some of the more stable properties. You may wish to use them as part of
299 a `gnugo-post-move-hook' function, for example. Be careful to preserve
300 the current buffer as `gnugo-state' is made into a buffer-local variable.
301 NOTE: In the following, \"see foo\" actually means \"see foo source or
302 you may never really understand to any degree of personal satisfaction\".
304 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
306 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
308 :game-over -- nil until game over at which time its value is set to
309 the alist `((live GROUP ...) (dead GROUP ...))'
311 :sgf-collection -- after a `loadsgf' command, entire parse tree of file,
312 a simple list of one or more gametrees, updated in
313 conjunction w/ :sgf-gametree and :monkey
315 :sgf-gametree -- one of the gametrees in :sgf-collection
317 :monkey -- vector of two elements:
318 MEM, a pointer to one of the branches in the gametree;
319 BIDX, the index of the \"current branch\"
321 :gnugo-color -- either \"black\" or \"white\"
325 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
328 :black-captures -- these are strings since gnugo.el doesn't do anything
329 :white-captures w/ the information besides display it in the mode line;
330 gory details in functions `gnugo-propertize-board-buffer'
331 and `gnugo-merge-showboard-results' (almost more effort
332 than they are worth!)
334 :display-using-images -- XPMs, to be precise; see functions `gnugo-yy',
335 `gnugo-toggle-image-display' and `gnugo-refresh',
336 as well as gnugo-xpms.el (available elsewhere)
338 :all-yy -- list of 46 symbols used as the `category' text property
339 (so that their plists, typically w/ property `display' or
340 `do-not-display') are consulted by the Emacs display engine;
341 46 = 9 places * (4 moku + 1 empty) + 1 hoshi; see functions
342 `gnugo-toggle-image-display', `gnugo-yy' and `gnugo-yang'
344 :paren-ov -- a pair (left and right) of overlays shuffled about to indicate
345 the last move; only one is used when displaying using images
347 :last-user-bpos -- board position; keep the hapless human happy
349 As things stabilize probably more info will be added to this docstring."
351 (puthash key value gnugo-state))
353 (defun gnugo-get (key)
354 "Return the move/game/board-specific value for KEY.
356 (gethash key gnugo-state))
358 (defun gnugo--forget (&rest keys)
360 (remhash key gnugo-state)))
362 (defsubst gnugo--tree-mnum (tree)
365 (defsubst gnugo--tree-ends (tree)
368 (defsubst gnugo--set-tree-ends (tree ls)
369 (aset tree 0 (apply 'vector ls))
370 (gnugo--tree-ends tree))
372 (defun gnugo--root-node (&optional tree)
373 (aref (or tree (gnugo-get :sgf-gametree))
376 (defun gnugo-describe-internal-properties ()
377 "Pretty-print `gnugo-state' properties in another buffer.
378 Handle the big, slow-to-render, and/or uninteresting ones specially."
380 (let ((buf (current-buffer))
381 (d (gnugo-get :diamond))
383 for key being the hash-keys of gnugo-state
384 using (hash-values val)
388 (format "hash: %X (%d images)"
394 (list (hash-table-count
395 (gnugo--tree-mnum val))
396 (gnugo--root-node val)
397 (gnugo--tree-ends val)))
399 (let ((mem (aref val 0)))
403 (switch-to-buffer (get-buffer-create
404 (format "%s*GNUGO Board Properties*"
408 (setq truncate-lines t)
412 (goto-char (point-min))
413 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
417 (while (re-search-forward rx nil t)
418 (let ((pos (get-text-property (string-to-number (match-string 1))
419 'gnugo-position buf)))
420 (delete-region (+ 2 (match-beginning 0)) (point))
421 (insert (format " %S" pos))))))
422 (message "%d properties" (length acc))))
424 (defun gnugo-board-buffer-p (&optional buffer)
425 "Return non-nil if BUFFER is a GNUGO Board buffer."
426 (eq 'gnugo-board-mode
429 (or buffer (current-buffer)))))
431 (defun gnugo-board-user-play-ok-p (&optional buffer)
432 "Return non-nil if BUFFER is a GNUGO Board buffer ready for a user move."
433 (with-current-buffer (or buffer (current-buffer))
434 (and gnugo-state (not (gnugo-get :waiting)))))
436 (defsubst gnugo--blackp (string)
437 (string= "black" string))
439 (defun gnugo-other (color)
440 (if (gnugo--blackp color) "white" "black"))
442 (defun gnugo-current-player ()
443 "Return the current player, either \"black\" or \"white\"."
444 (gnugo-other (gnugo-get :last-mover)))
446 (defsubst gnugo--prop<-color (color)
447 (if (gnugo--blackp color) :B :W))
449 (defun gnugo-gate (&optional in-progress-p)
450 (unless (gnugo-board-buffer-p)
451 (user-error "Wrong buffer -- try M-x gnugo"))
452 (unless (gnugo-get :proc)
453 (user-error "No \"gnugo\" process!"))
454 (cl-destructuring-bind (&optional color . suggestion)
458 "%s -- please wait for \"(%s to play)\""
460 (list "Still thinking"
462 (list "Not your turn yet"
463 (gnugo-other color))))))
464 (when (and in-progress-p (gnugo-get :game-over))
465 (user-error "Sorry, game over")))
467 (defun gnugo-sentinel (proc string)
468 (let ((status (process-status proc)))
469 (when (memq status '(exit signal))
470 (let ((buf (process-buffer proc)))
471 (when (buffer-live-p buf)
472 (with-current-buffer buf
473 (setq mode-line-process
475 (propertize (car (split-string string))
476 'face 'font-lock-warning-face)
478 (when (eq proc (gnugo-get :proc))
479 (gnugo--forget :proc))))))))
481 (defun gnugo--begin-exchange (proc filter line)
482 (declare (indent 2)) ; good time, for a rime
483 ; nice style, for a wile...
484 (set-process-filter proc filter)
485 (process-send-string proc line)
486 (process-send-string proc "\n"))
488 (defun gnugo--q (fmt &rest args)
489 "Send formatted command \"FMT ARGS...\"; wait for / return response.
490 The response is a string whose first two characters indicate the
491 status of the command. See also `gnugo-query'."
492 (let ((slow (gnugo-get :waiting))
493 (proc (gnugo-get :proc)))
495 (user-error "Sorry, still waiting for %s to %s"
496 (car slow) (if (cdr slow)
497 "receive a suggestion"
499 (process-put proc :incomplete t)
500 (process-put proc :srs "") ; synchronous return stash
501 (gnugo--begin-exchange
502 proc (lambda (proc string)
503 (let ((full (concat (process-get proc :srs)
505 (process-put proc :srs full)
506 (unless (numberp (gnugo--compare-strings
507 full (max 0 (- (length full)
510 (process-put proc :incomplete nil))))
513 (apply #'format fmt args)))
514 (while (process-get proc :incomplete)
515 (accept-process-output proc 30))
516 (prog1 (substring (process-get proc :srs) 0 -2)
517 (process-put proc :srs ""))))
519 (defsubst gnugo--no-worries (string)
520 (= ?= (aref string 0)))
522 (defun gnugo--q/ue (fmt &rest args)
523 (let ((ans (apply 'gnugo--q fmt args)))
524 (unless (gnugo--no-worries ans)
525 (user-error "%s" ans))
528 (defun gnugo-query (message-format &rest args)
529 "Send GNU Go a command formatted with MESSAGE-FORMAT and ARGS.
530 Return a string that omits the first two characters (corresponding
531 to the status indicator in the Go Text Protocol). Use this function
532 when you are sure the command cannot fail."
533 (substring (apply 'gnugo--q message-format args)
536 (defun gnugo--nquery (cmd)
537 (string-to-number (gnugo-query cmd)))
539 (defun gnugo-lsquery (message-format &rest args)
540 (split-string (apply 'gnugo-query message-format args)))
542 (defsubst gnugo--count-query (fmt &rest args)
543 (length (apply 'gnugo-lsquery fmt args)))
545 (defsubst gnugo--root-prop (prop &optional tree)
546 (cdr (assq prop (gnugo--root-node tree))))
548 (defun gnugo--set-root-prop (prop value &optional tree)
549 (let* ((root (gnugo--root-node tree))
550 (cur (assq prop root)))
553 (push (cons prop value)
554 (cdr (last root))))))
556 (defun gnugo-goto-pos (pos)
557 "Move point to board position POS, a letter-number string."
558 (goto-char (point-min))
559 (forward-line (- (1+ (gnugo-get :SZ))
560 (string-to-number (substring pos 1))))
562 (forward-char (+ (if (= 32 (following-char)) 1 2)
563 (* 2 (- (let ((letter (aref pos 0)))
570 (intern (if (symbolp id)
573 (gnugo-get :obarray)))
575 (defun gnugo-yang (c)
576 (cdr (assq c '((?+ . hoshi)
578 (?X . (bmoku . bpmoku))
579 (?O . (wmoku . wpmoku))))))
581 (defun gnugo-yy (yin yang &optional momentaryp)
582 (gnugo-f (format "%d-%s"
583 yin (cond ((symbolp yang) yang)
584 (momentaryp (cdr yang))
587 (defun gnugo-toggle-image-display ()
588 (unless (display-images-p)
589 (user-error "Display does not support images, sorry"))
590 (let ((fresh (if (functionp gnugo-xpms)
591 (funcall gnugo-xpms (gnugo-get :SZ))
594 (user-error "Sorry, `gnugo-xpms' unset"))
595 (unless (eq fresh (gnugo-get :xpms))
596 (gnugo-put :xpms fresh)
597 (gnugo--forget :all-yy)))
598 (let* ((new (not (gnugo-get :display-using-images)))
599 (act (if new 'display 'do-not-display)))
601 (setcar (symbol-plist yy) act))
602 (or (gnugo-get :all-yy)
604 (prog1 (mapcar (lambda (ent)
606 (yy (gnugo-yy (cdr k) (car k))))
607 (setplist yy `(not-yet ,(cdr ent)))
611 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
613 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
614 (gnugo-put :highlight-last-move-spec
617 (get (gnugo-yy (get-text-property p 'gnugo-yin)
618 (get-text-property p 'gnugo-yang)
622 (gnugo-get :default-highlight-last-move-spec)))
623 ;; a kludge to be reworked another time perhaps by another gnugo.el lover
624 (dolist (group (cdr (assq 'dead (gnugo-get :game-over))))
625 (mapc 'delete-overlay (cdar group))
626 (setcdr (car group) nil))
627 (gnugo-put :mul (if new
630 (gnugo-put :display-using-images new)))
632 (define-minor-mode gnugo-grid-mode
633 "If enabled, display grid around the board."
635 ((not (memq :nogrid buffer-invisibility-spec))
639 'remove-from-invisibility-spec
640 'add-to-invisibility-spec)
642 (save-excursion (gnugo-refresh)))))
644 (defun gnugo-propertize-board-buffer ()
646 (insert (substring (gnugo--q "showboard") 3))
647 (let* ((grid-props (list 'invisible :nogrid
648 'font-lock-face gnugo-grid-face))
649 (%gpad (gnugo-f 'gpad))
650 (%gspc (gnugo-f 'gspc))
651 (%lpad (gnugo-f 'lpad))
652 (%rpad (gnugo-f 'rpad))
653 (ispc-props (list 'category (gnugo-f 'ispc) 'rear-nonsticky t))
654 (size (gnugo-get :SZ))
655 (size-string (number-to-string size)))
656 (goto-char (point-min))
657 (put-text-property (point) (1+ (point)) 'category (gnugo-f 'tpad))
658 (skip-chars-forward " ")
659 (put-text-property (1- (point)) (point) 'category %gpad)
660 (put-text-property (point) (progn (end-of-line) (point)) 'category %gspc)
662 (add-text-properties (1+ (point-min)) (1- (point)) grid-props)
663 (while (looking-at "\\s-*\\([0-9]+\\)[ ]")
664 (let* ((row (match-string-no-properties 1))
666 (other-edge (+ edge (* 2 size) -1))
667 (right-empty (+ other-edge (length row) 1))
668 (top-p (string= size-string row))
669 (bot-p (string= "1" row)))
670 (let* ((nL (- edge 1 (length size-string)))
672 (ov (make-overlay nL nR (current-buffer) t)))
673 (add-text-properties nL nR grid-props)
674 ;; We redundantly set `invisible' in the overlay to workaround
675 ;; a display bug whereby text *following* the overlaid text is
676 ;; displayed with the face of the overlaid text, but only when
677 ;; that text is invisible (i.e., `:nogrid' in invisibility spec).
678 ;; This has something to do w/ the bletcherous `before-string'.
679 (overlay-put ov 'invisible :nogrid)
680 (overlay-put ov 'category %lpad))
681 (cl-do ((p edge (+ 2 p)) (ival 'even (if (eq 'even ival) 'odd 'even)))
683 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
684 (truncate (- p edge) 2))
686 (yin (let ((A-p (= edge p))
687 (Z-p (= (1- other-edge) p)))
688 (cond ((and top-p A-p) 1)
697 (yang (gnugo-yang (char-after p))))
698 (add-text-properties p (1+ p)
708 (gnugo-position gnugo-yin))))
709 (unless (= (1- other-edge) p)
710 (add-text-properties (1+ p) (+ 2 p) ispc-props)
711 (put-text-property p (+ 2 p) 'intangible ival)))
712 (add-text-properties (1+ other-edge) right-empty grid-props)
713 (goto-char right-empty)
714 (when (looking-at "\\s-+\\(WH\\|BL\\).*capt.* \\([0-9]+\\).*$")
715 (let ((prop (if (string= "WH" (match-string 1))
718 (beg (match-beginning 2))
720 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
721 (gnugo-put prop (match-string-no-properties 2))))
723 (put-text-property right-empty (point) 'category %rpad)
725 (add-text-properties (1- (point)) (point-max) grid-props)
726 (skip-chars-forward " ")
727 (put-text-property (1- (point)) (point) 'category %gpad)
728 (put-text-property (point) (progn (end-of-line) (point))
731 (defun gnugo-merge-showboard-results ()
732 (let ((aft (substring (gnugo--q "showboard") 3))
733 (adj 1) ; string to buffer position adjustment
735 (sync "[0-9]* stones$")
736 ;; Note: `sync' used to start w/ "[0-9]+", but that is too
737 ;; restrictive a condition that fails in the case of:
740 ;; ... WHITE has captured 1 stones
743 ;; ... WHITE has captured 14 stones
746 ;; where the after count has more digits than the before count,
747 ;; but shares the same leading digits. In this case, the result
748 ;; of `compare-strings' points to the SPC following the before
749 ;; count (indicated by caret in this example).
751 (bef (buffer-substring-no-properties (point-min) (point-max)))
752 (bef-start 0) (bef-idx 0)
753 (aft-start 0) (aft-idx 0)
754 aft-sync-backtrack mis inc cut new very-strange
756 (inhibit-read-only t))
757 (while (numberp (setq mis (gnugo--compare-strings
760 (setq aft-sync-backtrack nil
761 inc (if (cl-minusp mis)
764 bef-idx (+ bef-start inc)
765 aft-idx (+ aft-start inc)
766 bef-start (if (eq bef-idx (string-match sync bef bef-idx))
769 aft-start (if (and (eq aft-idx (string-match sync aft aft-idx))
770 (let ((peek (1- aft-idx)))
771 (while (not (= 32 (aref aft peek)))
772 (setq peek (1- peek)))
773 (setq aft-sync-backtrack (1+ peek))))
777 (if aft-sync-backtrack
778 (- aft-sync-backtrack aft-idx)
781 (if aft-sync-backtrack
782 (let* ((asb aft-sync-backtrack)
783 (l-p (get-text-property cut :gnugo-cf))
786 (keep (text-properties-at cut)))
787 (setq new (substring aft asb (string-match " " aft asb)))
788 (plist-put keep :gnugo-cf (cons (length new) capprop))
789 (gnugo-put capprop new)
790 (delete-char old-len)
791 (insert (apply 'propertize new keep))
792 (cl-incf adj (- (length new) old-len)))
793 (setq new (aref aft aft-idx))
794 (insert-and-inherit (char-to-string new))
795 (let ((yin (get-text-property cut 'gnugo-yin))
796 (yang (gnugo-yang new)))
797 (add-text-properties cut (1+ cut)
801 ,(gnugo-yy yin yang))))
803 ;; do this last to avoid complications w/ font lock
804 ;; (this also means we cannot include `intangible' in `front-sticky')
805 (when (setq very-strange (get-text-property (1+ cut) 'intangible))
806 (put-text-property cut (1+ cut) 'intangible very-strange))))))
808 (defsubst gnugo--move-prop (node)
812 (defun gnugo--as-pos-func ()
813 (let ((size (gnugo-get :SZ)))
818 (let ((col (aref cc 0)))
820 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
821 (- size (- (aref cc 1) ?a))))))))
823 (defsubst gnugo--resignp (string)
824 (string= "resign" string))
826 (defsubst gnugo--passp (string)
827 (string= "PASS" string))
829 (defun gnugo-move-history (&optional rsel color)
830 "Determine and return the game's move history.
831 Optional arg RSEL controls side effects and return value.
832 If nil, display the history in the echo area as \"(N moves)\"
833 followed by the space-separated list of moves. When called
834 interactively with a prefix arg (i.e., RSEL is `(4)'), display
835 similarly, but suffix with the mover (either \":B\" or \":W\").
836 RSEL may also be a symbol that selects what to return:
837 car -- the most-recent move
838 cadr -- the next-to-most-recent move
839 two -- the last two moves as a list, oldest last
840 bpos -- the last stone on the board placed by COLOR
841 For all other values of RSEL, do nothing and return nil."
843 (let* ((monkey (gnugo-get :monkey))
844 (mem (aref monkey 0))
845 (as-pos (gnugo--as-pos-func))
848 ((as-pos-maybe (x) (if (gnugo--resignp x)
851 (remem () (setq node (pop mem)
852 mprop (gnugo--move-prop node)))
853 (next (byp) (when (remem)
854 (setq move (as-pos-maybe (cdr mprop)))
856 (format "%s%s" move (car mprop))
860 (tell () (message "(%d moves) %s"
862 (mapconcat 'identity (nreverse acc) " ")))
863 (finish (byp) (while mem (next byp)) (tell)))
868 (`cadr (nn) (car (nn)))
871 with prop = (gnugo--prop<-color color)
874 (eq prop (car mprop))
875 (setq move (cdr mprop))
876 ;; i.e., "normal CC" position
878 return (funcall as-pos move)))
881 (defun gnugo-boss-is-near ()
882 "Do `bury-buffer' until the current one is not a GNU Board."
884 (while (gnugo-board-buffer-p)
887 (defsubst gnugo--no-regrets (monkey ends)
888 (eq (aref ends (aref monkey 1))
891 (defun gnugo--as-cc-func ()
892 (let ((size (gnugo-get :SZ)))
894 (let* ((col (aref pos 0))
895 (one (+ ?a (- col (if (< ?H col) 1 0) ?A)))
896 (two (+ ?a (- size (string-to-number
897 (substring pos 1))))))
898 (format "%c%c" one two)))))
900 (defun gnugo--decorate (node &rest plist)
902 with tp = (last node)
906 fruit (list (cons ; DWR: LtR OoE assumed.
912 (defun gnugo-close-game (end-time resign)
913 (gnugo-put :game-end-time end-time)
914 (let ((now (or end-time (current-time))))
915 (gnugo-put :scoring-seed (logior (ash (logand (car now) 255) 16)
917 (gnugo-put :game-over
918 (if (or (eq t resign)
919 (and (stringp resign)
920 (string-match "[BW][+][Rr]esign" resign)))
927 (gnugo-query "worm_stones %s" color)
929 (let ((live (append (ls "black") (ls "white"))))
932 (let ((dd (gnugo-query "dragon_data"))
933 (start 0) mem color ent live dead)
934 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
936 (setq mem (match-string 1 dd)
937 color (match-string 2 dd)
939 ent (cons (list color)
940 (sort (gnugo-lsquery "dragon_stones %s" mem)
942 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
944 (if (match-string 2 dd)
947 (setq start (match-end 0)))
951 (defun gnugo--unclose-game ()
952 (gnugo--forget :game-over ; all those in -close-game
955 (let* ((root (gnugo--root-node))
956 (cur (assq :RE root)))
958 (cl-assert (not (eq cur (car root))) nil
959 ":RE at head of root node: %S"
963 (defun gnugo-push-move (who move)
964 (let* ((simple (booleanp who))
965 (ucolor (gnugo-get :user-color))
969 (gnugo-get :gnugo-color))
971 (start (gnugo-get :waiting-start))
973 (resignp (gnugo--resignp move))
974 (passp (gnugo--passp move))
975 (head (gnugo-move-history 'car))
976 (onep (and head (gnugo--passp head)))
977 (donep (or resignp (and onep passp))))
979 (gnugo--q/ue "play %s %s" color move))
981 (gnugo-merge-showboard-results))
982 (gnugo-put :last-mover color)
985 (string= ucolor color))
986 (gnugo-put :last-user-bpos (and (not passp) (not resignp) move)))
987 ;; update :sgf-gametree and :monkey
988 (let* ((property (gnugo--prop<-color color))
989 (pair (cons property (cond (resignp move)
991 (t (funcall (gnugo--as-cc-func)
994 (monkey (gnugo-get :monkey))
995 (mem (aref monkey 0))
997 (tree (gnugo-get :sgf-gametree))
998 (ends (gnugo--tree-ends tree))
999 (mnum (gnugo--tree-mnum tree))
1000 (count (length ends))
1001 (tip-move-num (gethash tip mnum))
1002 (bidx (aref monkey 1)))
1003 ;; Detect déjà-vu. That is, when placing "A", avoid:
1009 ;; (such "variations" do not actually vary!) in favor of:
1015 ;; This linear search loses for multiple ‘old’ w/ "A",
1016 ;; a very unusual (but not invalid, sigh) situation.
1020 ;; Start with latest / highest likelihood for hit.
1021 ;; (See "to the right" comment, below.)
1022 from (if (gnugo--no-regrets monkey ends)
1026 if (setq bx (mod (+ bidx i) count)
1030 for m on (aref ends bx)
1031 while (< tip-move-num
1032 (gethash (setq node (car m))
1035 return (when (equal pair (assq property node))
1037 finally return nil))
1042 (cl-rotatef (aref ends bidx)
1044 (setq mem previous))
1048 (unless (gnugo--no-regrets monkey ends)
1049 (setq ends (gnugo--set-tree-ends
1050 tree (let ((ls (append ends nil)))
1051 ;; copy old to the right of new
1052 (push mem (nthcdr bidx ls))
1054 (puthash fruit (1+ (gethash tip mnum)) mnum)
1056 (aset ends bidx mem)))
1057 (setf (aref monkey 0) mem))
1059 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1061 (gnugo-close-game now resignp))
1062 (gnugo-put :waiting-start (and (not donep) now))
1065 (defun gnugo-venerate (yin yang)
1066 (let* ((fg-yy (gnugo-yy yin yang))
1067 (fg-disp (or (get fg-yy 'display)
1068 (get fg-yy 'do-not-display)))
1069 (fg-props (cdr fg-disp))
1070 (fg-data (plist-get fg-props :data))
1071 (c-symbs (plist-get fg-props :color-symbols))
1072 (bg-yy (gnugo-yy yin (gnugo-yang ?.)))
1073 (bg-disp (or (get bg-yy 'display)
1074 (get bg-yy 'do-not-display)))
1075 (bg-data (plist-get (cdr bg-disp) :data))
1079 (when (string-match "\\([0-9]+\\)\\s-+[0-9]+\"," s)
1080 (setq start (match-end 0))
1081 (string-to-number (match-string 1 s)))))
1082 (while (and (not (cl-minusp ncolors))
1083 (string-match ",\n" s start))
1084 (setq start (match-end 0)
1085 ncolors (1- ncolors)))
1086 (string-match "\"" s start)
1088 (new (copy-sequence fg-data))
1089 (lx (length fg-data))
1090 (sx (funcall bop fg-data))
1091 (sb (funcall bop bg-data))
1092 (color-key (aref new sx))) ; blech, heuristic
1094 (when (and (not (= color-key (aref new sx)))
1095 (cl-plusp (random 4)))
1096 (aset new sx (aref bg-data sb)))
1099 (apply 'create-image new 'xpm t
1100 :ascent 'center (when c-symbs
1101 (list :color-symbols
1104 (defun gnugo-refresh (&optional nocache)
1105 "Update GNUGO Board buffer display.
1106 While a game is in progress, parenthesize the last-played stone (no parens
1107 for pass). If the buffer is currently displayed in the selected window,
1108 recenter the board (presuming there is extra space in the window). Update
1109 the mode line. Lastly, move point to the last position played by the user,
1110 if that move was not a pass.
1112 Prefix arg NOCACHE requests complete reconstruction of the display, which may
1113 be slow. (This should normally be unnecessary; specify it only if the display
1114 seems corrupted.) NOCACHE is silently ignored when GNU Go is thinking about
1117 (let* ((move (gnugo-move-history 'car))
1118 (game-over (gnugo-get :game-over))
1119 (inhibit-read-only t)
1121 (when (and nocache (not (gnugo-get :waiting)))
1122 (gnugo-propertize-board-buffer))
1125 (cl-destructuring-bind (l-ov . r-ov) (gnugo-get :paren-ov)
1126 (if (member move '("PASS" "resign"))
1127 (mapc 'delete-overlay (list l-ov r-ov))
1128 (gnugo-goto-pos move)
1130 (hspec (gnugo-get :highlight-last-move-spec))
1131 (display-value (nth 0 hspec))
1132 (l-offset (nth 1 hspec))
1133 (l-new-pos (+ p l-offset))
1134 (r-action (nth 2 hspec)))
1135 (overlay-put l-ov 'display
1136 (if (functionp display-value)
1137 (funcall display-value p)
1139 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1141 (funcall r-action r-ov)
1142 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1144 (rename-buffer (concat (gnugo-get :diamond)
1146 (format "%s(game over)"
1147 (if (gnugo--resignp move)
1148 (concat move "ation ")
1150 (format "%s(%s to play)"
1151 (if move (concat move " ") "")
1152 (gnugo-current-player)))))
1155 (let ((live (cdr (assq 'live game-over)))
1156 (dead (cdr (assq 'dead game-over)))
1158 (unless (eq game-over (get-text-property 1 'game-over))
1159 (dolist (group (append live dead))
1160 (dolist (pos (cdr group))
1161 (gnugo-goto-pos pos)
1163 (put-text-property p (1+ p) 'group group)))
1164 (put-text-property 1 2 'game-over game-over))
1165 (dolist (group live)
1166 (when (setq pall (cdar group))
1167 (mapc 'delete-overlay pall)
1168 (setcdr (car group) nil)))
1169 (dolist (group dead)
1170 (unless (cdar group)
1171 (let (ov pall c (color (caar group)))
1172 (setq c (if (gnugo--blackp color) "x" "o"))
1173 (dolist (pos (cdr group))
1174 (gnugo-goto-pos pos)
1175 (setq p (point) ov (make-overlay p (1+ p)))
1178 (if (gnugo-get :display-using-images)
1179 ;; respect the dead individually; it takes more time
1180 ;; but that's not a problem (for them)
1181 (gnugo-venerate (get-text-property p 'gnugo-yin)
1182 (gnugo-yang (aref (upcase c) 0)))
1183 (propertize c 'face 'font-lock-warning-face)))
1185 (setcdr (car group) pall))))))
1187 (when (setq window (get-buffer-window (current-buffer)))
1188 (let* ((gridp (not (memq :nogrid buffer-invisibility-spec)))
1189 (size (gnugo-get :SZ))
1190 (under10p (< size 10))
1191 (mul (gnugo-get :mul))
1192 (h (- (truncate (- (window-height window)
1197 (edges (window-edges window))
1198 (right-w-edge (nth 2 edges))
1199 (avail-width (- right-w-edge (nth 0 edges)))
1201 (imagesp (symbol-plist (gnugo-f 'ispc)))
1202 (w (/ (- avail-width
1207 2 ; between board and grid
1212 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1213 `(display ,(make-string h 10))
1214 '(invisible :nogrid)))
1219 (cond (imagesp (+ (* 0.5 wmul)
1225 (gspc . ,(when imagesp
1229 ;; DWR: image width alone => OBOE!
1231 ;; NB: ‘(* wmul cw)’ is the same
1232 ;; as ‘(car (image-size ... t))’.
1233 (let ((cw (frame-char-width)))
1234 (/ (+ 1.0 (* wmul cw))
1237 (lpad . ,(let ((d `(display (space :align-to ,w))))
1238 ;; We distinguish between these cases to
1239 ;; workaround a display bug whereby the
1240 ;; `before-string' is omitted entirely (not
1241 ;; rendered) when interacting w/ the text
1242 ;; mode last-move left-paren for moves in
1246 ,(apply 'propertize " " d))
1249 (space :align-to ,(1- avail-width))))))
1250 (setplist (gnugo-f (car pair)) (cdr pair)))))
1252 (let ((cur (gnugo-get :mode-line)))
1253 (unless (equal cur gnugo-mode-line)
1254 (setq cur gnugo-mode-line)
1255 (gnugo-put :mode-line cur)
1256 (gnugo-put :mode-line-form
1257 (cond ((stringp cur)
1258 (setq cur (copy-sequence cur))
1260 (while (setq cut (string-match "~[bwpmtu]" cur))
1262 (setq c (aref cur (cl-incf cut)))
1265 `(,(intern (format "squig-%c" c))
1267 (?b '(or (gnugo-get :black-captures) 0))
1268 (?w '(or (gnugo-get :white-captures) 0))
1269 (?p '(gnugo-current-player))
1270 (?t '(let ((ws (gnugo-get :waiting-start)))
1272 (cadr (time-since ws))
1274 (?u '(or (gnugo-get :last-waiting) "-"))
1275 (?m '(let ((tree (gnugo-get :sgf-gametree))
1276 (monkey (gnugo-get :monkey)))
1277 (gethash (car (aref monkey 0))
1278 (gnugo--tree-mnum tree)
1279 ;; should be unnecessary
1282 `(let ,(delete-dups (copy-sequence acc))
1283 (format ,cur ,@(reverse (mapcar 'car acc))))))
1285 (let ((form (gnugo-get :mode-line-form)))
1286 (setq mode-line-process
1288 ;; this dynamicism is nice but excessive in its wantonness
1289 ;;- `(" [" (:eval ,form) "]")
1290 ;; this dynamicism is ok because the user triggers it
1291 (format " [%s]" (eval form)))))
1292 (force-mode-line-update))
1294 (when (setq last (gnugo-get :last-user-bpos))
1295 (gnugo-goto-pos last))))
1297 (defun gnugo--turn-the-wheel (&optional now)
1298 (unless (gnugo-get :waiting)
1299 (let ((color (gnugo-current-player))
1300 (wheel (gnugo-get :wheel)))
1302 (when (and (not (gnugo-get :game-over))
1303 (member color (cdr wheel)))
1307 2) ;;; sec (frettoloso? dubioso!)
1309 (lambda (buf color wheel)
1311 (with-current-buffer buf
1312 (gnugo-get-move color)))
1316 (defun gnugo--finish-move (&optional now)
1317 (let ((buf (current-buffer)))
1318 (run-hooks 'gnugo-post-move-hook)
1321 (gnugo--turn-the-wheel now))
1323 ;;;---------------------------------------------------------------------------
1324 ;;; Game play actions
1326 (defun gnugo--rename-buffer-portion (&optional back)
1327 (let ((old "to play")
1328 (new "waiting for suggestion"))
1330 (cl-rotatef old new))
1331 (let ((name (buffer-name)))
1332 (when (string-match old name)
1333 (rename-buffer (replace-match new t t name))))))
1335 (defun gnugo--display-suggestion (color suggestion)
1336 (message "%sSuggestion for %s: %s"
1337 (gnugo-get :diamond)
1340 (defun gnugo-get-move-insertion-filter (proc string)
1341 (with-current-buffer (process-buffer proc)
1342 (let* ((so-far (gnugo-get :get-move-string))
1343 (full (gnugo-put :get-move-string (concat so-far string))))
1344 (when (string-match "^= \\(.+\\)\n\n" full)
1345 (setq full (match-string 1 full)) ; POS or "PASS"
1346 (cl-destructuring-bind (color . suggestion)
1347 (gnugo-get :waiting)
1348 (gnugo--forget :get-move-string
1352 (gnugo--rename-buffer-portion t)
1353 (unless (or (gnugo--passp full)
1354 (eq 'nowarp suggestion))
1355 (gnugo-goto-pos full))
1356 (gnugo--display-suggestion color full))
1357 (gnugo-push-move color full)
1358 (gnugo--finish-move)))))))
1360 (defun gnugo-get-move (color &optional suggestion)
1361 (gnugo-put :waiting (cons color suggestion))
1362 (gnugo--begin-exchange
1363 (gnugo-get :proc) 'gnugo-get-move-insertion-filter
1364 ;; We used to use ‘genmove’ here, but that forced asymmetry in
1365 ;; downstream handling, an impediment to GNU Go vs GNU Go fun.
1366 (concat "reg_genmove " color))
1367 (accept-process-output))
1369 (defun gnugo-cleanup ()
1370 (when (gnugo-board-buffer-p)
1371 (unless (zerop (buffer-size))
1372 (message "Thank you for playing GNU Go."))
1373 (setq gnugo-state nil)))
1375 (defun gnugo-position ()
1376 (or (get-text-property (point) 'gnugo-position)
1377 (user-error "Not a proper position point")))
1379 (defun gnugo-request-suggestion (&optional nowarp)
1380 "Request a move suggestion from GNU Go.
1381 After some time (during which you can do other stuff),
1382 Emacs displays the suggestion in the echo area and warps the
1383 cursor to the suggested position. Prefix arg inhibits warp."
1386 (gnugo--rename-buffer-portion)
1387 (gnugo-get-move (gnugo-current-player)
1392 (defun gnugo--karma (color) ; => BOOL
1393 (when (member color (cdr (gnugo-get :wheel)))
1396 (defsubst gnugo--:karma (role)
1397 (gnugo--karma (gnugo-get role)))
1399 (defun gnugo--assist-state (&optional gate)
1400 (let ((bool (gnugo--:karma :user-color)))
1402 (user-error "Sorry, Assist mode enabled")
1405 (defun gnugo--user-play (pos-or-pass)
1407 ;; The "user" in this func's name used to signify both
1408 ;; who does the action and for whom the action is done.
1409 ;; Now, it signifies only the former.
1410 (let ((color (gnugo-current-player)))
1411 ;; Don't get confused by mixed signals.
1412 (when (gnugo--karma color)
1413 (if (equal color (gnugo-get :one-shot))
1414 (gnugo--forget :one-shot)
1415 (user-error "Sorry, you cannot play for %s at this time"
1417 (gnugo-push-move color pos-or-pass))
1418 (gnugo--finish-move t))
1420 (defun gnugo-move ()
1421 "Make a move on the GNUGO Board buffer.
1422 The position is computed from current point.
1423 Signal error if done out-of-turn or if game-over.
1424 To start a game try M-x gnugo."
1426 (gnugo--user-play (gnugo-position)))
1428 (defun gnugo-mouse-move (e)
1429 "Do `gnugo-move' at mouse location."
1432 (when (memq (following-char) '(?. ?+))
1435 (defun gnugo-pass ()
1436 "Make a pass on the GNUGO Board buffer.
1437 Signal error if done out-of-turn or if game-over.
1438 To start a game try M-x gnugo."
1440 (gnugo--user-play "PASS"))
1442 (defun gnugo-mouse-pass (e)
1443 "Do `gnugo-pass' at mouse location."
1448 (defun gnugo-resign ()
1451 (if (not (y-or-n-p "Resign? "))
1452 (message "(not resigning)")
1453 (gnugo-push-move t "resign")
1456 (defun gnugo-animate-group (w/d)
1457 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1459 (let* ((pos (gnugo-position))
1460 (orig-b-m-p (buffer-modified-p))
1462 (unless (memq (following-char) '(?X ?O))
1463 (user-error "No stone at %s" pos))
1464 (setq blurb (message "Computing %s stones ..." w/d)
1465 stones (gnugo-lsquery "%s_stones %s" w/d pos))
1466 (message "%s %s in group." blurb (length stones))
1467 (setplist (gnugo-f 'anim) nil)
1468 (let* ((spec (if (gnugo-get :display-using-images)
1470 with yin = (get-text-property (point) 'gnugo-yin)
1471 with yang = (gnugo-yang (following-char))
1472 with up = (get (gnugo-yy yin yang t) 'display)
1473 with dn = (get (gnugo-yy yin yang) 'display)
1474 for n below (length gnugo-animation-string)
1475 collect (if (zerop (logand 1 n))
1477 (split-string gnugo-animation-string "" t)))
1479 (ovs (save-excursion
1480 (mapcar (lambda (pos)
1481 (gnugo-goto-pos pos)
1483 (ov (make-overlay p (1+ p))))
1484 (overlay-put ov 'category (gnugo-f 'anim))
1485 (overlay-put ov 'priority most-positive-fixnum)
1488 (setplist (gnugo-f 'anim) (cons 'display cell))
1489 (while (and (cdr spec) ; let last linger lest levity lost
1490 (sit-for 0.08675309)) ; jenny jenny i got your number...
1491 (setcar cell (setq spec (cdr spec)))
1492 ;; Force redisplay of overlays.
1493 (set-buffer-modified-p orig-b-m-p))
1495 (mapc 'delete-overlay ovs)
1498 (defun gnugo-display-group-data (command buffer-name)
1500 (message "Computing %s ..." command)
1501 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1502 (switch-to-buffer buffer-name)
1505 (message "Computing %s ... done." command))
1507 (defun gnugo-worm-stones ()
1508 "In the GNUGO Board buffer, animate \"worm\" at current position.
1509 Signal error if done out-of-turn or if game-over.
1510 See variable `gnugo-animation-string' for customization."
1512 (gnugo-animate-group 'worm))
1514 (defun gnugo-worm-data ()
1515 "Display in another buffer data from \"worm\" at current position.
1516 Signal error if done out-of-turn or if game-over."
1518 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1520 (defun gnugo-dragon-stones ()
1521 "In the GNUGO Board buffer, animate \"dragon\" at current position.
1522 Signal error if done out-of-turn or if game-over.
1523 See variable `gnugo-animation-string' for customization."
1525 (gnugo-animate-group 'dragon))
1527 (defun gnugo-dragon-data ()
1528 "Display in another buffer data from \"dragon\" at current position.
1529 Signal error if done out-of-turn or if game-over."
1531 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1533 (defun gnugo-estimate-score ()
1534 "Display estimated score of a game of GNU Go.
1535 Output includes number of stones on the board and number of stones
1536 captured by each player, and the estimate of who has the advantage (and
1537 by how many stones)."
1539 (message "Est.score ...")
1540 (let ((black (gnugo--count-query "list_stones black"))
1541 (white (gnugo--count-query "list_stones white"))
1542 (black-captures (gnugo-query "captures black"))
1543 (white-captures (gnugo-query "captures white"))
1544 (est (gnugo-query "estimate_score")))
1545 ;; might as well update this
1546 (gnugo-put :black-captures black-captures)
1547 (gnugo-put :white-captures white-captures)
1548 (message "Est.score ... B %s %s | W %s %s | %s"
1549 black black-captures white white-captures est)))
1551 (defun gnugo--ok-file (filename)
1552 (setq default-directory
1553 (file-name-directory
1554 (expand-file-name filename)))
1555 (set-buffer-modified-p nil))
1557 (defun gnugo-write-sgf-file (filename)
1558 "Save the game history to FILENAME (even if unfinished).
1559 If FILENAME already exists, Emacs confirms that you wish to overwrite it."
1560 (interactive "FWrite game as SGF file: ")
1561 (when (and (file-exists-p filename)
1562 (not (y-or-n-p "File exists. Continue? ")))
1563 (user-error "Not writing %s" filename))
1564 (when (buffer-modified-p)
1565 ;; take responsibility for our actions
1566 (gnugo--set-root-prop :AP (cons "gnugo.el" gnugo-version)))
1567 (gnugo/sgf-write-file (gnugo-get :sgf-collection) filename)
1568 (gnugo--ok-file filename))
1570 (defun gnugo--dance-dance (karma)
1571 (cl-destructuring-bind (dance btw)
1572 (aref [(moshpit " Zombie")
1574 (reverse " Zombie Assist") ; "Assist Zombie"? no thanks! :-D
1575 (stilted " Assist")]
1578 (if (member (gnugo-get prop)
1582 (+ (try 2 :user-color)
1583 (try 1 :gnugo-color))))
1584 (gnugo-put :dance dance) ; pure cruft (for now)
1585 (setq gnugo-btw btw)))
1587 (defun gnugo--who-is-who (wait play samep)
1589 (let ((wheel (gnugo-get :wheel)))
1592 (setcdr wheel (mapcar 'gnugo-other
1594 (message "GNU Go %splays as %s, you as %s (%s)"
1595 (if samep "" "now ")
1598 "NOTE: this is a switch!")))
1600 (defsubst gnugo--nodep (x)
1601 (keywordp (caar x)))
1603 (defun gnugo--SZ! (size)
1604 (gnugo-put :SZ size)
1605 (gnugo-put :center-position
1606 (funcall (gnugo--as-pos-func)
1607 (let ((c (+ -1 ?a (truncate (1+ size) 2))))
1610 (defun gnugo--plant-and-climb (collection &optional sel)
1611 (gnugo-put :sgf-collection collection)
1612 (let ((tree (nth (or sel 0) collection)))
1613 (gnugo-put :sgf-gametree tree)
1614 (gnugo-put :monkey (vector
1616 (aref (gnugo--tree-ends tree) 0)
1621 (defun gnugo-read-sgf-file (filename)
1622 "Load the first game tree from FILENAME, a file in SGF format."
1623 (interactive "fSGF file to load: ")
1624 (when (file-directory-p filename)
1625 (user-error "Cannot load a directory (try a filename with extension .sgf)"))
1626 (let (play wait samep coll tree game-over)
1627 ;; problem: requiring GTP `loadsgf' complicates network subproc support;
1628 ;; todo: skip it altogether when confident about `gnugo/sgf-create'
1629 (setq play (gnugo--q/ue "loadsgf %s" (expand-file-name filename))
1630 wait (gnugo-other play)
1631 samep (string= (gnugo-get :user-color) play))
1632 (gnugo-put :last-mover wait)
1634 (gnugo-put :gnugo-color wait)
1635 (gnugo-put :user-color play))
1636 (setq coll (gnugo/sgf-create filename)
1637 tree (gnugo--plant-and-climb
1638 coll (let ((n (length coll)))
1642 ;; (let* ((q (format "Which game? (1-%d)" n))
1643 ;; (choice (1- (read-number q 1))))
1644 ;; (if (and (< -1 choice) (< choice n))
1646 ;; (message "(Selecting the first game)")
1648 ;; but this is what we use (for now) to accomodate
1649 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1651 (message "(Selecting the first game)"))
1653 ;; This is deliberately undocumented for now.
1654 (gnugo--SZ! (gnugo--root-prop :SZ tree))
1655 (when (setq game-over (or (gnugo--root-prop :RE tree)
1656 (when (equal '("PASS" "PASS")
1657 (gnugo-move-history 'two))
1659 (gnugo-close-game nil game-over))
1660 (gnugo-put :last-user-bpos
1661 (gnugo-move-history 'bpos (gnugo-get :user-color)))
1663 (gnugo--ok-file filename)
1664 (gnugo--who-is-who wait play samep)))
1666 (defun gnugo--mem-with-played-stone (pos &optional noerror)
1667 (let ((color (cl-case (following-char)
1672 (user-error "No stone at %s" pos))
1674 with fruit = (cons color (funcall (gnugo--as-cc-func) pos))
1675 for mem on (aref (gnugo-get :monkey) 0)
1676 when (equal fruit (caar mem))
1678 finally return nil))))
1680 (defun gnugo--climb-towards-root (spec &optional reaction keep)
1682 (gnugo--assist-state t)
1683 (let* ((user-color (gnugo-get :user-color))
1684 (monkey (gnugo-get :monkey))
1685 (tree (gnugo-get :sgf-gametree))
1686 (ends (gnugo--tree-ends tree))
1687 (remorseful (not (gnugo--no-regrets monkey ends)))
1688 (stop (if (numberp spec)
1689 (nthcdr (if (zerop spec)
1690 (if (string= (gnugo-get :last-mover)
1696 (cdr (gnugo--mem-with-played-stone
1699 (gnugo-position)))))))
1700 (when (gnugo-get :game-over)
1701 (gnugo--unclose-game))
1702 (while (and (not (eq stop (aref monkey 0)))
1703 (gnugo--no-worries (gnugo--q "undo")))
1704 (pop (aref monkey 0))
1705 (gnugo-put :last-mover (gnugo-current-player))
1706 (gnugo-merge-showboard-results) ; all
1707 (gnugo-refresh) ; this
1708 (redisplay)) ; eye candy
1709 (let* ((ulastp (string= (gnugo-get :last-mover) user-color))
1710 (ubpos (gnugo-move-history (if ulastp 'car 'cadr))))
1711 (gnugo-put :last-user-bpos (if (and ubpos (not (gnugo--passp ubpos)))
1713 (gnugo-get :center-position)))
1715 (unless (or keep remorseful)
1716 (aset ends (aref monkey 1) (aref monkey 0)))
1718 (let ((g (gnugo-get :gnugo-color)))
1719 (cl-flet ((turn () (gnugo--turn-the-wheel t)))
1720 (cl-case (or reaction gnugo-undo-reaction)
1722 (play! (let ((wheel (gnugo-get :wheel)))
1723 (cl-letf (((cdr wheel) (cons g (cdr wheel))))
1725 (zombie (gnugo-zombie-mode 1))
1726 (t (gnugo-put :one-shot g)))))))))
1728 (defun gnugo-undo-one-move (&optional me-next)
1729 "Undo exactly one move (perhaps GNU Go's, perhaps yours).
1730 Do not schedule a move by GNU Go even if it is GNU Go's turn to play.
1731 Prefix arg ME-NEXT means to arrange for you to play
1732 the color of the next move (and GNU Go the opposite).
1733 This is useful after loading an SGF file whose last
1734 move was done by the color you prefer to play:
1735 \\[gnugo-read-sgf-file] FILENAME RET
1736 C-u \\[gnugo-undo-one-move]
1738 See also `gnugo-undo-two-moves'."
1742 (let* ((play (gnugo-get :last-mover))
1743 (wait (gnugo-other play))
1744 (samep (string= play (gnugo-get :user-color))))
1745 (gnugo-put :user-color play)
1746 (gnugo-put :gnugo-color wait)
1747 (gnugo--who-is-who wait play samep)))
1748 (gnugo--climb-towards-root 1 (cl-case gnugo-undo-reaction
1749 (zombie gnugo-undo-reaction)
1752 (defun gnugo-undo-two-moves ()
1753 "Undo a pair of moves (GNU Go's and yours).
1754 However, if you are the last mover, undo only one move.
1755 Regardless, after undoing, it is your turn to play again."
1757 (gnugo--climb-towards-root 0))
1759 (defun gnugo-oops (&optional position)
1760 "Like `gnugo-undo-two-moves', but keep the undone moves.
1761 The kept moves become a sub-gametree (variation) when play resumes.
1762 Prefix arg means, instead, undo repeatedly up to and including
1763 the move which placed the stone at point, like `\\[gnugo-fancy-undo]'."
1765 (gnugo--climb-towards-root (unless position
1769 (defun gnugo-okay (&optional full)
1770 "Redo a pair of undone moves.
1771 Prefix arg means to redo all the undone moves."
1774 (let* ((tree (gnugo-get :sgf-gametree))
1775 (ends (gnugo--tree-ends tree))
1776 (monkey (gnugo-get :monkey)))
1777 (if (gnugo--no-regrets monkey ends)
1778 (message "Oop ack!")
1779 (let* ((as-pos (gnugo--as-pos-func))
1780 (mnum (gnugo--tree-mnum tree))
1781 (mem (aref monkey 0))
1782 (bidx (aref monkey 1))
1783 (end (aref ends bidx))
1784 (ucolor (gnugo-get :user-color))
1785 (uprop (gnugo--prop<-color ucolor)))
1786 (cl-flet ((mvno (node) (gethash node mnum)))
1790 (+ 2 (mvno (car mem))))
1791 with (node move todo)
1795 move (gnugo--move-prop node))
1796 (when (and move (>= ok (mvno node)))
1797 (let ((userp (eq uprop (car move))))
1799 (funcall as-pos (cdr move)))
1801 until (eq mem (cdr ls))
1804 for (userp pos) in todo
1806 (gnugo-push-move userp pos)
1810 (defun gnugo-display-final-score (&optional comment)
1811 "Display final score and other info in another buffer (when game over).
1812 If the game is still ongoing, Emacs asks if you wish to stop play (by
1813 making sure two \"pass\" moves are played consecutively, if necessary).
1814 Also, add the `:RE' SGF property to the root node of the game tree.
1815 Prefix arg COMMENT means to also attach the text (slightly compacted)
1816 to the last move, as a comment."
1818 (let ((game-over (gnugo-get :game-over)))
1819 (unless (or game-over
1820 (and (not (gnugo-get :waiting))
1821 (y-or-n-p "Game still in play. Stop play now? ")))
1822 (user-error "Sorry, game still in play"))
1826 (message "Playing PASS for %s ..."
1827 (gnugo-get (if userp :user-color :gnugo-color)))
1829 (gnugo-push-move userp "PASS")))
1834 (let ((b= " Black = ")
1836 (res (when (gnugo--resignp (gnugo-move-history 'car))
1837 (gnugo-get :last-mover)))
1841 (format "%s wins.\n"
1842 (substring (if (= ?b (aref res 0)) w= b=)
1844 "The game is over.\n"
1845 (format "Resignation by %s.\n" res))
1846 result (concat (upcase (substring (gnugo-other res) 0 1))
1848 (message "Computing final score ...")
1849 (let* ((g-over (gnugo-get :game-over))
1850 (live (cdr (assq 'live g-over)))
1851 (dead (cdr (assq 'dead g-over)))
1852 (seed (gnugo-get :scoring-seed))
1853 (terr-q (format "final_status_list %%s_territory %d" seed))
1856 (b-terr (gnugo--count-query terr-q "black"))
1857 (w-terr (gnugo--count-query terr-q "white"))
1858 (b-capt (string-to-number (gnugo-get :black-captures)))
1859 (w-capt (string-to-number (gnugo-get :white-captures)))
1860 (komi (gnugo--root-prop :KM)))
1861 (setq blurb (list "The game is over. Final score:\n")
1862 result (gnugo-query "final_score %d" seed))
1863 (cond ((string= "Chinese" (gnugo--root-prop :RU))
1864 (dolist (group live)
1865 (cl-incf (if (gnugo--blackp (caar group))
1868 (length (cdr group))))
1869 (dolist (group dead)
1870 (cl-incf (if (gnugo--blackp (caar group))
1873 (length (cdr group))))
1874 (push (format "%s%d %s = %3.1f\n" b= b-terr terr b-terr) blurb)
1875 (push (format "%s%d %s + %3.1f %s = %3.1f\n" w=
1876 w-terr terr komi 'komi (+ w-terr komi))
1879 (dolist (group dead)
1880 (cl-incf (if (gnugo--blackp (caar group))
1883 (* 2 (length (cdr group)))))
1884 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1889 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1893 (+ w-terr w-capt komi))
1895 (push (if (string= "0" result)
1896 "The game is a draw.\n"
1897 (format "%s wins by %s.\n"
1898 (substring (if (= ?B (aref result 0)) b= w=) 3 8)
1899 (substring result 2)))
1901 (message "Computing final score ... done")))
1903 (let ((beg (gnugo-get :game-start-time))
1904 (end (gnugo-get :game-end-time)))
1908 ((yep (pretty moment)
1909 (push (format-time-string
1910 (concat pretty ": %F %T %z\n")
1913 (yep "Game start" beg)
1915 (setq blurb (apply 'concat (nreverse blurb)))
1916 (gnugo--set-root-prop :RE result)
1918 (let ((node (car (aref (gnugo-get :monkey) 0))))
1920 (delq (assq :C node) node)
1922 (with-temp-buffer ; lame
1924 (when (search-backward "\n\nGame start:" nil t)
1925 (delete-region (point) (point-max)))
1926 (cl-flet ((rep (old new)
1927 (goto-char (point-min))
1928 (while (search-forward old nil t)
1929 (replace-match new))))
1930 (rep "The game is over. " "")
1931 (rep "territory" "T")
1932 (rep "captures" "C")
1935 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
1939 (defun gnugo-quit ()
1940 "Kill the current buffer, assumed to be in GNUGO Board mode, maybe.
1941 If the game is not over, ask for confirmation first."
1943 (if (or (gnugo-get :game-over)
1944 (y-or-n-p "Quit? "))
1946 (message "(not quitting)")))
1948 (defun gnugo-leave-me-alone ()
1949 "Kill the current buffer unconditionally."
1953 (defun gnugo-fancy-undo (count)
1954 "Rewind the game tree in various ways.
1955 Prefix arg COUNT means to undo that many moves.
1956 Otherwise, undo repeatedly up to and including the move
1957 which placed the stone at point."
1959 (gnugo--climb-towards-root
1964 (define-minor-mode gnugo-image-display-mode
1965 "If enabled, display the board using images.
1966 See function `display-images-p' and variable `gnugo-xpms'."
1968 ((gnugo-get :display-using-images)
1971 (unless (eq bool (gnugo-get :display-using-images))
1972 (gnugo-toggle-image-display)
1973 (save-excursion (gnugo-refresh))))))
1975 (defsubst gnugo--node-with-played-stone (pos &optional noerror)
1976 (car (gnugo--mem-with-played-stone pos noerror)))
1978 (defun gnugo-describe-position ()
1979 "Display the board position under cursor in the echo area.
1980 If there a stone at that position, also display its move number."
1982 (let* ((pos (gnugo-position)) ; do first (can throw)
1983 (node (gnugo--node-with-played-stone pos t)))
1987 (let* ((tree (gnugo-get :sgf-gametree))
1988 (mnum (gnugo--tree-mnum tree))
1989 (move-num (gethash node mnum)))
1990 (format " (move %d)" move-num)))
1993 (defun gnugo-switch-to-another ()
1994 "Switch to another GNU Go game buffer (if any)."
1997 for buf in (cdr (buffer-list))
1998 if (gnugo-board-buffer-p buf)
2001 (switch-to-buffer buf))
2002 finally do (message "(only one)")))
2004 (defun gnugo-comment (node comment)
2005 "Add to NODE a COMMENT (string) property.
2006 Called interactively, NODE is the one corresponding to the
2007 stone at point, and any previous comment is inserted as the
2008 initial-input (see `read-string').
2010 If COMMENT is nil or the empty string, remove the property entirely."
2012 (let* ((pos (gnugo-position))
2013 (node (gnugo--node-with-played-stone pos)))
2015 (read-string (format "Comment for %s: "
2016 (gnugo-describe-position))
2017 (cdr (assq :C node))))))
2018 (setq node (delq (assq :C node) node))
2019 (unless (zerop (length comment))
2020 (gnugo--decorate node :C comment)))
2022 (defun gnugo--struggle (prop updn)
2023 (unless (eq updn (gnugo--:karma prop)) ; drudgery avoidance
2024 (let ((color (gnugo-get prop)))
2029 (let ((waiting (gnugo-get :waiting)))
2030 (when (and waiting (string= color (car waiting)))
2031 (gnugo--rename-buffer-portion)
2033 ;; heuristic: Warp only if it appears
2034 ;; that the user is "following along".
2036 (string= (gnugo-position)
2037 (gnugo-move-history 'bpos color)))
2039 (gnugo--display-suggestion color "forthcoming")
2041 (let* ((wheel (gnugo-get :wheel))
2043 (karma (cdr wheel)))
2044 (when (timerp timer)
2045 (cancel-timer timer))
2047 (setcdr wheel (setq karma
2048 ;; walk to the west, fly to the east,
2049 ;; talk and then rest, cry and then feast.
2050 ;; 99 beers down thirsty throats sloshed?
2051 ;; 500 years under pink mountains squashed?
2052 ;; balk with the best, child now re-creased!
2055 (delete color karma))))
2056 (gnugo--dance-dance karma))
2057 (gnugo--turn-the-wheel t))))
2059 (define-minor-mode gnugo-assist-mode
2060 "If enabled (\"Assist\" in mode line), GNU Go plays for you.
2061 When disabling, if GNU Go has already started thinking of
2062 a move to play for you, the thinking is not cancelled but instead
2063 transformed into a move suggestion (see `gnugo-request-suggestion')."
2065 ((gnugo--assist-state)
2068 (gnugo--struggle :user-color bool))))
2070 (define-minor-mode gnugo-zombie-mode
2071 "If enabled (\"Zombie\" in mode line), GNU Go lets you play for it.
2072 When disabling, if GNU Go has already started thinking of
2073 a move to play, the thinking is not cancelled but instead
2074 transformed into a move suggestion (see `gnugo-request-suggestion')."
2076 ((not (gnugo--:karma :gnugo-color))
2079 (gnugo--struggle :gnugo-color (not bool)))))
2081 ;;;---------------------------------------------------------------------------
2082 ;;; Command properties and gnugo-command
2084 ;; GTP commands entered by the user are never issued directly to GNU Go;
2085 ;; instead, their behavior and output are controlled by the property
2086 ;; `:gnugo-gtp-command-spec' hung off of each (interned/symbolic) command.
2087 ;; The value of this property is a sub-plist, w/ sub-properties as follows:
2089 ;; :full -- completely interpret the command string; the value is a
2090 ;; func that takes the list of words derived from splitting the
2091 ;; command string (minus the command) and handles everything.
2093 ;; :output -- either a keyword specifying the preferred output method:
2094 ;; :message -- show output in minibuffer
2095 ;; :discard -- sometimes you just don't care;
2096 ;; or a function that takes one arg, the output string, and
2097 ;; handles it completely. default is to switch to buffer
2098 ;; "*gnugo command output*" if the output has a newline,
2099 ;; otherwise use `message'.
2101 ;; :post-thunk -- run after output processing (at the very end).
2103 (defun gnugo-command (command)
2104 "Send the Go Text Protocol COMMAND (a string) to GNU Go.
2105 Output and Emacs behavior depend on which command is given (some
2106 commands are handled completely by Emacs w/o using the subprocess;
2107 some commands have their output displayed in specially prepared
2108 buffers or in the echo area; some commands are instrumented to do
2109 gnugo.el-specific housekeeping).
2111 For example, for the command \"help\", Emacs visits the
2112 GTP command reference info page.
2114 NOTE: At this time, GTP command handling specification is still
2115 incomplete. Thus, some commands WILL confuse gnugo.el."
2116 (interactive "sCommand: ")
2117 (if (string= "" command)
2118 (message "(no command given)")
2119 (let* ((split (split-string command))
2120 (cmd (intern (car split)))
2121 (spec (get cmd :gnugo-gtp-command-spec))
2122 (full (plist-get spec :full)))
2124 (funcall full (cdr split))
2125 (message "Doing %s ..." command)
2126 (let* ((ans (gnugo--q command))
2127 (where (plist-get spec :output)))
2128 (if (string-match "unknown.command" ans)
2130 (cond ((functionp where) (funcall where ans))
2131 ((eq :discard where) (message ""))
2132 ((or (eq :message where)
2133 (not (string-match "\n" ans)))
2135 (t (switch-to-buffer "*gnugo command output*")
2138 (message "Doing %s ... done." command)))
2139 (let ((thunk (plist-get spec :post-thunk)))
2140 (when thunk (funcall thunk)))))))))
2142 ;;;---------------------------------------------------------------------------
2143 ;;; Major mode for interacting with a GNUGO subprocess
2145 (define-derived-mode gnugo-board-mode special-mode "GNUGO Board"
2146 "Major mode for playing GNU Go.
2147 Entering this mode runs the normal hook `gnugo-board-mode-hook'.
2148 In this mode, keys do not self insert."
2149 (buffer-disable-undo) ; todo: undo undo undoing
2150 (setq font-lock-defaults '(gnugo-font-lock-keywords t)
2152 (add-hook 'kill-buffer-hook 'gnugo-cleanup nil t)
2153 (set (make-local-variable 'gnugo-state)
2154 (gnugo--mkht :size (1- 42)))
2155 (set (make-local-variable 'gnugo-btw) nil)
2156 (add-to-list 'minor-mode-alist '(gnugo-btw gnugo-btw))
2157 (gnugo-put :highlight-last-move-spec
2158 (gnugo-put :default-highlight-last-move-spec '("(" -1 nil)))
2159 (gnugo-put :paren-ov (cons (make-overlay 1 1)
2160 (let ((ov (make-overlay 1 1)))
2161 (overlay-put ov 'display ")")
2163 (gnugo-put :mul '(1 . 1))
2164 (gnugo-put :obarray (make-vector 31 nil))
2165 (add-to-invisibility-spec :nogrid))
2167 ;;;---------------------------------------------------------------------------
2171 (defun gnugo (&optional new-game)
2172 "Run gnugo in a buffer, or resume a game in progress.
2173 If there is already a game in progress you may resume it instead
2174 of starting a new one. Prefix arg means skip the game-in-progress
2175 check and start a new game straight away.
2177 Before starting, Emacs queries you for additional command-line
2178 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2180 Note that specifying \"--infile FILENAME\" (or, \"-l FILENAME\")
2181 silently clobbers certain other options, such as \"--color\".
2182 For details, see info node `(gnugo) Invoking GNU Go'.
2184 \\<gnugo-board-mode-map>
2185 To play, use \\[gnugo-move] to place a stone or \\[gnugo-pass] to pass.
2186 See `gnugo-board-mode' for a full list of commands."
2188 (let* ((all (let (acc)
2189 (dolist (buf (buffer-list))
2190 (when (gnugo-board-buffer-p buf)
2191 (push (cons (buffer-name buf) buf) acc)))
2194 (if (and (not new-game)
2196 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2197 (if (= 1 n) "" "s"))))
2202 (let ((sel (completing-read "Which one? " all nil t)))
2203 (if (string= "" sel)
2205 (assoc sel all))))))
2207 (unless (executable-find gnugo-program)
2208 (user-error "Invalid `gnugo-program': %S" gnugo-program))
2209 ;; set up a new board
2210 (switch-to-buffer (generate-new-buffer "(Uninitialized GNUGO Board)"))
2212 (let* ((filename nil)
2213 (user-color "black")
2215 with ls = (split-string
2216 ;; todo: grok ‘gnugo --help’; completion
2219 (car gnugo-option-history)
2220 'gnugo-option-history))
2223 (let ((arg (pop ls)))
2227 (warn "%s %s ignored" opt fn)
2228 (setq filename fn))))
2230 ((string= "--color" arg)
2233 ;; Unfortunately, GTP does not provide
2234 ;; a way to query the user color, so
2235 ;; we must resort to this weirdness.
2239 ((string= "--infile" arg)
2240 (ex "--infile" (pop ls)))
2241 ((string-match "^-l" arg)
2242 (ex "-l" (if (< 2 (length arg))
2245 (t (push arg ok)))))
2246 finally return (nreverse ok)))
2247 (proc (apply 'start-process "gnugo"
2250 "--mode" "gtp" "--quiet"
2252 root board-size handicap komi)
2253 (gnugo-put :user-color user-color)
2254 (gnugo-put :proc proc)
2255 (set-process-sentinel proc 'gnugo-sentinel)
2256 ;; Emacs is too protective sometimes, blech.
2257 (set-process-query-on-exit-flag proc nil)
2258 (gnugo-put :diamond (substring (process-name proc) 5))
2259 (gnugo-put :gnugo-color (gnugo-other user-color))
2261 (gnugo-read-sgf-file (expand-file-name filename))
2263 ((r! (&rest plist) (apply 'gnugo--decorate root plist)))
2265 (setq root (gnugo--root-node
2266 (gnugo--plant-and-climb
2267 (gnugo/sgf-create "(;FF[4]GM[1])" t)))
2268 komi (gnugo--nquery "get_komi")
2269 handicap (gnugo--nquery "get_handicap")
2270 board-size (gnugo--nquery "query_boardsize")))
2271 ;; Work around a GNU Go 3.8 (and possibly earlier/later)
2272 ;; bug whereby GTP command ‘get_handicap’ fails to return
2273 ;; the N set by ‘--handicap N’ on the command line.
2274 (let ((actually (member "--handicap" args)))
2275 ;; Checking ‘(zerop handicap)’ first is not strictly
2276 ;; necessary; it represents a hope that some day GNU Go
2277 ;; will DTRT (or provide rationale for this weird behavior)
2278 ;; and become worthy of our trust.
2279 (when (and (zerop handicap) actually)
2280 (setq handicap (string-to-number (cadr actually)))))
2282 :DT (format-time-string "%F")
2283 :RU (if (member "--chinese-rules" args)
2287 (let ((ub (gnugo--blackp user-color)))
2288 (r! (if ub :PW :PB) (concat "GNU Go " (gnugo-query "version"))
2289 (if ub :PB :PW) (user-full-name)))
2290 (unless (zerop handicap)
2292 :AB (mapcar (gnugo--as-cc-func)
2293 (gnugo-lsquery "fixed_handicap %d"
2295 (gnugo-put :waiting-start (current-time))
2297 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2298 (gnugo-get :center-position)))
2300 (gnugo-put :game-start-time (current-time))
2301 (let ((g (gnugo-get :gnugo-color))
2302 (n (or (gnugo--root-prop :HA) 0))
2303 (u (gnugo-get :user-color)))
2304 (unless (gnugo-get :last-mover)
2305 (gnugo-put :last-mover
2306 (if (or (and (gnugo--blackp u) (< 1 n))
2307 (and (gnugo--blackp g) (< n 2)))
2310 (let ((karma (list g)))
2311 (gnugo-put :wheel (cons nil karma))
2312 (gnugo--dance-dance karma))
2313 (run-hooks 'gnugo-start-game-hook)
2314 (gnugo--turn-the-wheel)))))
2316 ;;;---------------------------------------------------------------------------
2317 ;;; Load-time actions
2319 (unless (get 'help :gnugo-gtp-command-spec)
2321 ((sget (x) (get x :gnugo-gtp-command-spec))
2322 (jam (cmd prop val) (put cmd :gnugo-gtp-command-spec
2323 (plist-put (sget cmd) prop val)))
2324 (validpos (s &optional go)
2325 (let ((pos (upcase s)))
2327 with size = (gnugo-get :SZ)
2328 for c across (funcall (gnugo--as-cc-func)
2330 do (let ((norm (- c ?a)))
2331 (unless (and (< -1 norm)
2333 (user-error "Invalid position: %s"
2336 (gnugo-goto-pos pos))
2338 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2341 (jam cmd (car ls) (cadr ls))
2342 (setq ls (cddr ls)))))))
2343 (cl-macrolet ((deffull (who &body body)
2344 (declare (indent 1))
2345 `(defgtp ',who :full (lambda (sel)
2349 (info "(gnugo)GTP command reference")
2350 (when sel (setq sel (intern (car sel))))
2351 (let (buffer-read-only pad cur spec output found)
2353 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2354 (goto-char (point-min))
2356 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2359 (setq pad (make-string (- (match-beginning 1)
2360 (match-beginning 0))
2364 (get (setq cur (intern (match-string 1)))
2365 :gnugo-gtp-command-spec))
2367 (note "handles this command completely"))
2368 (when (setq output (plist-get spec :output))
2369 (if (functionp output)
2370 (note "handles the output specially")
2372 (:discard (note "discards the output"))
2373 (:message (note "displays the output in the echo area")))))
2375 (setq found (make-marker))
2376 (set-marker found (match-beginning 0))))))
2377 (cond (found (goto-char found) (set-marker found nil))
2379 (t (message "(no such command: %s)" sel)))))
2381 (deffull final_score
2382 ;; Explicit ignorance avoids byte-compiler warning.
2384 (gnugo-display-final-score))
2390 :post-thunk (lambda ()
2391 (gnugo--unclose-game)
2392 (gnugo--forget :last-mover)
2394 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2398 (gnugo-read-sgf-file (car sel)))
2400 (deffull (undo gg-undo)
2401 (gnugo--climb-towards-root
2404 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2405 (t (validpos (car sel) t)))))))))
2410 ;;;---------------------------------------------------------------------------
2411 ;;; The remainder of this file defines a simplified SGF-handling library.
2412 ;;; When/if it should start to attain generality, it should be split off into
2413 ;;; a separate file (probably named sgf.el) w/ funcs and vars renamed sans the
2414 ;;; "gnugo/" prefix.
2416 (defconst gnugo/sgf-*r4-properties*
2417 '((AB "Add Black" setup list stone)
2418 (AE "Add Empty" game list point)
2419 (AN "Annotation" game simpletext)
2420 (AP "Application" root (simpletext . simpletext))
2421 (AR "Arrow" - list (point . point))
2422 (AS "Who adds stones" - simpletext) ; (LOA)
2423 (AW "Add White" setup list stone)
2424 (B "Black" move move)
2425 (BL "Black time left" move real)
2426 (BM "Bad move" move double)
2427 (BR "Black rank" game simpletext)
2428 (BT "Black team" game simpletext)
2429 (C "Comment" - text)
2430 (CA "Charset" root simpletext)
2431 (CP "Copyright" game simpletext)
2432 (CR "Circle" - list point)
2433 (DD "Dim points" - elist point) ; (inherit)
2434 (DM "Even position" - double)
2435 (DO "Doubtful" move none)
2436 (DT "Date" game simpletext)
2437 (EV "Event" game simpletext)
2438 (FF "Fileformat" root [number (1 . 4)])
2439 (FG "Figure" - (or none (number . simpletext)))
2440 (GB "Good for Black" - double)
2441 (GC "Game comment" game text)
2442 (GM "Game" root [number (1 . 20)])
2443 (GN "Game name" game simpletext)
2444 (GW "Good for White" - double)
2445 (HA "Handicap" game number) ; (Go)
2446 (HO "Hotspot" - double)
2447 (IP "Initial pos." game simpletext) ; (LOA)
2448 (IT "Interesting" move none)
2449 (IY "Invert Y-axis" game simpletext) ; (LOA)
2450 (KM "Komi" game real) ; (Go)
2452 (LB "Label" - list (point . simpletext))
2453 (LN "Line" - list (point . point))
2454 (MA "Mark" - list point)
2455 (MN "set move number" move number)
2456 (N "Nodename" - simpletext)
2457 (OB "OtStones Black" move number)
2458 (ON "Opening" game text)
2459 (OT "Overtime" game simpletext)
2460 (OW "OtStones White" move number)
2461 (PB "Player Black" game simpletext)
2462 (PC "Place" game simpletext)
2463 (PL "Player to play" setup color)
2464 (PM "Print move mode" - number) ; (inherit)
2465 (PW "Player White" game simpletext)
2466 (RE "Result" game simpletext)
2467 (RO "Round" game simpletext)
2468 (RU "Rules" game simpletext)
2469 (SE "Markup" - point) ; (LOA)
2470 (SL "Selected" - list point)
2471 (SO "Source" game simpletext)
2472 (SQ "Square" - list point)
2473 (ST "Style" root [number (0 . 3)])
2474 (SU "Setup type" game simpletext) ; (LOA)
2475 (SZ "Size" root (or number (number . number)))
2476 (TB "Territory Black" - elist point) ; (Go)
2477 (TE "Tesuji" move double)
2478 (TM "Timelimit" game real)
2479 (TR "Triangle" - list point)
2480 (TW "Territory White" - elist point) ; (Go)
2481 (UC "Unclear pos" - double)
2482 (US "User" game simpletext)
2484 (VW "View" - elist point) ; (inherit)
2485 (W "White" move move)
2486 (WL "White time left" move real)
2487 (WR "White rank" game simpletext)
2488 (WT "White team" game simpletext)
2489 (LT "Lose on time" setup simpletext))
2490 ;; r4-specific notes
2491 ;; - changed: DT FG LB RE RU SZ
2492 ;; - added: AP AR AS DD IP IY LN OT PM SE SQ ST SU VW
2493 "List of SGF[4] properties, each of the form (PROP NAME CONTEXT SPEC...).")
2495 (defun gnugo/sgf-create (file-or-data &optional data-p)
2496 "Return the SGF[4] collection parsed from FILE-OR-DATA.
2497 FILE-OR-DATA is a file name or SGF[4] data.
2498 Optional arg DATA-P non-nil means FILE-OR-DATA is
2499 a string containing SGF[4] data.
2500 A collection is a list of gametrees, each a vector of four elements:
2502 ENDS -- a vector of node lists, with shared tails
2503 (last element of all the lists is the root node)
2505 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2506 have a move number of the previous \"move\" node (or zero)
2508 ROOT -- the root node"
2509 ;; Arg names inspired by `create-image', despite -P being frowned upon.
2510 (let ((keywords (or (get 'gnugo/sgf-*r4-properties* :keywords)
2511 (put 'gnugo/sgf-*r4-properties* :keywords
2512 (mapcar (lambda (full)
2514 (intern (format ":%s" (car full)))))
2515 gnugo/sgf-*r4-properties*))))
2516 (specs (or (get 'gnugo/sgf-*r4-properties* :specs)
2517 (put 'gnugo/sgf-*r4-properties* :specs
2518 (mapcar (lambda (full)
2519 (cons (car full) (cl-cdddr full)))
2520 gnugo/sgf-*r4-properties*))))
2523 ((sw () (skip-chars-forward " \t\n"))
2524 (x (end preserve-whitespace)
2527 (:end (lambda (char) (= ?\] char)))
2528 (:mid (lambda (char) (= ?\: char)))
2529 (t (lambda (char) (or (= ?\: char)
2532 (while (not (funcall endp (setq c (following-char))))
2538 ((unless preserve-whitespace
2539 (looking-at "\\s-+"))
2540 (delete-region (point) (match-end 0))
2542 (t (forward-char 1))))
2543 (buffer-substring-no-properties beg (point))))
2544 (one (type end) (let ((s (progn
2546 (x end (eq 'text type)))))
2549 ;; blech, begone bu"tt"-ugly blatherings
2550 ;; (but bide brobdingnagian boards)...
2551 (if (and (string= "tt" s)
2556 ((simpletext color) s)
2557 ((number real double) (string-to-number s))
2560 (t (error "Unhandled type: %S" type)))))
2561 (val (spec) (cond ((symbolp spec)
2564 ;; todo: check range here.
2565 (one (aref spec 0) :end))
2566 ((eq 'or (car spec))
2567 (let ((v (one (cadr spec) t)))
2568 (if (= ?\] (following-char))
2571 ;; todo: this assumes `spec' has the form
2572 ;; (or foo (foo . bar))
2573 ;; i.e., foo is not rescanned. e.g., `SZ'.
2574 ;; probably this assumption is consistent
2575 ;; w/ the SGF authors' desire to make the
2576 ;; parsing easy, but you never know...
2577 (cons v (one (cl-cdaddr spec) :end)))))
2578 (t (cons (one (car spec) :mid)
2579 (one (cdr spec) :end)))))
2580 (short (who) (when (eobp)
2581 (error "Unexpected EOF while reading %s" who)))
2582 (atvalp () (= ?\[ (following-char)))
2583 (PROP () (let (name spec ltype)
2584 (sw) (short 'property)
2585 (when (looking-at "[A-Z]")
2586 (setq name (read (current-buffer))
2587 spec (cdr (assq name specs)))
2590 (cdr (assq name keywords))
2591 (prog1 (if (= 1 (length spec))
2593 (unless (memq (setq ltype (car spec))
2595 (error "Bad spec: %S" spec))
2596 (if (and (eq 'elist ltype) (sw)
2599 (let ((type (cadr spec))
2601 (while (and (sw) (atvalp)
2602 (setq mo (val type)))
2607 (forward-char 1))))))
2608 (morep () (and (sw) (not (eobp))))
2609 (seek (c) (and (morep) (= c (following-char))))
2610 (seek-into (c) (when (seek c)
2613 (NODE () (when (seek-into ?\;)
2616 while (setq prop (PROP))
2618 (when (eq :SZ (car prop))
2619 (setq SZ (cdr prop)))
2628 (puthash node (+ (if (gnugo--move-prop node)
2631 (gethash prev mnum 0))
2636 (if (not (seek ?\())
2642 append (TREE ls mnum)))
2646 (insert-file-contents file-or-data)
2647 (insert file-or-data)
2648 (goto-char (point-min)))
2651 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2652 (ends (TREE nil mnum))
2653 (root (car (last (car ends)))))
2654 (vector (apply 'vector ends)
2658 (defun gnugo/sgf-write-file (collection filename)
2659 (let ((aft-newline-appreciated '(:AP :GN :PB :PW :HA :KM :RU :RE))
2660 (specs (mapcar (lambda (full)
2661 (cons (intern (format ":%s" (car full)))
2663 gnugo/sgf-*r4-properties*))
2666 ((esc (composed fmt arg)
2667 (mapconcat (lambda (c)
2669 ;; ‘?\[’ is not strictly required
2670 ;; but neither is it forbidden.
2671 ((?\[ ?\] ?\\) (format "\\%c" c))
2672 (?: (concat (if composed "\\" "") ":"))
2674 (string-to-list (format fmt arg))
2676 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2677 (>>two (v) (insert "["
2678 (esc t "%s" (car v))
2680 (esc t "%s" (cdr v))
2682 (>>nl () (cond ((memq name aft-newline-appreciated)
2684 ((< 60 (current-column))
2692 (insert (substring (symbol-name name) 1))
2695 (setq spec (cdr (assq name specs)))
2699 (let ((>> (if (consp (cadr spec))
2702 (dolist (little-v v)
2704 (funcall >> little-v)
2712 initially (insert ";")
2716 (unless (zerop (current-column))
2720 (funcall (if (gnugo--nodep x)
2726 (dolist (tree collection)
2728 (let ((ht (gnugo--mkht))
2729 (leaves (append (gnugo--tree-ends tree) nil)))
2733 with rh ; rectified history
2734 with bp ; branch point
2736 until (setq bp (gethash node ht))
2738 (push node rh) ; good for now: ½τ
2742 ;; first run: main line
2744 ;; subsequent runs: grafts (value discarded)
2746 ;; Maintain order of ‘leaves’.
2747 (let ((was (cdr bp)))
2748 (if (gnugo--nodep (car was))
2752 (setq tree (hang (pop leaves)))
2753 (mapc #'hang leaves)
2756 (write-file filename)))))
2758 ;;; gnugo.el ends here