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