Skip to content

Instantly share code, notes, and snippets.

@salehmu
Last active Jan 27, 2023
Embed
What would you like to do?
Add org babel support for Portable Game Notation
;; this is another version that doesn't require any user parameters
(defun org-babel-execute:chess (body params)
"Execute a block of Chess code with org-babel.
This function is called by `org-babel-execute-src-block'."
(let* ((output-file (concat (file-name-sans-extension (buffer-file-name)) (format "_%s_chess_output.svg" (format-time-string "%Y-%m-%d_%H-%M-%S")) ))
(notation (cdr (assq :notation params)))
(extension (if (equal notation "fen") ".fen" ".pgn"))
(notation-file (make-temp-file "chess-notation" nil extension))
(cmd (format "python ~/configs/elchess.py %s %s %s" notation-file output-file notation)))
(with-temp-buffer
(insert body)
(write-file notation-file))
(shell-command cmd)
(org-babel-result-to-file (file-name-nondirectory output-file))))
(setq org-babel-default-header-args:chess
'((:results . "raw")))
(org-babel-do-load-languages
'org-babel-load-languages
'((chess . t)))
;; #+begin_src chess
;; 1.e4 e5 2.f4 exf4
;; #+end_src
;; #+RESULTS:
;; [[file:dummies_chess_2023-01-10_18-35-11_chess_output.svg]]
import chess
import chess.svg
import chess.pgn
import sys
import os
notation_file = sys.argv[1]
image_file = sys.argv[2]
try:
_, ext = os.path.splitext(notation_file)
if ext == ".pgn":
with open(notation_file) as f:
game = chess.pgn.read_game(f)
game = game.end()
board = game.board()
elif ext == ".fen":
board = chess.Board(open(notation_file).read())
else:
raise ValueError("Invalid file format. Only '.pgn' and '.fen' are supported.")
boardsvg = chess.svg.board(board=board)
with open(image_file, "w") as f:
f.write(boardsvg)
except Exception as e:
raise e
;; replace the file path with your path to the python script
(defun org-babel-execute:chess (body params)
"Execute a block of Chess code with org-babel.
This function is called by `org-babel-execute-src-block'."
(let* ((output-file (cdr (assq :file params)))
(notation (cdr (assq :notation params)))
(extension (if (equal notation "fen") ".fen" ".pgn"))
(notation-file (make-temp-file "chess-notation" nil extension))
(cmd (format "python ~/configs/elchess.py %s %s %s" notation-file output-file notation)))
(with-temp-buffer
(insert body)
(write-file notation-file))
(shell-command cmd)
(org-babel-result-to-file output-file)))
(setq org-babel-default-header-args:chess
'((:results . "raw")))
;; #+BEGIN_SRC chess :file startpos.svg :notation fen
;; rnbqkbnr/ppp1pppp/8/3p4/2PP4/8/PP2PPPP/RNBQKBNR b KQkq c3 0 2
;; #+END_SRC
;; #+RESULTS:
;; [[file:startpos.svg]]
(org-babel-do-load-languages
'org-babel-load-languages
'((chess . t)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment