Rust的Markdown渲染库egui_commonmark_backend的使用,为egui UI框架提供高性能CommonMark解析与渲染功能

Rust的Markdown渲染库egui_commonmark_backend的使用,为egui UI框架提供高性能CommonMark解析与渲染功能

简介

这是一个为egui UI框架提供的CommonMark查看器。它包含了egui_commonmarkegui_commonmark_macros两个crate之间共享的代码。

许可证

可选择以下任一许可证:

  • Apache License, Version 2.0
  • MIT license

安装

在项目目录中运行以下Cargo命令:

cargo add egui_commonmark_backend

或者在Cargo.toml中添加以下行:

egui_commonmark_backend = "0.21.0"

完整示例代码

以下是一个使用egui_commonmark_backend的完整示例:

use eframe::egui;
use egui_commonmark_backend::{CommonMarkCache, CommonMarkViewer};

struct MyApp {
    cache: CommonMarkCache,
    markdown: String,
}

impl Default for MyApp {
    fn default() -> Self {
        Self {
            cache: CommonMarkCache::default(),
            markdown: String::from(
                r#"
# Hello, egui_commonmark!

This is a **Markdown** viewer for egui.

## Features

- Supports CommonMark spec
- Fast parsing and rendering
- Easy to integrate with egui

```rust
fn main() {
    println!("Hello, world!");
}

"#, ), } } }

impl eframe::App for MyApp { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { egui::CentralPanel::default().show(ctx, |ui| { // 创建一个可滚动的区域来显示Markdown egui::ScrollArea::vertical().show(ui, |ui| { // 使用CommonMarkViewer来渲染Markdown CommonMarkViewer::new(“viewer”) .max_image_width(Some(512)) .show(ui, &mut self.cache, &self.markdown); }); }); } }

fn main() { let options = eframe::NativeOptions::default(); eframe::run_native( “Markdown Viewer”, options, Box::new(|_cc| Box::new(MyApp::default())), ); }


## 代码说明

1. `CommonMarkCache` - 用于缓存已解析的Markdown内容,提高渲染性能
2. `CommonMarkViewer` - 主要的Markdown渲染组件
   - `new("viewer")` - 创建一个新的查看器实例,需要提供唯一的ID
   - `max_image_width(Some(512))` - 设置图片最大宽度
   - `show()` - 渲染Markdown内容

## 文档

更多详细用法请参考官方文档

## 仓库

项目源码位于

1 回复

egui_commonmark_backend - 为egui UI框架提供高性能CommonMark渲染功能

简介

egui_commonmark_backend 是一个Rust库,它为流行的即时模式GUI框架egui提供了CommonMark(Markdown)渲染支持。这个库允许开发者在egui应用程序中轻松地渲染和显示Markdown格式的内容。

主要特性

  • 高性能CommonMark解析与渲染
  • 与egui的无缝集成
  • 支持基本的Markdown语法
  • 可定制的渲染样式
  • 轻量级实现

使用方法

添加依赖

首先,在你的Cargo.toml中添加依赖:

[dependencies]
egui_commonmark_backend = "0.1"
egui = "0.21"  # 或其他兼容版本

基本使用示例

use egui_commonmark_backend::{CommonMarkCache, CommonMarkViewer};
use egui::{CentralPanel, Context};

fn ui(ui: &mut egui::Ui) {
    let mut cache = CommonMarkCache::default();
    let mut viewer = CommonMarkViewer::new("markdown_viewer");
    
    let markdown_content = r#"
# 标题1
## 标题2

这是一个段落,包含*斜体*和**粗体**文本。

- 列表项1
- 列表项2
    - 嵌套列表项

`代码片段`

```rust
fn main() {
    println!("Hello, world!");
}
"#;

viewer.show(ui, &mut cache, markdown_content);

}

fn main() { let options = eframe::NativeOptions::default(); eframe::run_native( “Markdown示例”, options, Box::new(|_cc| Box::new(MyApp)), ); }

struct MyApp;

impl eframe::App for MyApp { fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) { CentralPanel::default().show(ctx, |ui| { ui(ui); }); } }


### 自定义样式

你可以通过修改`CommonMarkCache`来自定义Markdown的渲染样式:

```rust
use egui::{Color32, FontId};

fn custom_style(ui: &mut egui::Ui, cache: &mut CommonMarkCache) {
    // 修改标题样式
    cache.set_header_font(FontId::proportional(24.0));
    cache.set_header_color(Color32::from_rgb(100, 150, 200));
    
    // 修改代码块背景色
    cache.set_code_background(Color32::from_rgb(40, 40, 40));
    
    // 修改链接颜色
    cache.set_link_color(Color32::from_rgb(0, 200, 100));
}

高级用法:处理链接点击

use egui_commonmark_backend::CommonMarkEvent;

fn handle_events(viewer: &mut CommonMarkViewer) {
    if let Some(event) = viewer.get_event() {
        match event {
            CommonMarkEvent::LinkClicked(url) => {
                println!("链接被点击: {}", url);
                // 在这里处理链接点击事件,例如打开浏览器
            }
        }
    }
}

完整示例代码

use egui_commonmark_backend::{CommonMarkCache, CommonMarkViewer, CommonMarkEvent};
use egui::{CentralPanel, Context, Color32, FontId};
use eframe;

fn main() {
    let options = eframe::NativeOptions::default();
    eframe::run_native(
        "Markdown完整示例",
        options,
        Box::new(|_cc| Box::new(MyApp::default())),
    );
}

#[derive(Default)]
struct MyApp {
    cache: CommonMarkCache,
    viewer: CommonMarkViewer,
    markdown_content: String,
}

impl MyApp {
    fn new() -> Self {
        let mut cache = CommonMarkCache::default();
        // 自定义样式
        cache.set_header_font(FontId::proportional(24.0));
        cache.set_header_color(Color32::from_rgb(100, 150, 200));
        cache.set_code_background(Color32::from_rgb(40, 40, 40));
        cache.set_link_color(Color32::from_rgb(0, 200, 100));
        
        Self {
            cache,
            viewer: CommonMarkViewer::new("markdown_viewer"),
            markdown_content: r#"
# 示例文档

这是一个使用`egui_commonmark_backend`的完整示例。

## 功能展示

- **粗体**和*斜体*文本
- `内联代码`
- [链接示例](#)
- 列表项
    - 嵌套列表

```rust
// 代码块示例
fn main() {
    println!("Hello, egui_commonmark_backend!");
}

引用文本 "#.to_string(), } } }

impl eframe::App for MyApp { fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) { CentralPanel::default().show(ctx, |ui| { // 渲染Markdown内容 self.viewer.show(ui, &mut self.cache, &self.markdown_content);

        // 处理链接点击事件
        if let Some(event) = self.viewer.get_event() {
            match event {
                CommonMarkEvent::LinkClicked(url) => {
                    println!("链接被点击: {}", url);
                    // 实际应用中可添加链接处理逻辑
                }
            }
        }
    });
}

}


## 注意事项

1. 该库支持CommonMark标准,但可能不支持所有Markdown扩展语法
2. 性能优化对于大型Markdown文档很重要,考虑分块渲染
3. 样式自定义需要在渲染前完成

## 替代方案

如果你需要更完整的Markdown支持,可以考虑:
- `pulldown-cmark` + 自定义egui渲染
- `comrak` 作为解析器后端

`egui_commonmark_backend` 提供了在egui中渲染Markdown的最简单直接的方式,特别适合需要基本Markdown支持的egui应用程序。
回到顶部