]> code.delx.au - gnu-emacs-elpa/blob - packages/gnugo/gnugo.el
Fix some quoting problems in doc strings
[gnu-emacs-elpa] / packages / gnugo / gnugo.el
1 ;;; gnugo.el --- play GNU Go in a buffer -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2014 Free Software Foundation, Inc.
4
5 ;; Author: Thien-Thi Nguyen <ttn@gnu.org>
6 ;; Maintainer: Thien-Thi Nguyen <ttn@gnu.org>
7 ;; Version: 3.0.0
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/
11
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.
16
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.
21
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/>.
24
25 ;;; Commentary:
26
27 ;; Playing
28 ;; -------
29 ;;
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.
35 ;;
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.
40 ;;
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).
46 ;;
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.
52 ;;
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. :-)
58 ;;
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
61 ;; the program.
62 ;;
63 ;;
64 ;; Meta-Playing (aka Customizing)
65 ;; ------------------------------
66 ;;
67 ;; Customization is presently limited to
68 ;; vars: `gnugo-program'
69 ;; `gnugo-animation-string'
70 ;; `gnugo-mode-line'
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'
80 ;;
81 ;;
82 ;; Meta-Meta-Playing (aka Hacking)
83 ;; -------------------------------
84 ;;
85 ;; <http://git.sv.gnu.org/cgit/emacs/elpa.git/tree/packages/gnugo/>
86
87 ;;; Code:
88
89 (require 'cl-lib) ; use the source luke!
90 (require 'time-date) ; for `time-subtract'
91
92 ;;;---------------------------------------------------------------------------
93 ;;; Political arts
94
95 (defconst gnugo-version "3.0.0"
96 "Version of gnugo.el currently loaded.
97 This follows a MAJOR.MINOR.PATCH scheme.")
98
99 ;;;---------------------------------------------------------------------------
100 ;;; Variables for the uninquisitive programmer
101
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:
106 --mode gtp --quiet
107 For more information on GTP and GNU Go, please visit:
108 <http://www.gnu.org/software/gnugo>")
109
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)
122 (mapc (lambda (pair)
123 (define-key map (car pair) (cdr pair)))
124 '(("?" . describe-mode)
125 ("S" . gnugo-request-suggestion)
126 ("\C-m" . gnugo-move)
127 (" " . gnugo-move)
128 ("P" . gnugo-pass)
129 ("R" . gnugo-resign)
130 ("q" . gnugo-quit)
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)
136 ("o" . gnugo-oops)
137 ("O" . gnugo-okay)
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)
163 ;; mouse
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)))
169 map)
170 "Keymap for GNUGO Board mode.")
171
172 (defvar gnugo-board-mode-hook nil
173 "Hook run when entering GNUGO Board mode.")
174
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'.")
179
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.")
186
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...
200 yada yada yada))
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.")
205
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)
212 ~m move number
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.")
217
218 (defvar gnugo-X-face 'font-lock-string-face
219 "Name of face to use for X (black) stones.")
220
221 (defvar gnugo-O-face 'font-lock-builtin-face
222 "Name of face to use for O (white) stones.")
223
224 (defvar gnugo-grid-face 'default
225 "Name of face to use for the grid (A B C ... 1 2 3 ...).")
226
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.")
239
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).
244
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
250
251 LOCATION is an integer encoding edge, corner, or center:
252 1 2 3
253 4 5 6
254 7 8 9
255 For instance, 4 means \"left edge\", 9 means \"bottom right\".
256
257 There is only one location for hoshi: center. The other five
258 types each have all possible locations. So (+ 1 (* 9 5)) => 46.
259
260 The value can also be a function (satisfying `functionp') that
261 takes one arg, the size of the board, and returns the appropriate
262 list of forms.")
263
264 ;;;---------------------------------------------------------------------------
265 ;;; Variables for the inquisitive programmer
266
267 (defconst gnugo-font-lock-keywords
268 '(("X" . gnugo-X-face)
269 ("O" . gnugo-O-face))
270 "Font lock keywords for `gnugo-board-mode'.")
271
272 (defvar gnugo-option-history nil)
273
274 (defvar gnugo-state nil) ; hint: C-c C-p
275
276 (defvar gnugo-btw nil)
277
278 ;;;---------------------------------------------------------------------------
279 ;;; Support functions
280
281 (defsubst gnugo--mkht (&rest etc)
282 (apply 'make-hash-table :test 'eq etc))
283
284 (defsubst gnugo--compare-strings (s1 beg1 s2 beg2)
285 (compare-strings s1 beg1 nil s2 beg2 nil))
286
287 (defun gnugo-put (key value)
288 "Associate move/game/board-specific property KEY with VALUE.
289
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\".
298
299 :proc -- subprocess named \"gnugo\", \"gnugo<1>\" and so forth
300
301 :diamond -- the part of the subprocess name after \"gnugo\", may be \"\"
302
303 :game-over -- nil until game over at which time its value is set to
304 the alist ((live GROUP ...) (dead GROUP ...))
305
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
309
310 :sgf-gametree -- one of the gametrees in :sgf-collection
311
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\"
315
316 :gnugo-color -- either \"black\" or \"white\"
317 :user-color
318 :last-mover
319
320 :last-waiting -- seconds and time value, respectively; see `gnugo-push-move'
321 :waiting-start
322
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!)
328
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)
332
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'
338
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
341
342 :last-user-bpos -- board position; keep the hapless human happy
343
344 As things stabilize probably more info will be added to this docstring."
345 (declare (indent 1))
346 (puthash key value gnugo-state))
347
348 (defun gnugo-get (key)
349 "Return the move/game/board-specific value for KEY.
350 See `gnugo-put'."
351 (gethash key gnugo-state))
352
353 (defun gnugo--forget (&rest keys)
354 (dolist (key keys)
355 (remhash key gnugo-state)))
356
357 (defsubst gnugo--tree-mnum (tree)
358 (aref tree 1))
359
360 (defsubst gnugo--tree-ends (tree)
361 (aref tree 0))
362
363 (defsubst gnugo--set-tree-ends (tree ls)
364 (aset tree 0 (apply 'vector ls))
365 (gnugo--tree-ends tree))
366
367 (defun gnugo--root-node (&optional tree)
368 (aref (or tree (gnugo-get :sgf-gametree))
369 2))
370
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."
374 (interactive)
375 (let ((buf (current-buffer))
376 (d (gnugo-get :diamond))
377 (acc (cl-loop
378 for key being the hash-keys of gnugo-state
379 using (hash-values val)
380 collect (cons key
381 (cl-case key
382 ((:xpms)
383 (format "hash: %X (%d images)"
384 (sxhash val)
385 (length val)))
386 (:sgf-collection
387 (length val))
388 (:sgf-gametree
389 (list (hash-table-count
390 (gnugo--tree-mnum val))
391 (gnugo--root-node val)
392 (gnugo--tree-ends val)))
393 (:monkey
394 (let ((mem (aref val 0)))
395 (list (aref val 1)
396 (car mem))))
397 (t val))))))
398 (switch-to-buffer (get-buffer-create
399 (format "%s*GNUGO Board Properties*"
400 d)))
401 (erase-buffer)
402 (emacs-lisp-mode)
403 (setq truncate-lines t)
404 (save-excursion
405 (pp acc
406 (current-buffer))
407 (goto-char (point-min))
408 (let ((rx (format "overlay from \\([0-9]+\\).+\n%s\\s-+"
409 (if (string= "" d)
410 ".+\n"
411 ""))))
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))))
418
419 (defun gnugo-board-buffer-p (&optional buffer)
420 "Return non-nil if BUFFER is a GNUGO Board buffer."
421 (eq 'gnugo-board-mode
422 (buffer-local-value
423 'major-mode
424 (or buffer (current-buffer)))))
425
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)))))
430
431 (defsubst gnugo--blackp (string)
432 (string= "black" string))
433
434 (defun gnugo-other (color)
435 (if (gnugo--blackp color) "white" "black"))
436
437 (defun gnugo-current-player ()
438 "Return the current player, either \"black\" or \"white\"."
439 (gnugo-other (gnugo-get :last-mover)))
440
441 (defsubst gnugo--prop<-color (color)
442 (if (gnugo--blackp color) :B :W))
443
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)
450 (gnugo-get :waiting)
451 (when color
452 (apply 'user-error
453 "%s -- please wait for \"(%s to play)\""
454 (if suggestion
455 (list "Still thinking"
456 color)
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")))
461
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
469 (list " [%s ("
470 (propertize (car (split-string string))
471 'face 'font-lock-warning-face)
472 ")]"))
473 (when (eq proc (gnugo-get :proc))
474 (gnugo--forget :proc))))))))
475
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"))
482
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)))
489 (when slow
490 (user-error "Sorry, still waiting for %s to %s"
491 (car slow) (if (cdr slow)
492 "receive a suggestion"
493 "play")))
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)
499 string)))
500 (process-put proc :srs full)
501 (unless (numberp (gnugo--compare-strings
502 full (max 0 (- (length full)
503 2))
504 "\n\n" nil))
505 (process-put proc :incomplete nil))))
506 (if (null args)
507 fmt
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 ""))))
513
514 (defsubst gnugo--no-worries (string)
515 (= ?= (aref string 0)))
516
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))
521 (substring ans 2)))
522
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)
529 2))
530
531 (defun gnugo--nquery (cmd)
532 (string-to-number (gnugo-query cmd)))
533
534 (defun gnugo-lsquery (message-format &rest args)
535 (split-string (apply 'gnugo-query message-format args)))
536
537 (defsubst gnugo--count-query (fmt &rest args)
538 (length (apply 'gnugo-lsquery fmt args)))
539
540 (defsubst gnugo--root-prop (prop &optional tree)
541 (cdr (assq prop (gnugo--root-node tree))))
542
543 (defun gnugo--set-root-prop (prop value &optional tree)
544 (let* ((root (gnugo--root-node tree))
545 (cur (assq prop root)))
546 (if cur
547 (setcdr cur value)
548 (push (cons prop value)
549 (cdr (last root))))))
550
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))))
556 (forward-char 1)
557 (forward-char (+ (if (= 32 (following-char)) 1 2)
558 (* 2 (- (let ((letter (aref pos 0)))
559 (if (> ?I letter)
560 letter
561 (1- letter)))
562 ?A)))))
563
564 (defun gnugo-f (id)
565 (intern (if (symbolp id)
566 (symbol-name id)
567 id)
568 (gnugo-get :obarray)))
569
570 (defun gnugo-yang (c)
571 (cdr (assq c '((?+ . hoshi)
572 (?. . empty)
573 (?X . (bmoku . bpmoku))
574 (?O . (wmoku . wpmoku))))))
575
576 (defun gnugo-yy (yin yang &optional momentaryp)
577 (gnugo-f (format "%d-%s"
578 yin (cond ((symbolp yang) yang)
579 (momentaryp (cdr yang))
580 (t (car yang))))))
581
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))
587 gnugo-xpms)))
588 (unless fresh
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)))
595 (mapc (lambda (yy)
596 (setcar (symbol-plist yy) act))
597 (or (gnugo-get :all-yy)
598 (gnugo-put :all-yy
599 (prog1 (mapcar (lambda (ent)
600 (let* ((k (car ent))
601 (yy (gnugo-yy (cdr k) (car k))))
602 (setplist yy `(not-yet ,(cdr ent)))
603 yy))
604 (gnugo-get :xpms))
605 (gnugo-put :imul
606 (image-size (get (gnugo-yy 5 (gnugo-yang ?+))
607 'not-yet)))))))
608 (setplist (gnugo-f 'ispc) (and new '(display (space :width 0))))
609 (gnugo-put :highlight-last-move-spec
610 (if new
611 `(,(lambda (p)
612 (get (gnugo-yy (get-text-property p 'gnugo-yin)
613 (get-text-property p 'gnugo-yang)
614 t)
615 'display))
616 0 delete-overlay)
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
623 (gnugo-get :imul)
624 '(1 . 1)))
625 (gnugo-put :display-using-images new)))
626
627 (define-minor-mode gnugo-grid-mode
628 "If enabled, display grid around the board."
629 :variable
630 ((not (memq :nogrid buffer-invisibility-spec))
631 .
632 (lambda (bool)
633 (funcall (if bool
634 'remove-from-invisibility-spec
635 'add-to-invisibility-spec)
636 :nogrid)
637 (save-excursion (gnugo-refresh)))))
638
639 (defun gnugo-propertize-board-buffer ()
640 (erase-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)
656 (forward-char 1)
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))
660 (edge (match-end 0))
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)))
666 (nR (- edge 1))
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)))
677 ((< other-edge p))
678 (let* ((position (format "%c%s" (aref "ABCDEFGHJKLMNOPQRST"
679 (truncate (- p edge) 2))
680 row))
681 (yin (let ((A-p (= edge p))
682 (Z-p (= (1- other-edge) p)))
683 (cond ((and top-p A-p) 1)
684 ((and top-p Z-p) 3)
685 ((and bot-p A-p) 7)
686 ((and bot-p Z-p) 9)
687 (top-p 2)
688 (bot-p 8)
689 (A-p 4)
690 (Z-p 6)
691 (t 5))))
692 (yang (gnugo-yang (char-after p))))
693 (add-text-properties p (1+ p)
694 `(gnugo-position
695 ,position
696 gnugo-yin
697 ,yin
698 gnugo-yang
699 ,yang
700 category
701 ,(gnugo-yy yin yang)
702 front-sticky
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))
711 :white-captures
712 :black-captures))
713 (beg (match-beginning 2))
714 (end (match-end 2)))
715 (put-text-property beg end :gnugo-cf (cons (- end beg) prop))
716 (gnugo-put prop (match-string-no-properties 2))))
717 (end-of-line)
718 (put-text-property right-empty (point) 'category %rpad)
719 (forward-char 1)))
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))
724 'category %gspc)))
725
726 (defun gnugo-merge-showboard-results ()
727 (let ((aft (substring (gnugo--q "showboard") 3))
728 (adj 1) ; string to buffer position adjustment
729
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:
733 ;;
734 ;; (before)
735 ;; ... WHITE has captured 1 stones
736 ;; ^
737 ;; (after)
738 ;; ... WHITE has captured 14 stones
739 ;; ^
740 ;;
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).
745
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
750
751 (inhibit-read-only t))
752 (while (numberp (setq mis (gnugo--compare-strings
753 bef bef-start
754 aft aft-start)))
755 (setq aft-sync-backtrack nil
756 inc (if (cl-minusp mis)
757 (- (+ 1 mis))
758 (- mis 1))
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))
762 (match-end 0)
763 (1+ 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))))
769 (match-end 0)
770 (1+ aft-idx))
771 cut (+ bef-idx adj
772 (if aft-sync-backtrack
773 (- aft-sync-backtrack aft-idx)
774 0)))
775 (goto-char cut)
776 (if aft-sync-backtrack
777 (let* ((asb aft-sync-backtrack)
778 (l-p (get-text-property cut :gnugo-cf))
779 (old-len (car l-p))
780 (capprop (cdr l-p))
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)
793 `(gnugo-yang
794 ,yang
795 category
796 ,(gnugo-yy yin yang))))
797 (delete-char 1)
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))))))
802
803 (defsubst gnugo--move-prop (node)
804 (or (assq :B node)
805 (assq :W node)))
806
807 (defun gnugo--as-pos-func ()
808 (let ((size (gnugo-get :SZ)))
809 ;; rv
810 (lambda (cc)
811 (if (string= "" cc)
812 "PASS"
813 (let ((col (aref cc 0)))
814 (format "%c%d"
815 (+ ?A (- (if (> ?i col) col (1+ col)) ?a))
816 (- size (- (aref cc 1) ?a))))))))
817
818 (defsubst gnugo--resignp (string)
819 (string= "resign" string))
820
821 (defsubst gnugo--passp (string)
822 (string= "PASS" string))
823
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."
837 (interactive "P")
838 (let* ((monkey (gnugo-get :monkey))
839 (mem (aref monkey 0))
840 (as-pos (gnugo--as-pos-func))
841 acc node mprop move)
842 (cl-flet*
843 ((as-pos-maybe (x) (if (gnugo--resignp x)
844 x
845 (funcall as-pos 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)))
850 (push (if byp
851 (format "%s%s" move (car mprop))
852 move)
853 acc)))
854 (nn () (next nil))
855 (tell () (message "(%d moves) %s"
856 (length acc)
857 (mapconcat 'identity (nreverse acc) " ")))
858 (finish (byp) (while mem (next byp)) (tell)))
859 (pcase rsel
860 (`(4) (finish t))
861 (`nil (finish nil))
862 (`car (car (nn)))
863 (`cadr (nn) (car (nn)))
864 (`two (nn) (nn) acc)
865 (`bpos (cl-loop
866 with prop = (gnugo--prop<-color color)
867 while mem
868 when (and (remem)
869 (eq prop (car mprop))
870 (setq move (cdr mprop))
871 ;; i.e., "normal CC" position
872 (= 2 (length move)))
873 return (funcall as-pos move)))
874 (_ nil)))))
875
876 (defun gnugo-boss-is-near ()
877 "Do `bury-buffer' until the current one is not a GNU Board."
878 (interactive)
879 (while (gnugo-board-buffer-p)
880 (bury-buffer)))
881
882 (defsubst gnugo--no-regrets (monkey ends)
883 (eq (aref ends (aref monkey 1))
884 (aref monkey 0)))
885
886 (defun gnugo--as-cc-func ()
887 (let ((size (gnugo-get :SZ)))
888 (lambda (pos)
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)))))
894
895 (defun gnugo--decorate (node &rest plist)
896 (cl-loop
897 with tp = (last node)
898 with fruit
899 while plist
900 do (setf
901 fruit (list (cons ; DWR: LtR OoE assumed.
902 (pop plist)
903 (pop plist)))
904 (cdr tp) fruit
905 tp fruit)))
906
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)
911 (cadr now))))
912 (gnugo-put :game-over
913 (if (or (eq t resign)
914 (and (stringp resign)
915 (string-match "[BW][+][Rr]esign" resign)))
916 (cl-flet
917 ((ls (color) (mapcar
918 (lambda (x)
919 (cons (list color)
920 (split-string x)))
921 (split-string
922 (gnugo-query "worm_stones %s" color)
923 "\n"))))
924 (let ((live (append (ls "black") (ls "white"))))
925 `((live ,@live)
926 (dead))))
927 (let ((dd (gnugo-query "dragon_data"))
928 (start 0) mem color ent live dead)
929 (while (string-match "\\(.+\\):\n[^ ]+[ ]+\\(black\\|white\\)\n"
930 dd start)
931 (setq mem (match-string 1 dd)
932 color (match-string 2 dd)
933 start (match-end 0)
934 ent (cons (list color)
935 (sort (gnugo-lsquery "dragon_stones %s" mem)
936 'string<)))
937 (string-match "\nstatus[ ]+\\(\\(ALIVE\\)\\|[A-Z]+\\)\n"
938 dd start)
939 (if (match-string 2 dd)
940 (push ent live)
941 (push ent dead))
942 (setq start (match-end 0)))
943 `((live ,@live)
944 (dead ,@dead))))))
945
946 (defun gnugo--unclose-game ()
947 (gnugo--forget :game-over ; all those in -close-game
948 :scoring-seed
949 :game-end-time)
950 (let* ((root (gnugo--root-node))
951 (cur (assq :RE root)))
952 (when cur
953 (cl-assert (not (eq cur (car root))) nil
954 ":RE at head of root node: %S"
955 root)
956 (delq cur root))))
957
958 (defun gnugo-push-move (who move)
959 (let* ((simple (booleanp who))
960 (ucolor (gnugo-get :user-color))
961 (color (if simple
962 (if who
963 ucolor
964 (gnugo-get :gnugo-color))
965 who))
966 (start (gnugo-get :waiting-start))
967 (now (current-time))
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))))
973 (unless resignp
974 (gnugo--q/ue "play %s %s" color move))
975 (unless passp
976 (gnugo-merge-showboard-results))
977 (gnugo-put :last-mover color)
978 (when (if simple
979 who
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)
985 (passp "")
986 (t (funcall (gnugo--as-cc-func)
987 move)))))
988 (fruit (list pair))
989 (monkey (gnugo-get :monkey))
990 (mem (aref monkey 0))
991 (tip (car mem))
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:
999 ;;
1000 ;; X---Y---A new
1001 ;; \
1002 ;; --A---B old
1003 ;;
1004 ;; (such "variations" do not actually vary!) in favor of:
1005 ;;
1006 ;; X---Y---A new
1007 ;; \
1008 ;; --B old
1009 ;;
1010 ;; This linear search loses for multiple ‘old’ w/ "A",
1011 ;; a very unusual (but not invalid, sigh) situation.
1012 (cl-loop
1013 with (bx previous)
1014 for i
1015 ;; Start with latest / highest likelihood for hit.
1016 ;; (See "to the right" comment, below.)
1017 from (if (gnugo--no-regrets monkey ends)
1018 1
1019 0)
1020 below count
1021 if (setq bx (mod (+ bidx i) count)
1022 previous
1023 (cl-loop
1024 with node
1025 for m on (aref ends bx)
1026 while (< tip-move-num
1027 (gethash (setq node (car m))
1028 mnum))
1029 if (eq mem (cdr m))
1030 return (when (equal pair (assq property node))
1031 m)
1032 finally return nil))
1033 ;; yes => follow
1034 return
1035 (progn
1036 (unless (= bidx bx)
1037 (cl-rotatef (aref ends bidx)
1038 (aref ends bx)))
1039 (setq mem previous))
1040 ;; no => construct
1041 finally do
1042 (progn
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))
1048 ls))))
1049 (puthash fruit (1+ (gethash tip mnum)) mnum)
1050 (push fruit mem)
1051 (aset ends bidx mem)))
1052 (setf (aref monkey 0) mem))
1053 (when start
1054 (gnugo-put :last-waiting (cadr (time-subtract now start))))
1055 (when donep
1056 (gnugo-close-game now resignp))
1057 (gnugo-put :waiting-start (and (not donep) now))
1058 donep))
1059
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))
1071 (bop (lambda (s)
1072 (let* ((start 0)
1073 (ncolors
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)
1082 (match-end 0))))
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
1088 (while (< sx lx)
1089 (when (and (not (= color-key (aref new sx)))
1090 (cl-plusp (random 4)))
1091 (aset new sx (aref bg-data sb)))
1092 (cl-incf sx)
1093 (cl-incf sb))
1094 (apply 'create-image new 'xpm t
1095 :ascent 'center (when c-symbs
1096 (list :color-symbols
1097 c-symbs)))))
1098
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.
1106
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
1110 its move."
1111 (interactive "P")
1112 (let* ((move (gnugo-move-history 'car))
1113 (game-over (gnugo-get :game-over))
1114 (inhibit-read-only t)
1115 window last)
1116 (when (and nocache (not (gnugo-get :waiting)))
1117 (gnugo-propertize-board-buffer))
1118 ;; last move
1119 (when move
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)
1124 (let* ((p (point))
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)
1133 display-value))
1134 (move-overlay l-ov l-new-pos (1+ l-new-pos))
1135 (if r-action
1136 (funcall r-action r-ov)
1137 (move-overlay r-ov (+ l-new-pos 2) (+ l-new-pos 3)))))))
1138 ;; buffer name
1139 (rename-buffer (concat (gnugo-get :diamond)
1140 (if game-over
1141 (format "%s(game over)"
1142 (if (gnugo--resignp move)
1143 (concat move "ation ")
1144 ""))
1145 (format "%s(%s to play)"
1146 (if move (concat move " ") "")
1147 (gnugo-current-player)))))
1148 ;; pall of death
1149 (when game-over
1150 (let ((live (cdr (assq 'live game-over)))
1151 (dead (cdr (assq 'dead game-over)))
1152 p pall)
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)
1157 (setq p (point))
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)))
1171 (overlay-put
1172 ov 'display
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)))
1179 (push ov pall))
1180 (setcdr (car group) pall))))))
1181 ;; window update
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)
1188 (* size (cdr mul))
1189 (if gridp 2 0))
1190 2)
1191 (if gridp 0 1)))
1192 (edges (window-edges window))
1193 (right-w-edge (nth 2 edges))
1194 (avail-width (- right-w-edge (nth 0 edges)))
1195 (wmul (car mul))
1196 (imagesp (symbol-plist (gnugo-f 'ispc)))
1197 (w (/ (- avail-width
1198 (* size wmul)
1199 (if imagesp
1200 0
1201 (1- size))
1202 2 ; between board and grid
1203 (if gridp
1204 (if under10p 2 4)
1205 0))
1206 2.0)))
1207 (dolist (pair `((tpad . ,(if (and h (cl-plusp h))
1208 `(display ,(make-string h 10))
1209 '(invisible :nogrid)))
1210 (gpad . (display
1211 (space :align-to
1212 ,(+ w
1213 2.0
1214 (cond (imagesp (+ (* 0.5 wmul)
1215 (if under10p
1216 -0.5
1217 0.5)))
1218 (under10p 0)
1219 (t 1))))))
1220 (gspc . ,(when imagesp
1221 `(display
1222 (space-width
1223 ,(-
1224 ;; DWR: image width alone => OBOE!
1225 ;;- wmul
1226 ;; NB: ‘(* wmul cw)’ is the same
1227 ;; as ‘(car (image-size ... t))’.
1228 (let ((cw (frame-char-width)))
1229 (/ (+ 1.0 (* wmul cw))
1230 cw))
1231 1.0)))))
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
1238 ;; column A.
1239 (if gridp
1240 `(before-string
1241 ,(apply 'propertize " " d))
1242 d)))
1243 (rpad . (display
1244 (space :align-to ,(1- avail-width))))))
1245 (setplist (gnugo-f (car pair)) (cdr pair)))))
1246 ;; mode line update
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))
1254 (let (acc cut c)
1255 (while (setq cut (string-match "~[bwpmtu]" cur))
1256 (aset cur cut ?%)
1257 (setq c (aref cur (cl-incf cut)))
1258 (aset cur cut ?s)
1259 (push
1260 `(,(intern (format "squig-%c" c))
1261 ,(cl-case 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)))
1266 (if ws
1267 (cadr (time-since ws))
1268 "-")))
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
1275 "?")))))
1276 acc))
1277 `(let ,(delete-dups (copy-sequence acc))
1278 (format ,cur ,@(reverse (mapcar 'car acc))))))
1279 (t cur))))
1280 (let ((form (gnugo-get :mode-line-form)))
1281 (setq mode-line-process
1282 (and form
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))
1288 ;; last user move
1289 (when (setq last (gnugo-get :last-user-bpos))
1290 (gnugo-goto-pos last))))
1291
1292 (defun gnugo--turn-the-wheel (&optional now)
1293 (unless (gnugo-get :waiting)
1294 (let ((color (gnugo-current-player))
1295 (wheel (gnugo-get :wheel)))
1296 (setcar wheel
1297 (when (and (not (gnugo-get :game-over))
1298 (member color (cdr wheel)))
1299 (run-at-time
1300 (if now
1301 nil
1302 2) ;;; sec (frettoloso? dubioso!)
1303 nil
1304 (lambda (buf color wheel)
1305 (setcar wheel nil)
1306 (with-current-buffer buf
1307 (gnugo-get-move color)))
1308 (current-buffer)
1309 color wheel))))))
1310
1311 (defun gnugo--finish-move (&optional now)
1312 (let ((buf (current-buffer)))
1313 (run-hooks 'gnugo-post-move-hook)
1314 (set-buffer buf))
1315 (gnugo-refresh)
1316 (gnugo--turn-the-wheel now))
1317
1318 ;;;---------------------------------------------------------------------------
1319 ;;; Game play actions
1320
1321 (defun gnugo--rename-buffer-portion (&optional back)
1322 (let ((old "to play")
1323 (new "waiting for suggestion"))
1324 (when back
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))))))
1329
1330 (defun gnugo--display-suggestion (color suggestion)
1331 (message "%sSuggestion for %s: %s"
1332 (gnugo-get :diamond)
1333 color suggestion))
1334
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
1344 :waiting)
1345 (if suggestion
1346 (progn
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)))))))
1354
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))
1363
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)))
1369
1370 (defun gnugo-position ()
1371 (or (get-text-property (point) 'gnugo-position)
1372 (user-error "Not a proper position point")))
1373
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."
1379 (interactive "P")
1380 (gnugo-gate t)
1381 (gnugo--rename-buffer-portion)
1382 (gnugo-get-move (gnugo-current-player)
1383 (if nowarp
1384 'nowarp
1385 t)))
1386
1387 (defun gnugo--karma (color) ; => BOOL
1388 (when (member color (cdr (gnugo-get :wheel)))
1389 t))
1390
1391 (defsubst gnugo--:karma (role)
1392 (gnugo--karma (gnugo-get role)))
1393
1394 (defun gnugo--assist-state (&optional gate)
1395 (let ((bool (gnugo--:karma :user-color)))
1396 (if (and bool gate)
1397 (user-error "Sorry, Assist mode enabled")
1398 bool)))
1399
1400 (defun gnugo--user-play (pos-or-pass)
1401 (gnugo-gate t)
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"
1411 color)))
1412 (gnugo-push-move color pos-or-pass))
1413 (gnugo--finish-move t))
1414
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."
1420 (interactive)
1421 (gnugo--user-play (gnugo-position)))
1422
1423 (defun gnugo-mouse-move (e)
1424 "Do `gnugo-move' at mouse location."
1425 (interactive "@e")
1426 (mouse-set-point e)
1427 (when (memq (following-char) '(?. ?+))
1428 (gnugo-move)))
1429
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."
1434 (interactive)
1435 (gnugo--user-play "PASS"))
1436
1437 (defun gnugo-mouse-pass (e)
1438 "Do `gnugo-pass' at mouse location."
1439 (interactive "@e")
1440 (mouse-set-point e)
1441 (gnugo-pass))
1442
1443 (defun gnugo-resign ()
1444 (interactive)
1445 (gnugo-gate t)
1446 (if (not (y-or-n-p "Resign? "))
1447 (message "(not resigning)")
1448 (gnugo-push-move t "resign")
1449 (gnugo-refresh)))
1450
1451 (defun gnugo-animate-group (w/d)
1452 ;; W/D is a symbol, either ‘worm’ or ‘dragon’.
1453 (gnugo-gate)
1454 (let* ((pos (gnugo-position))
1455 (orig-b-m-p (buffer-modified-p))
1456 blurb stones)
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)
1464 (cl-loop
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))
1471 dn up))
1472 (split-string gnugo-animation-string "" t)))
1473 (cell (list spec))
1474 (ovs (save-excursion
1475 (mapcar (lambda (pos)
1476 (gnugo-goto-pos pos)
1477 (let* ((p (point))
1478 (ov (make-overlay p (1+ p))))
1479 (overlay-put ov 'category (gnugo-f 'anim))
1480 (overlay-put ov 'priority most-positive-fixnum)
1481 ov))
1482 stones))))
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))
1489 (sit-for 5)
1490 (mapc 'delete-overlay ovs)
1491 t)))
1492
1493 (defun gnugo-display-group-data (command buffer-name)
1494 (gnugo-gate)
1495 (message "Computing %s ..." command)
1496 (let ((data (gnugo--q "%s %s" command (gnugo-position))))
1497 (switch-to-buffer buffer-name)
1498 (erase-buffer)
1499 (insert data))
1500 (message "Computing %s ... done." command))
1501
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."
1506 (interactive)
1507 (gnugo-animate-group 'worm))
1508
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."
1512 (interactive)
1513 (gnugo-display-group-data "worm_data" "*gnugo worm data*"))
1514
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."
1519 (interactive)
1520 (gnugo-animate-group 'dragon))
1521
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."
1525 (interactive)
1526 (gnugo-display-group-data "dragon_data" "*gnugo dragon data*"))
1527
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)."
1533 (interactive)
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)))
1545
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))
1551
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))
1564
1565 (defun gnugo--dance-dance (karma)
1566 (cl-destructuring-bind (dance btw)
1567 (aref [(moshpit " Zombie")
1568 (classic nil)
1569 (reverse " Zombie Assist") ; "Assist Zombie"? no thanks! :-D
1570 (stilted " Assist")]
1571 (cl-flet
1572 ((try (n prop)
1573 (if (member (gnugo-get prop)
1574 karma)
1575 n
1576 0)))
1577 (+ (try 2 :user-color)
1578 (try 1 :gnugo-color))))
1579 (gnugo-put :dance dance) ; pure cruft (for now)
1580 (setq gnugo-btw btw)))
1581
1582 (defun gnugo--who-is-who (wait play samep)
1583 (unless samep
1584 (let ((wheel (gnugo-get :wheel)))
1585 (when wheel
1586 (gnugo--dance-dance
1587 (setcdr wheel (mapcar 'gnugo-other
1588 (cdr wheel)))))))
1589 (message "GNU Go %splays as %s, you as %s (%s)"
1590 (if samep "" "now ")
1591 wait play (if samep
1592 "as before"
1593 "NOTE: this is a switch!")))
1594
1595 (defsubst gnugo--nodep (x)
1596 (keywordp (caar x)))
1597
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))))
1603 (string c c)))))
1604
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
1610 ;; mem
1611 (aref (gnugo--tree-ends tree) 0)
1612 ;; bidx
1613 0))
1614 tree))
1615
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)
1628 (unless samep
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)))
1634 ;; This is better:
1635 ;; (if (= 1 n)
1636 ;; 0
1637 ;; (let* ((q (format "Which game? (1-%d)" n))
1638 ;; (choice (1- (read-number q 1))))
1639 ;; (if (and (< -1 choice) (< choice n))
1640 ;; choice
1641 ;; (message "(Selecting the first game)")
1642 ;; 0)))
1643 ;; but this is what we use (for now) to accomodate
1644 ;; (aka faithfully mimic) GTP `loadsgf' limitations:
1645 (unless (= 1 n)
1646 (message "(Selecting the first game)"))
1647 0)))
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))
1653 'two-passes)))
1654 (gnugo-close-game nil game-over))
1655 (gnugo-put :last-user-bpos
1656 (gnugo-move-history 'bpos (gnugo-get :user-color)))
1657 (gnugo-refresh t)
1658 (gnugo--ok-file filename)
1659 (gnugo--who-is-who wait play samep)))
1660
1661 (defun gnugo--mem-with-played-stone (pos &optional noerror)
1662 (let ((color (cl-case (following-char)
1663 (?X :B)
1664 (?O :W))))
1665 (if (not color)
1666 (unless noerror
1667 (user-error "No stone at %s" pos))
1668 (cl-loop
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))
1672 return mem
1673 finally return nil))))
1674
1675 (defun gnugo--climb-towards-root (spec &optional reaction keep)
1676 (gnugo-gate)
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)
1686 user-color)
1687 1
1688 2)
1689 spec)
1690 (aref monkey 0))
1691 (cdr (gnugo--mem-with-played-stone
1692 (if (stringp spec)
1693 spec
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)))
1707 ubpos
1708 (gnugo-get :center-position)))
1709 (gnugo-refresh t)
1710 (unless (or keep remorseful)
1711 (aset ends (aref monkey 1) (aref monkey 0)))
1712 (when ulastp
1713 (let ((g (gnugo-get :gnugo-color)))
1714 (cl-flet ((turn () (gnugo--turn-the-wheel t)))
1715 (cl-case (or reaction gnugo-undo-reaction)
1716 (play (turn))
1717 (play! (let ((wheel (gnugo-get :wheel)))
1718 (cl-letf (((cdr wheel) (cons g (cdr wheel))))
1719 (turn))))
1720 (zombie (gnugo-zombie-mode 1))
1721 (t (gnugo-put :one-shot g)))))))))
1722
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]
1732
1733 See also `gnugo-undo-two-moves'."
1734 (interactive "P")
1735 (gnugo-gate)
1736 (when me-next
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)
1745 (t 'one-shot))))
1746
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."
1751 (interactive)
1752 (gnugo--climb-towards-root 0))
1753
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]'."
1759 (interactive "P")
1760 (gnugo--climb-towards-root (unless position
1761 0)
1762 nil t))
1763
1764 (defun gnugo-okay (&optional full)
1765 "Redo a pair of undone moves.
1766 Prefix arg means to redo all the undone moves."
1767 (interactive "P")
1768 (gnugo-gate)
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)))
1782 (cl-loop
1783 with ok = (if full
1784 (mvno (car end))
1785 (+ 2 (mvno (car mem))))
1786 with (node move todo)
1787 for ls on end
1788 do (progn
1789 (setq node (car ls)
1790 move (gnugo--move-prop node))
1791 (when (and move (>= ok (mvno node)))
1792 (let ((userp (eq uprop (car move))))
1793 (push (list userp
1794 (funcall as-pos (cdr move)))
1795 todo))))
1796 until (eq mem (cdr ls))
1797 finally do
1798 (cl-loop
1799 for (userp pos) in todo
1800 do (progn
1801 (gnugo-push-move userp pos)
1802 (gnugo-refresh)
1803 (redisplay)))))))))
1804
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."
1812 (interactive "P")
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"))
1818 (unless game-over
1819 (cl-flet
1820 ((pass (userp)
1821 (message "Playing PASS for %s ..."
1822 (gnugo-get (if userp :user-color :gnugo-color)))
1823 (sit-for 1)
1824 (gnugo-push-move userp "PASS")))
1825 (unless (pass t)
1826 (pass nil)))
1827 (gnugo-refresh)
1828 (sit-for 3)))
1829 (let ((b= " Black = ")
1830 (w= " White = ")
1831 (res (when (gnugo--resignp (gnugo-move-history 'car))
1832 (gnugo-get :last-mover)))
1833 blurb result)
1834 (if res
1835 (setq blurb (list
1836 (format "%s wins.\n"
1837 (substring (if (= ?b (aref res 0)) w= b=)
1838 3 8))
1839 "The game is over.\n"
1840 (format "Resignation by %s.\n" res))
1841 result (concat (upcase (substring (gnugo-other res) 0 1))
1842 "+Resign"))
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))
1849 (terr "territory")
1850 (capt "captures")
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))
1861 b-terr
1862 w-terr)
1863 (length (cdr group))))
1864 (dolist (group dead)
1865 (cl-incf (if (gnugo--blackp (caar group))
1866 w-terr
1867 b-terr)
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))
1872 blurb))
1873 (t
1874 (dolist (group dead)
1875 (cl-incf (if (gnugo--blackp (caar group))
1876 w-terr
1877 b-terr)
1878 (* 2 (length (cdr group)))))
1879 (push (format "%s%d %s + %s %s = %3.1f\n" b=
1880 b-terr terr
1881 b-capt capt
1882 (+ b-terr b-capt))
1883 blurb)
1884 (push (format "%s%d %s + %s %s + %3.1f %s = %3.1f\n" w=
1885 w-terr terr
1886 w-capt capt
1887 komi 'komi
1888 (+ w-terr w-capt komi))
1889 blurb)))
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)))
1895 blurb)
1896 (message "Computing final score ... done")))
1897 ;; extra info
1898 (let ((beg (gnugo-get :game-start-time))
1899 (end (gnugo-get :game-end-time)))
1900 (when end
1901 (push "\n" blurb)
1902 (cl-flet
1903 ((yep (pretty moment)
1904 (push (format-time-string
1905 (concat pretty ": %F %T %z\n")
1906 moment)
1907 blurb)))
1908 (yep "Game start" beg)
1909 (yep " end" end))))
1910 (setq blurb (apply 'concat (nreverse blurb)))
1911 (gnugo--set-root-prop :RE result)
1912 (when comment
1913 (let ((node (car (aref (gnugo-get :monkey) 0))))
1914 (gnugo--decorate
1915 (delq (assq :C node) node)
1916 :C
1917 (with-temp-buffer ; lame
1918 (insert blurb)
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")
1928 (rep "komi" "K"))
1929 (buffer-string)))))
1930 (switch-to-buffer (format "%s*GNUGO Final Score*" (gnugo-get :diamond)))
1931 (erase-buffer)
1932 (insert blurb)))
1933
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."
1937 (interactive)
1938 (if (or (gnugo-get :game-over)
1939 (y-or-n-p "Quit? "))
1940 (kill-buffer nil)
1941 (message "(not quitting)")))
1942
1943 (defun gnugo-leave-me-alone ()
1944 "Kill the current buffer unconditionally."
1945 (interactive)
1946 (kill-buffer nil))
1947
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."
1953 (interactive "P")
1954 (gnugo--climb-towards-root
1955 (if (numberp count)
1956 count
1957 (car-safe count))))
1958
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'."
1962 :variable
1963 ((gnugo-get :display-using-images)
1964 .
1965 (lambda (bool)
1966 (unless (eq bool (gnugo-get :display-using-images))
1967 (gnugo-toggle-image-display)
1968 (save-excursion (gnugo-refresh))))))
1969
1970 (defsubst gnugo--node-with-played-stone (pos &optional noerror)
1971 (car (gnugo--mem-with-played-stone pos noerror)))
1972
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."
1976 (interactive)
1977 (let* ((pos (gnugo-position)) ; do first (can throw)
1978 (node (gnugo--node-with-played-stone pos t)))
1979 (message
1980 "%s%s" pos
1981 (or (when node
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)))
1986 ""))))
1987
1988 (defun gnugo-switch-to-another ()
1989 "Switch to another GNU Go game buffer (if any)."
1990 (interactive)
1991 (cl-loop
1992 for buf in (cdr (buffer-list))
1993 if (gnugo-board-buffer-p buf)
1994 return (progn
1995 (bury-buffer)
1996 (switch-to-buffer buf))
1997 finally do (message "(only one)")))
1998
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').
2004
2005 If COMMENT is nil or the empty string, remove the property entirely."
2006 (interactive
2007 (let* ((pos (gnugo-position))
2008 (node (gnugo--node-with-played-stone pos)))
2009 (list node
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)))
2016
2017 (defun gnugo--struggle (prop updn)
2018 (unless (eq updn (gnugo--:karma prop)) ; drudgery avoidance
2019 (let ((color (gnugo-get prop)))
2020 (if updn
2021 ;; enable
2022 (gnugo-gate)
2023 ;; disable
2024 (let ((waiting (gnugo-get :waiting)))
2025 (when (and waiting (string= color (car waiting)))
2026 (gnugo--rename-buffer-portion)
2027 (setcdr waiting
2028 ;; heuristic: Warp only if it appears
2029 ;; that the user is "following along".
2030 (or (ignore-errors
2031 (string= (gnugo-position)
2032 (gnugo-move-history 'bpos color)))
2033 'nowarp))
2034 (gnugo--display-suggestion color "forthcoming")
2035 (sit-for 2))))
2036 (let* ((wheel (gnugo-get :wheel))
2037 (timer (car wheel))
2038 (karma (cdr wheel)))
2039 (when (timerp timer)
2040 (cancel-timer timer))
2041 (setcar wheel nil)
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!
2048 (if updn
2049 (push color karma)
2050 (delete color karma))))
2051 (gnugo--dance-dance karma))
2052 (gnugo--turn-the-wheel t))))
2053
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')."
2059 :variable
2060 ((gnugo--assist-state)
2061 .
2062 (lambda (bool)
2063 (gnugo--struggle :user-color bool))))
2064
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')."
2070 :variable
2071 ((not (gnugo--:karma :gnugo-color))
2072 .
2073 (lambda (bool)
2074 (gnugo--struggle :gnugo-color (not bool)))))
2075
2076 ;;;---------------------------------------------------------------------------
2077 ;;; Command properties and gnugo-command
2078
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:
2083 ;;
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.
2087 ;;
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'.
2095 ;;
2096 ;; :post-thunk -- run after output processing (at the very end).
2097
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).
2105
2106 For example, for the command \"help\", Emacs visits the
2107 GTP command reference info page.
2108
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)))
2118 (if 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)
2124 (message "%s" ans)
2125 (cond ((functionp where) (funcall where ans))
2126 ((eq :discard where) (message ""))
2127 ((or (eq :message where)
2128 (not (string-match "\n" ans)))
2129 (message "%s" ans))
2130 (t (switch-to-buffer "*gnugo command output*")
2131 (erase-buffer)
2132 (insert ans)
2133 (message "Doing %s ... done." command)))
2134 (let ((thunk (plist-get spec :post-thunk)))
2135 (when thunk (funcall thunk)))))))))
2136
2137 ;;;---------------------------------------------------------------------------
2138 ;;; Major mode for interacting with a GNUGO subprocess
2139
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)
2146 truncate-lines 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 ")")
2157 ov)))
2158 (gnugo-put :mul '(1 . 1))
2159 (gnugo-put :obarray (make-vector 31 nil))
2160 (add-to-invisibility-spec :nogrid))
2161
2162 ;;;---------------------------------------------------------------------------
2163 ;;; Entry point
2164
2165 ;;;###autoload
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.
2171
2172 Before starting, Emacs queries you for additional command-line
2173 options (Emacs supplies \"--mode gtp --quiet\" automatically).
2174
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'.
2178
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."
2182 (interactive "P")
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)))
2187 acc))
2188 (n (length all)))
2189 (if (and (not new-game)
2190 (cl-plusp n)
2191 (y-or-n-p (format "GNU Go game%s in progress, resume play? "
2192 (if (= 1 n) "" "s"))))
2193 ;; resume
2194 (switch-to-buffer
2195 (cdr (if (= 1 n)
2196 (car all)
2197 (let ((sel (completing-read "Which one? " all nil t)))
2198 (if (string= "" sel)
2199 (car all)
2200 (assoc sel all))))))
2201 ;; sanity check
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)"))
2206 (gnugo-board-mode)
2207 (let* ((filename nil)
2208 (user-color "black")
2209 (args (cl-loop
2210 with ls = (split-string
2211 ;; todo: grok ‘gnugo --help’; completion
2212 (read-string
2213 "GNU Go options: "
2214 (car gnugo-option-history)
2215 'gnugo-option-history))
2216 with ok
2217 while ls do
2218 (let ((arg (pop ls)))
2219 (cl-flet
2220 ((ex (opt fn)
2221 (if filename
2222 (warn "%s %s ignored" opt fn)
2223 (setq filename fn))))
2224 (cond
2225 ((string= "--color" arg)
2226 (push arg ok)
2227 (push
2228 ;; Unfortunately, GTP does not provide
2229 ;; a way to query the user color, so
2230 ;; we must resort to this weirdness.
2231 (setq user-color
2232 (pop ls))
2233 ok))
2234 ((string= "--infile" arg)
2235 (ex "--infile" (pop ls)))
2236 ((string-match "^-l" arg)
2237 (ex "-l" (if (< 2 (length arg))
2238 (substring arg 2)
2239 (pop ls))))
2240 (t (push arg ok)))))
2241 finally return (nreverse ok)))
2242 (proc (apply 'start-process "gnugo"
2243 (current-buffer)
2244 gnugo-program
2245 "--mode" "gtp" "--quiet"
2246 args))
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))
2255 (if filename
2256 (gnugo-read-sgf-file (expand-file-name filename))
2257 (cl-flet
2258 ((r! (&rest plist) (apply 'gnugo--decorate root plist)))
2259 (gnugo--SZ!
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)))))
2276 (r! :SZ board-size
2277 :DT (format-time-string "%F")
2278 :RU (if (member "--chinese-rules" args)
2279 "Chinese"
2280 "Japanese")
2281 :KM komi)
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)
2286 (r! :HA handicap
2287 :AB (mapcar (gnugo--as-cc-func)
2288 (gnugo-lsquery "fixed_handicap %d"
2289 handicap)))))))
2290 (gnugo-put :waiting-start (current-time))
2291 (gnugo-refresh t)
2292 (gnugo-goto-pos (or (gnugo-get :last-user-bpos)
2293 (gnugo-get :center-position)))
2294 ;; first move
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)))
2303 u
2304 g)))
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)))))
2310
2311 ;;;---------------------------------------------------------------------------
2312 ;;; Load-time actions
2313
2314 (unless (get 'help :gnugo-gtp-command-spec)
2315 (cl-flet*
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)))
2321 (cl-loop
2322 with size = (gnugo-get :SZ)
2323 for c across (funcall (gnugo--as-cc-func)
2324 pos)
2325 do (let ((norm (- c ?a)))
2326 (unless (and (< -1 norm)
2327 (> size norm))
2328 (user-error "Invalid position: %s"
2329 pos))))
2330 (when go
2331 (gnugo-goto-pos pos))
2332 pos))
2333 (defgtp (x &rest props) (dolist (cmd (if (symbolp x) (list x) x))
2334 (let ((ls props))
2335 (while ls
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)
2341 ,@body))))
2342
2343 (deffull help
2344 (info "(gnugo)GTP command reference")
2345 (when sel (setq sel (intern (car sel))))
2346 (let (buffer-read-only pad cur spec output found)
2347 (cl-flet
2348 ((note (s) (insert pad "[NOTE: gnugo.el " s ".]\n")))
2349 (goto-char (point-min))
2350 (save-excursion
2351 (while (re-search-forward "^ *[*] \\([a-zA-Z_]+\\)\\(:.*\\)*\n"
2352 nil t)
2353 (unless pad
2354 (setq pad (make-string (- (match-beginning 1)
2355 (match-beginning 0))
2356 32)))
2357 (when (plist-get
2358 (setq spec
2359 (get (setq cur (intern (match-string 1)))
2360 :gnugo-gtp-command-spec))
2361 :full)
2362 (note "handles this command completely"))
2363 (when (setq output (plist-get spec :output))
2364 (if (functionp output)
2365 (note "handles the output specially")
2366 (cl-case output
2367 (:discard (note "discards the output"))
2368 (:message (note "displays the output in the echo area")))))
2369 (when (eq sel cur)
2370 (setq found (make-marker))
2371 (set-marker found (match-beginning 0))))))
2372 (cond (found (goto-char found) (set-marker found nil))
2373 ((not sel))
2374 (t (message "(no such command: %s)" sel)))))
2375
2376 (deffull final_score
2377 ;; Explicit ignorance avoids byte-compiler warning.
2378 (ignore sel)
2379 (gnugo-display-final-score))
2380
2381 (defgtp '(boardsize
2382 clear_board
2383 fixed_handicap)
2384 :output :discard
2385 :post-thunk (lambda ()
2386 (gnugo--unclose-game)
2387 (gnugo--forget :last-mover)
2388 ;; ugh
2389 (gnugo--SZ! (gnugo--nquery "query_boardsize"))
2390 (gnugo-refresh t)))
2391
2392 (deffull loadsgf
2393 (gnugo-read-sgf-file (car sel)))
2394
2395 (deffull (undo gg-undo)
2396 (gnugo--climb-towards-root
2397 (let (n)
2398 (cond ((not sel) 1)
2399 ((cl-plusp (setq n (string-to-number (car sel)))) n)
2400 (t (validpos (car sel) t)))))))))
2401
2402 (provide 'gnugo)
2403
2404 \f
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.
2410
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)
2446 (KO "Ko" move none)
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)
2478 (V "Value" - real)
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...).")
2489
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:
2496
2497 ENDS -- a vector of node lists, with shared tails
2498 (last element of all the lists is the root node)
2499
2500 MNUM -- `eq' hash: node to move numbers; non-\"move\" nodes
2501 have a move number of the previous \"move\" node (or zero)
2502
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)
2508 (cons (car 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*))))
2516 SZ)
2517 (cl-labels
2518 ((sw () (skip-chars-forward " \t\n"))
2519 (x (end preserve-whitespace)
2520 (let ((beg (point))
2521 (endp (cl-case end
2522 (:end (lambda (char) (= ?\] char)))
2523 (:mid (lambda (char) (= ?\: char)))
2524 (t (lambda (char) (or (= ?\: char)
2525 (= ?\] char))))))
2526 c)
2527 (while (not (funcall endp (setq c (following-char))))
2528 (cond ((= ?\\ c)
2529 (delete-char 1)
2530 (if (eolp)
2531 (kill-line 1)
2532 (forward-char 1)))
2533 ((unless preserve-whitespace
2534 (looking-at "\\s-+"))
2535 (delete-region (point) (match-end 0))
2536 (insert " "))
2537 (t (forward-char 1))))
2538 (buffer-substring-no-properties beg (point))))
2539 (one (type end) (let ((s (progn
2540 (forward-char 1)
2541 (x end (eq 'text type)))))
2542 (cl-case type
2543 ((stone point move)
2544 ;; blech, begone bu"tt"-ugly blatherings
2545 ;; (but bide brobdingnagian boards)...
2546 (if (and (string= "tt" s)
2547 SZ
2548 (>= 19 SZ))
2549 ""
2550 s))
2551 ((simpletext color) s)
2552 ((number real double) (string-to-number s))
2553 ((text) s)
2554 ((none) "")
2555 (t (error "Unhandled type: %S" type)))))
2556 (val (spec) (cond ((symbolp spec)
2557 (one spec :end))
2558 ((vectorp 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))
2564 v
2565 (forward-char 1)
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)))
2583 (sw)
2584 (cons
2585 (cdr (assq name keywords))
2586 (prog1 (if (= 1 (length spec))
2587 (val (car spec))
2588 (unless (memq (setq ltype (car spec))
2589 '(elist list))
2590 (error "Bad spec: %S" spec))
2591 (if (and (eq 'elist ltype) (sw)
2592 (not (atvalp)))
2593 nil
2594 (let ((type (cadr spec))
2595 mo ls)
2596 (while (and (sw) (atvalp)
2597 (setq mo (val type)))
2598 (push mo ls)
2599 (forward-char 1))
2600 (forward-char -1)
2601 (nreverse ls))))
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)
2606 (forward-char 1)
2607 t))
2608 (NODE () (when (seek-into ?\;)
2609 (cl-loop
2610 with prop
2611 while (setq prop (PROP))
2612 collect (progn
2613 (when (eq :SZ (car prop))
2614 (setq SZ (cdr prop)))
2615 prop))))
2616 (TREE (parent mnum)
2617 (let ((ls parent)
2618 prev node)
2619 (seek-into ?\()
2620 (while (seek ?\;)
2621 (setq prev (car ls)
2622 node (NODE))
2623 (puthash node (+ (if (gnugo--move-prop node)
2624 1
2625 0)
2626 (gethash prev mnum 0))
2627 mnum)
2628 (push node
2629 ls))
2630 (prog1
2631 (if (not (seek ?\())
2632 ;; singular
2633 (list ls)
2634 ;; multiple
2635 (cl-loop
2636 while (seek ?\()
2637 append (TREE ls mnum)))
2638 (seek-into ?\))))))
2639 (with-temp-buffer
2640 (if (not data-p)
2641 (insert-file-contents file-or-data)
2642 (insert file-or-data)
2643 (goto-char (point-min)))
2644 (cl-loop
2645 while (morep)
2646 collect (let* ((mnum (gnugo--mkht :weakness 'key))
2647 (ends (TREE nil mnum))
2648 (root (car (last (car ends)))))
2649 (vector (apply 'vector ends)
2650 mnum
2651 root)))))))
2652
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)))
2657 (cl-cdddr full)))
2658 gnugo/sgf-*r4-properties*))
2659 p name v spec)
2660 (cl-labels
2661 ((esc (composed fmt arg)
2662 (mapconcat (lambda (c)
2663 (cl-case c
2664 ;; ‘?\[’ is not strictly required
2665 ;; but neither is it forbidden.
2666 ((?\[ ?\] ?\\) (format "\\%c" c))
2667 (?: (concat (if composed "\\" "") ":"))
2668 (t (string c))))
2669 (string-to-list (format fmt arg))
2670 ""))
2671 (>>one (v) (insert "[" (esc nil "%s" v) "]"))
2672 (>>two (v) (insert "["
2673 (esc t "%s" (car v))
2674 ":"
2675 (esc t "%s" (cdr v))
2676 "]"))
2677 (>>nl () (cond ((memq name aft-newline-appreciated)
2678 (insert "\n"))
2679 ((< 60 (current-column))
2680 (save-excursion
2681 (goto-char p)
2682 (insert "\n")))))
2683 (>>prop (prop)
2684 (setq p (point)
2685 name (car prop)
2686 v (cdr prop))
2687 (insert (substring (symbol-name name) 1))
2688 (cond ((not v))
2689 ((and (consp v)
2690 (setq spec (cdr (assq name specs)))
2691 (memq (car spec)
2692 '(list elist)))
2693 (>>nl)
2694 (let ((>> (if (consp (cadr spec))
2695 #'>>two
2696 #'>>one)))
2697 (dolist (little-v v)
2698 (setq p (point))
2699 (funcall >> little-v)
2700 (>>nl))))
2701 ((consp v)
2702 (>>two v) (>>nl))
2703 (t
2704 (>>one v) (>>nl))))
2705 (>>node (node)
2706 (cl-loop
2707 initially (insert ";")
2708 for prop in node
2709 do (>>prop prop)))
2710 (>>tree (tree)
2711 (unless (zerop (current-column))
2712 (newline))
2713 (insert "(")
2714 (dolist (x tree)
2715 (funcall (if (gnugo--nodep x)
2716 #'>>node
2717 #'>>tree)
2718 x))
2719 (insert ")")))
2720 (with-temp-buffer
2721 (dolist (tree collection)
2722 ;; write it out
2723 (let ((ht (gnugo--mkht))
2724 (leaves (append (gnugo--tree-ends tree) nil)))
2725 (cl-flet
2726 ((hang (stack)
2727 (cl-loop
2728 with rh ; rectified history
2729 with bp ; branch point
2730 for node in stack
2731 until (setq bp (gethash node ht))
2732 do (puthash node
2733 (push node rh) ; good for now: ½τ
2734 ht)
2735 finally return
2736 (if (not bp)
2737 ;; first run: main line
2738 rh
2739 ;; subsequent runs: grafts (value discarded)
2740 (setcdr bp (nconc
2741 ;; Maintain order of ‘leaves’.
2742 (let ((was (cdr bp)))
2743 (if (gnugo--nodep (car was))
2744 (list was)
2745 was))
2746 (list rh)))))))
2747 (setq tree (hang (pop leaves)))
2748 (mapc #'hang leaves)
2749 (>>tree tree))))
2750 (newline)
2751 (write-file filename)))))
2752
2753 ;;; gnugo.el ends here