Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

migrate tikz plugin #12

Merged
merged 2 commits into from
Apr 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
.pids/
.DS_Store
dist/
__pycache__/
9 changes: 9 additions & 0 deletions BUILD.pants
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ pex_binary(
resolve="sympy_req",
)

pex_binary(
name="tikz",
entry_point="plugins/tikz.py",
dependencies=[
"tmpy/graph:sources",
"tmpy:sources",
],
)

python_requirement(
name="black",
requirements=["black==22.1.0", "click<8.1"],
Expand Down
19 changes: 19 additions & 0 deletions plugins/tikz.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/usr/bin/env python

# MODULE : tikz.py
# DESCRIPTION : Launcher for the TikZ plugin
# COPYRIGHT : (C) 2019 Darcy Shen
#
# This software falls under the GNU general public license version 3 or later.
# It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE
# in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>.

from tmpy.protocol import flush_prompt

from tmpy.graph.tikz import TikZ

current = TikZ()
current.greet()
flush_prompt(current.name + "] ")

current.main_loop()
24 changes: 24 additions & 0 deletions plugins/tikz/doc/tikz-abstract.en.tm
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<TeXmacs|1.99.12>

<style|<tuple|tmdoc|old-dots|british>>

<\body>
<tmdoc-title|Short description of <name|TikZ>>

PGF is a <TeX> macro package for generating graphics. It is platform- and
format-independent and works together with the most important <TeX> backend
drivers, including pdftex and dvips. It comes with a user-friedly syntax
layer called TikZ.

<tmdoc-copyright|2020|Darcy Shen>

<tmdoc-license|Permission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version 1.1
or any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU Free
Documentation License".>
</body>

<initial|<\collection>
</collection>>
78 changes: 78 additions & 0 deletions plugins/tikz/doc/tikz-demo.en.tm

Large diffs are not rendered by default.

31 changes: 31 additions & 0 deletions plugins/tikz/doc/tikz.en.tm
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<TeXmacs|1.99.12>

<style|<tuple|tmdoc|old-spacing|old-dots>>

<\body>
<tmdoc-title|The <name|TikZ> plug-in>

<\traverse>
<branch|Short description|tikz-abstract.en.tm>

<\branch>
Example sessions
</branch|tikz-demo.en.tm>
</traverse>

<tmdoc-copyright|2020|Darcy Shen>

<tmdoc-license|Permission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License, Version 1.1
or any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled "GNU Free
Documentation License".>
</body>

<\initial>
<\collection>
<associate|par-hyphen|normal>
<associate|preamble|false>
</collection>
</initial>
36 changes: 36 additions & 0 deletions plugins/tikz/progs/init-tikz.scm
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; MODULE : init-tikz.scm
;; DESCRIPTION : Initialize TikZ plugin
;; COPYRIGHT : (C) 2021 Darcy Shen
;;
;; This software falls under the GNU general public license version 3 or later.
;; It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE
;; in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(use-modules (dynamic session-edit) (dynamic program-edit))

(define (tikz-serialize lan t)
(with u (pre-serialize lan t)
(with s (texmacs->code (stree->tree u) "SourceCode")
(string-append s "\n<EOF>\n"))))

(define (tikz-launcher)
(if (url-exists? "$TEXMACS_HOME_PATH/plugins/tikz")
(string-append (python-command) " \""
(getenv "TEXMACS_HOME_PATH")
"/plugins/tikz/bin/tikz.pex\"")
(string-append (python-command) " \""
(getenv "TEXMACS_PATH")
"/plugins/tikz/bin/tikz.pex\"")))

(plugin-configure tikz
(:require (python-command))
(:require (url-exists-in-path? "pdflatex"))
(:launch ,(tikz-launcher))
(:serializer ,tikz-serialize)
(:session "TikZ"))

92 changes: 92 additions & 0 deletions tmpy/graph/pdflatex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
#!/usr/bin/env python
###############################################################################
##
## MODULE : pdflatex.py
## DESCRIPTION : LaTeX graphics support
## COPYRIGHT : (C) 2019 Darcy Shen and Massimiliano Gubinelli
##
## This software falls under the GNU general public license version 3 or later.
## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE
## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>.

import os
import shutil
from subprocess import Popen, PIPE, STDOUT
from tmpy.graph.graph import Graph
from tmpy.protocol import flush_file, flush_err, flush_verbatim


class PDFLaTeX(Graph):
"""
TeXmacs interface to PDFLaTeX for picture generation
"""

def __init__(self, name="pdflatex"):
super().__init__()
self.name = name
self.cmd = "pdflatex"
self.message = "TeXmacs interface to PDFLaTeX for picture generation"

def available(self):
return shutil.which(self.cmd) is not None

def greet(self):
if not self.message:
try:
with Popen([self.cmd, "--version"], stderr=PIPE) as p:
out, err = p.communicate()
if p.returncode == 0:
self.message = err.decode()
else:
self.message = out
except OSError:
pass
super().greet()

def kpsewhich(self, name):
"""use kpsewhich to find latex package."""
cmd = ["kpsewhich", name]
with Popen(cmd, stdout=PIPE, stderr=STDOUT) as p:
out, _err = p.communicate()
if p.returncode == 0:
return out
return ""

def evaluate(self, code):
if not code.lstrip().startswith("\\documentclass"):
flush_err(
"I expect a valid LaTeX document, usually starting with\n"
+ " \\documentclass{standalone}\n"
+ "which will take proper care of suitable bounding box for the image.\n"
+ "The document is sent to latex and then to dvips to produce a single image."
)
flush_verbatim("")
return

code_path = self.get_tmp_dir() + self.name + ".tex"
pdf_path = self.get_tmp_dir() + self.name + ".pdf"

with open(code_path, "wb") as code_file:
code_file.write(code.encode())

args = [
self.cmd,
"--interaction=errorstopmode",
"-halt-on-error",
code_path,
]

# flush_err (code) # to debug
phase = "PDFLaTeX"
# flush_err ("Running " + phase)
os.chdir(self.get_tmp_dir())
with Popen(args, stdout=PIPE, stderr=STDOUT) as p:
out, _err = p.communicate()
if p.returncode == 0:
phase = "Finished"
# flush_err ("Running " + phase)
size_param = f"?width={self.width}&height={self.height}"
flush_file(pdf_path + size_param)
return
flush_err(phase + " error!\n" + out.decode())
flush_verbatim("") # otherwise TeXmacs keeps waiting output
55 changes: 55 additions & 0 deletions tmpy/graph/tikz.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env python
###############################################################################
##
## MODULE : tikz.py
## DESCRIPTION : TikZ support
## COPYRIGHT : (C) 2019 Darcy Shen, Massimiliano Gubinelli
##
## This software falls under the GNU general public license version 3 or later.
## It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE
## in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>.

from tmpy.graph.pdflatex import PDFLaTeX
from tmpy.protocol import flush_err

PRE_CODE = """
\\documentclass[tikz]{standalone}
\\begin{document}
"""

POST_CODE = """
\\end{document}
"""


class TikZ(PDFLaTeX):
"""
TikZ support
"""

def __init__(self, name="tikz"):
super().__init__()
self.name = name
self.message = "TeXmacs interface to TikZ"

def available(self):
if not super().available():
return False
for sty in ("standalone", "tikz"):
if len(super().kpsewhich(sty + ".sty")) <= 0:
flush_err(
"Failed to find " + sty + ".sty,"
" please install the missing LaTeX packages\n"
)
return False
return True

def evaluate(self, code):
if not code.lstrip().startswith("\\documentclass"):
if code.lstrip().startswith("\\usetikzlibrary"):
pass
elif not code.lstrip().startswith("\\begin{tikzpicture}"):
code = "\\begin{tikzpicture}\n" + code + "\n\\end{tikzpicture}"
code = PRE_CODE + "\n" + code + "\n" + POST_CODE

super().evaluate(code)
Loading