1.0.0开始重构,实现了Style

This commit is contained in:
跨越晨昏 2024-09-30 17:12:54 +08:00
parent aefe325649
commit 989c9accaa
7 changed files with 269 additions and 162 deletions

96
CrossDown/Core.py Normal file
View File

@ -0,0 +1,96 @@
from markdown.extensions import Extension
from markdown.treeprocessors import Treeprocessor
from markdown.inlinepatterns import Pattern
from markdown.preprocessors import Preprocessor
from markdown import Markdown
from typing import *
import re
Extensions = {
"Extra": "markdown.extensions.extra",
"Abbreviations": "markdown.extensions.abbr",
"Attribute Lists": "markdown.extensions.attr_list",
"Definition Lists": "markdown.extensions.def_list",
"Fenced Code Blocks": "markdown.extensions.fenced_code",
"Footnotes": "markdown.extensions.footnotes",
"Tables": "markdown.extensions.tables",
# "Smart Strong": "markdown.extensions.smart_strong",
"Admonition": "markdown.extensions.admonition",
"CodeHilite": "markdown.extensions.codehilite",
# "HeaderId": "markdown.extensions.headerid",
"Meta-Data": "markdown.extensions.meta",
"New Line to Break": "markdown.extensions.nl2br",
"Sane Lists": "markdown.extensions.sane_lists",
"SmartyPants": "markdown.extensions.smarty",
"Table of Contents": "markdown.extensions.toc",
"WikiLinks": "markdown.extensions.wikilinks",
}
class Style(Preprocessor):
"""
渲染字体样式
"""
@staticmethod
def underline(text):
"""
~下划线~
:return:
"""
return re.sub(r'~([^~\n]+)~', r'<u>\1</u>', text)
@staticmethod
def strikethrough(text):
"""
~~删除线~~
:return:
"""
return re.sub(r'~~([^~\n]+)~~', r'<s>\1</s>', text)
@staticmethod
def highlight(text):
"""
==高亮==
:return:
"""
return re.sub(r'==([^=\n]+)==', r'<mark>\1</mark>', text)
@staticmethod
def up(text):
"""
[在文本的正上方添加一行小文本]^(主要用于标拼音)
:return:
"""
return re.sub(r'\[(.*?)]\^\((.*?)\)', r'<ruby>\1<rt>\2</rt></ruby>', text)
@staticmethod
def hide(text):
"""
[在指定的文本里面隐藏一段文本]-(只有鼠标放在上面才会显示隐藏文本)
:return:
"""
return re.sub(r'\[(.*?)]-\((.*?)\)', r'<span title="\2">\1</span>', text)
def run(self, lines):
new_line = []
for line in lines:
line = self.strikethrough(line) # 渲染删除线
line = self.underline(line) # 渲染下划线
line = self.highlight(line) # 渲染高亮
line = self.up(line) # 渲染上部文本
line = self.hide(line) # 渲染隐藏文本
new_line.append(line)
return new_line
class Core(Extension):
def extendMarkdown(self, md):
md.registerExtension(self) # 注册扩展
md.preprocessors.register(Style(md), 'custom_preprocessor', 0)
def main(text):
md = Markdown(extensions=[Core()] + list(Extensions.values()))
return md.convert(text), md.Meta

View File

@ -1,4 +0,0 @@
from markdown.extensions import Extension
from markdown.treeprocessors import Treeprocessor
from markdown.inlinepatterns import Pattern
from markdown import Markdown

View File

@ -0,0 +1,54 @@
from typing import *
from .Core import main
__all__ = [
'main', # 主函数
'indent', # 添加空格
'HEAD', #
'BODY', #
]
__version__ = '0.11.2'
__author__ = 'CrossDark'
__email__ = 'liuhanbo333@icloud.com'
__source__ = 'https://crossdark.net/'
__license__ = """MIT"""
HEAD = (
'<script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML"></script>',
'<link href="https://cdn.jsdelivr.net/npm/prismjs/themes/prism.css" rel="stylesheet" />',
'<script src="https://cdn.jsdelivr.net/npm/prismjs/prism.js"></script>',
'<script src="https://cdn.jsdelivr.net/npm/prismjs/components/prism-yaml.min.js"></script>',
'<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>',
'<style>',
' .block {',
' background-color: grey; /* 灰色背景 */',
' color: white; /* 白色文字 */',
'}',
'</style>'
)
BODY = (
'<script>',
' mermaid.initialize({{startOnLoad:true}});',
'</script>',
'<script>',
' document.addEventListener("DOMContentLoaded", function() {',
' emojify.run();',
'});',
'</script>',
)
def indent(input_: Union[str, List, Tuple], indent_spaces: int = 4) -> str:
"""
给字符串中的每一行前面加上缩进
:param input_: 原始字符串可以包含多行
:param indent_spaces: 每行前面要添加的空格数默认为4
:return: 带缩进的新字符串
"""
# 使用字符串的splitlines()方法分割原始字符串为行列表,如果是可迭代对象则直接遍历
# 遍历行列表,给每行前面加上相应的缩进,并重新组合成字符串
return "\n".join(
f"{' ' * indent_spaces}{line}" for line in (lambda x: x.splitlines() if isinstance(x, str) else x)(input_))

View File

@ -6,7 +6,6 @@ import markdown
try: # 检测当前平台是否支持扩展语法 try: # 检测当前平台是否支持扩展语法
import CrossMore import CrossMore
EXTRA_ABLE = True EXTRA_ABLE = True
except ModuleNotFoundError: except ModuleNotFoundError:
EXTRA_ABLE = False EXTRA_ABLE = False

File diff suppressed because one or more lines are too long

View File

@ -1,10 +1,12 @@
[TOC] Title: My Document
Summary: A brief description of my document.
Authors: Waylan Limberg
John Doe
Date: October 2, 2007
blank-value:
base_url: http://example.com
--- [TOC]
title: "Markdown文档标题"
author: "作者姓名"
date: "2024-09-26"
---
# CrossDown # CrossDown
自制的markdown添加了一些自定义的语法 自制的markdown添加了一些自定义的语法

32
run.py Normal file
View File

@ -0,0 +1,32 @@
import time
from CrossDown import *
if __name__ == '__main__':
# 开始计时
start_time = time.perf_counter_ns()
# 主程序
with open('README.md', encoding='utf-8') as test:
cd, meta = main(test.read())
print(meta)
with open('README.html', 'w', encoding='utf-8') as html:
html.write(f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UTF-8编码示例</title>
{indent(HEAD)}
<!-- 可以在这里添加其他元数据和CSS链接 -->
</head>
<body>
{indent(BODY)}
{indent(cd, 4)}
</body>
</html>
""")
# 停止计时
end_time = time.perf_counter_ns()
# 输出用时
print("运行时间: {:.9f}".format((end_time - start_time) / 1e9))