跳转到主要内容

Syntect语法高亮器的Python绑定。

项目描述

pysyntect

Project License - MIT pypi version conda version download count Downloads PyPI status Linux build MacOS build Windows build

版权所有 © 2020– Spyder 项目贡献者

概述

Python绑定用于Syntect库。Pysyntect提供了一种轻量级、快速的引擎,用于使用Sublime Text语法定义和TextMate主题定义进行语法高亮显示,这些定义被许多编辑器共享。

Python example

安装

要安装pysyntect,您可以使用conda或pip包管理器

# Using Conda (Recommended)
conda install pysyntect -c spyder-ide

# Using pip
pip install pysyntect

依赖关系

要编译pysyntect,您将需要Rust的最新稳定/测试/夜间版本,以及Cargo。此外,它需要一个带有相应开发头文件的Python发行版。最后,此项目依赖于以下Cargo crates

  • PyO3:用于从Rust代码生成Python绑定的库。
  • Syntect:Rust 编程语言中的语法高亮库。
  • Maturin:用于构建和发布基于 Rust 的 Python 包的构建系统

本地编译

除了 Rust 之外,您还需要安装最新版本的 maturin 才能本地编译此项目

pip install maturin toml

安装完这些包后,可以使用以下命令编译 pysyntect

maturin develop

为了生成 wheels,可以使用 maturin build 替代。该项目支持 PEP517,因此也可以使用 pip 安装此软件包

pip install -U .

运行测试

我们使用 pytest 运行测试,如下所示(调用 maturin develop 之后)

pytest -v syntect/tests

包使用

Pysyntect 提供了加载主题和语法定义以及高亮文本字符串的实用工具和函数。Pysyntect 支持超过 500 个跨多个 TextMate 主题定义的 语法语言定义(不包括在本软件包中)。

from syntect import (highlight, load_theme_folder,
                     load_default_syntax, load_syntax_folder,
                     escape_to_console)

# Load default syntax grammars
syntax = load_default_syntax()

# Load syntax grammars from a path
syntax = load_syntax_folder("path/to/a/folder/with/grammars")

# Languages supported by the syntax set
syntax.languages

# Load theme definitions from a path
themes = load_theme_folder("path/to/a/folder/with/themes")

# List of themes loaded
themes.themes

# Select a theme
theme = themes['<name_of_the_theme>']

# Load a file and syntax highlight it
with open('my_file.extension', 'r') as f:
    lines = f.read()

# Returns a list of styles to apply per token
color_ranges = highlight(lines, 'extension', syntax, theme)

# Get background/foreground colors by token
style, token = color_ranges[0]

background = style.background
foreground = style.foreground

components = ('r', 'g', 'b', 'a')
bg_red, bg_green, bg_blue, bg_alpha = [getattr(background, c)
                                       for c in components]
fg_red, fg_green, fg_blue, fg_alpha = [getattr(foreground, c)
                                       for c in components]

# Preview syntax highlighing result to console
escape_to_console(color_ranges, display_bg=True)

更新日志

请参阅我们的 CHANGELOG 文件,了解我们的新功能和改进。

贡献指南

我们遵循 PEP8 和 PEP257 为纯 Python 软件包和 Rust 编译扩展。我们为此软件包中声明的所有函数和类使用 MyPy 类型注解。如果您有任何问题/疑问,请随时发送 PR 或创建问题。

由以下机构支持

AWSAWS 云计算和安全赞助商 DatadogDatadog 监控 FastlyFastly CDN GoogleGoogle 下载分析 MicrosoftMicrosoft PSF 赞助商 PingdomPingdom 监控 SentrySentry 错误日志 StatusPageStatusPage 状态页面