在阅读Pygments的formatters文档(https://pygments.org/docs/formatters/)时,我找不到在使用ImageFormatter时如何换行以便将突出显示的代码导出为png图像。
下面是我的代码:
from pygments.lexers import PythonLexer
from pygments.formatters import ImageFormatter
from pygments import highlight
code = 'print("Reading through Pygments\' formatters doc (https://pygments.org/docs/formatters/), I cannot find how to wrap code when using the ImageFormatter in order to export my highlighted code to a png image (i.e. let\'s say I want my image to be 600px, or 300 characters at font size, wide). It seems like wrapping is essential when exporting to an image, is the option missing from Pygments at this moment?")'
formatter = ImageFormatter()
with open("highlighted1.png", "wb") as f:
f.write(highlight(code, PythonLexer(), formatter))它会生成这样的图像(许多应用程序都无法使用):

在导出到图像时,包装似乎是必不可少的,目前Pygments中是否缺少该选项?
发布于 2020-03-11 16:12:52
pygments库中缺少换行选项。
您可以扩展ImageFormatter并覆盖其format方法,以插入新行标记和换行代码行。向format method传递一个令牌列表。
更准确地说,专注于对Token.Literal.String.Double令牌执行此过程。
否则,请在将code正确传递到highlight函数之前对其进行格式化。您可以手动执行此操作,也可以使用linter以编程方式执行此操作。大多数linter都不能修复长字符串。
以autopep8为例,它对代码没有任何影响
import autopep8
autopep8.fix_code(code, options=autopep8.parse_args(['']))code必须手动编写为:
code = """
print(
"Reading through Pygments' formatters doc(https://pygments.org/docs/formatters/), "
"I cannot find how to wrap code when using the ImageFormatter in order to export my "
"highlighted code to a png image (i.e. let's say I want my image to be 600px, "
"or 300 characters at font size, wide). It seems like wrapping is essential "
"when exporting to an image, is the option missing from Pygments at this moment?"
)
"""https://stackoverflow.com/questions/60480115
复制相似问题