实现 SiYuan 笔记图、表和公式的自动编号和交叉引用

本贴最后更新于 382 天前,其中的信息可能已经时异事殊

对图、表和公式的自动编号和交叉引用是科研笔记最基本的功能,但当前各种笔记系统均未实现该功能。因此,抽出一天时间,利用 Quicker 并结合 C#代码,针对 Siyuan 做了一下尝试。虽然还有待完善,但也基本实现了该功能,见图 11

交叉引用 - 动作信息 - Quicker (getquicker.net)

主要功能:

  1. 实现对图进行自动编号,同时增减图刷新后,编号将进行全自动更新;

  2. 实现对表进行自动编号,同时增减表刷新后,编号将进行全自动更新;

  3. 实现对公式进行自动编号,同时增减公式刷新后,编号将进行全自动更新;

  4. 实现了对图表和公式的交叉引用,同时增删图表和公式后将自动更新交叉引用

image

图 1 界面

主要代码如下:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

public static string Exec(string paramValue)
{
	JObject Jobj=JObject.Parse(paramValue);
	string block_id = (string)Jobj["block_id"];
	string API_token= (string)Jobj["API_token"];
	string cmd = (string)Jobj["cmd"];
	string data = (string)Jobj["data"];
	if (cmd.ToLower()=="setcaption"){
		SetCaption(data, block_id,API_token);
	} else if (cmd.ToLower()=="clear"){
		ClearCaptionInfo(block_id,API_token);
	} else if (cmd.ToLower()=="update") {
		UpdateCaptions(block_id,API_token);
	}



	return "";
}

private static Dictionary<string, string> ial2JSON(string ial, string mk)
{
	Dictionary<string, string> mydict = new Dictionary<string, string>();
	foreach (Match m in Regex.Matches(ial, "([\\w-]+)=\"([^\"]*)\""))
	{
		mydict.Add(m.Groups[1].Value, m.Groups[2].Value);
	}
	mydict.Add("mk", mk);
	return mydict;
}
public static string ClearCaptionInfo(string block_id, string Token)
{
	SYAPI siyuanAPI = new SYAPI(Token);
	JObject myJobj = new JObject();
	myJobj["custom-type"] = "";
	myJobj["custom-id"] = "";
	myJobj["name"] = "";
	siyuanAPI.SetBlockAttrs(block_id, myJobj);
	siyuanAPI.PushMsg("已完成更新!");
	return "";
}
public static string SetCaption(string CaptionLabel, string block_id, string Token)
{
    SYAPI siyuanAPI = new SYAPI(Token);       
    JObject result=siyuanAPI.SQL_query(string.Format("Select markdown from blocks where id='{0}'", block_id));
    string cmk = (string)result["data"][0]["markdown"];
    Dictionary<string, string> cdict = new Dictionary<string, string>()
    {
        { "custom-type",CaptionLabel},
        { "custom-id","1"},
        { "name",CaptionLabel+" 1"},
        { "id",block_id},
        { "mk",cmk}
    };
    string doc_id = siyuanAPI.GetDocumentIDbyBlockID(block_id);
   result = siyuanAPI.SQL_query(string.Format("select markdown,ial from blocks where id in (SELECT block_id FROM attributes where name='custom-type' and root_id='{0}') ", doc_id));
    List<Dictionary<string, string>> data = result["data"].Select(x => ial2JSON((string)x["ial"], (string)x["markdown"])).ToList<Dictionary<string, string>>();
    data.Add(cdict);
    result = siyuanAPI.GetChildBlocks(doc_id);
    List<string> idx = result["data"].Select(x => (string)x["id"]).ToList<string>();
    data = data.OrderBy(mdict => idx.IndexOf(mdict["id"])).ToList();

    Dictionary<string, int> CaptionDictID = new Dictionary<string, int>();
    foreach (Dictionary<string, string> item in data)
    {
        string captionLabel = item["custom-type"];
        int seqID = int.Parse(item["custom-id"]);
        string id = item["id"];
        string name = item["name"];
        string mk = item["mk"];
        if (CaptionDictID.Keys.Contains(captionLabel))
        {
            CaptionDictID[captionLabel] += 1;
        }
        else
        {
            CaptionDictID[captionLabel] = 1;
        }

        if ((new string[] { "式", "equation", "eq", "eq.", "公式" }).Contains(captionLabel.ToLower()))
        {
            mk = Regex.Replace(mk, "^\\$\\$", "");
            mk = Regex.Replace(mk, "\\$\\$$", "");
            mk = Regex.Replace(mk.Trim(), @"\\tag ?\{ ?(\d+-)?\d+ ?\}", "");
            name = captionLabel + " " + CaptionDictID[captionLabel].ToString();
            siyuanAPI.UpdateBlock(id, string.Format("$${0}\\tag{{{1}{2}}}$$", mk.Trim(), "", CaptionDictID[captionLabel]));
        }
        else
        {
            string pattern = string.Format("^(?<header>[#\\* ]*)(?<CaptionLabel>{0} \\d{{1,3}})?(?<last>.*)$", captionLabel);
            GroupCollection groups = Regex.Match(mk, pattern).Groups;
            mk = groups["header"].ToString().Trim() + captionLabel + " " + CaptionDictID[captionLabel].ToString() + " " + groups["last"].ToString().Trim();
            siyuanAPI.UpdateBlock(id, mk);
        }

        JObject  myJobj = new JObject();
        myJobj["custom-type"] = captionLabel;
        myJobj["custom-id"] = CaptionDictID[captionLabel].ToString();
        myJobj["name"] = captionLabel + " " + CaptionDictID[captionLabel].ToString();
        siyuanAPI.SetBlockAttrs(id, myJobj);
        }

	return "";
}


public static void UpdateCaptions(string block_id, string Token)
{
	SYAPI siyuanAPI = new SYAPI(Token);
	string doc_id = siyuanAPI.GetDocumentIDbyBlockID(block_id);
	JObject result = siyuanAPI.SQL_query(string.Format("select markdown,ial from blocks where id in (SELECT block_id FROM attributes where name='custom-type' and root_id='{0}') ", doc_id));
	List<Dictionary<string, string>> data = result["data"].Select(x => ial2JSON((string)x["ial"], (string)x["markdown"])).ToList<Dictionary<string, string>>();
	result = siyuanAPI.GetChildBlocks(doc_id);
	List<string> idx = result["data"].Select(x => (string)x["id"]).ToList<string>();
	data = data.OrderBy(mdict => idx.IndexOf(mdict["id"])).ToList();

	Dictionary<string, int> CaptionDictID = new Dictionary<string, int>();
	foreach (Dictionary<string, string> item in data)
	{
		string captionLabel = item["custom-type"];
		int seqID = int.Parse(item["custom-id"]);
		string id = item["id"];
		string name = item["name"];
		string mk = item["mk"];
		if (CaptionDictID.Keys.Contains(captionLabel))
		{
			CaptionDictID[captionLabel] += 1;
		}
		else
		{
			CaptionDictID[captionLabel] = 1;
		}

		if ((new string[] { "式", "equation", "eq", "eq.", "公式" }).Contains(captionLabel.ToLower()))
		{
			mk = Regex.Replace(mk, "^\\$\\$", "");
			mk = Regex.Replace(mk, "\\$\\$$", "");
			mk = Regex.Replace(mk.Trim(), @"\\tag ?\{ ?(\d+-)?\d+ ?\}", "");
			name = captionLabel + " " + CaptionDictID[captionLabel].ToString();
			siyuanAPI.UpdateBlock(id, string.Format("$${0}\\tag{{{1}{2}}}$$", mk.Trim(), "", CaptionDictID[captionLabel]));
		}
		else
		{
			string pattern = string.Format("^(?<header>[#\\* ]*)(?<CaptionLabel>{0} \\d{{1,3}})?(?<last>.*)$", captionLabel);
			GroupCollection groups = Regex.Match(mk, pattern).Groups;
			mk = groups["header"].ToString().Trim() + captionLabel + " " + CaptionDictID[captionLabel].ToString() + " " + groups["last"].ToString().Trim();
			siyuanAPI.UpdateBlock(id, mk);
		}

		JObject myJobj = new JObject();
		myJobj["custom-type"] = captionLabel;
		myJobj["custom-id"] = CaptionDictID[captionLabel].ToString();
		myJobj["name"] = captionLabel + " " + CaptionDictID[captionLabel].ToString();
		siyuanAPI.SetBlockAttrs(id, myJobj);
	}

	siyuanAPI.PushMsg("已完成更新!");
}



public class SYAPI
{
	private string _TokenID;
	public SYAPI(string TokenID)
	{
		_TokenID = TokenID;
	}

	private async Task<JObject> CommandAsync(string path, JObject data)
	{
		string url = "http://127.0.0.1:6806";
		url = url + path;
		var body = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
		using (HttpClient client = new HttpClient())
		{
			client.DefaultRequestHeaders.Add("Authorization", "Token " + _TokenID);
			HttpResponseMessage response = await client.PostAsync(url, body);
			response.EnsureSuccessStatusCode();
			string responseBody = await response.Content.ReadAsStringAsync();
			return (JObject.Parse(responseBody));
		}

	}
	public JObject lsNotebooksAsync()
	{
		return (CommandAsync("/api/notebook/lsNotebooks", new JObject()).Result);
	}
	public JObject PushMsg(string msg)
	{
		return CommandAsync("/api/notification/pushMsg",
		                    JObject.FromObject(new
		                                       {
		                                       	msg = msg,
		                                       	timeout = 7000
		                                       })).Result;

	}
	public JObject PushErrMsg(string msg)
	{
		return CommandAsync("/api/notification/pushMsg",
		                    JObject.FromObject(new
		                                       {
		                                       	msg = msg,
		                                       	timeout = 7000
		                                       })).Result;

	}
	public JObject SQL_query(string SQL)
	{
		return CommandAsync("/api/query/sql",
		                    JObject.FromObject(new
		                                       {
		                                       	stmt = SQL,
		                                       })).Result;

	}

	#region Block块
	public JObject UpdateBlock(string block_id, string markdown, string dataType = "markdown")
	{
		return CommandAsync("/api/block/updateBlock",
		                    JObject.FromObject(new
		                                       {
		                                       	id = block_id,
		                                       	dataType = dataType,
		                                       	data = markdown
		                                       })).Result;

	}
	public JObject GetBlockInfo(string block_id)
	{
		return CommandAsync("/api/block/getBlockInfo",
		                    JObject.FromObject(new
		                                       {
		                                       	id = block_id,
		                                       })).Result;

	}
	public JObject GetBlockKramdown(string block_id)
	{
		return CommandAsync("/api/block/getBlockKramdown", JObject.FromObject(new
		                                                                      {
		                                                                      	id = block_id,
		                                                                      })).Result;
	}

	public JObject GetChildBlocks(string block_id)
	{
		return CommandAsync("/api/block/getChildBlocks", JObject.FromObject(new
		                                                                    {
		                                                                    	id = block_id
		                                                                    })).Result;
	}

	public JObject SetBlockAttrs(string block_id, object dict)
	{

		return CommandAsync("/api/attr/setBlockAttrs", JObject.FromObject(new
		                                                                  {
		                                                                  	id = block_id,
		                                                                  	attrs = JObject.FromObject(dict),
		                                                                  })).Result;
	}

	public JObject ResetBlockAttrs(string block_id, object dict)
	{

		return CommandAsync("/api/attr/resetBlockAttrs", JObject.FromObject(new
		                                                                    {
		                                                                    	id = block_id,
		                                                                    	attrs = JObject.FromObject(dict),
		                                                                    })).Result;
	}
	#endregion

	#region Document
	public string GetDocumentIDbyBlockID(string block_id)
	{
		JObject result = SQL_query(string.Format(" select root_id from blocks where id='{0}'", block_id));
		return (string)result["data"][0]["root_id"];
	}

	#endregion
}


  1. 图 1 界面

  • 公式
    5 引用 • 24 回帖
  • 思源笔记

    思源笔记是一款隐私优先的个人知识管理系统,支持完全离线使用,同时也支持端到端加密同步。

    融合块、大纲和双向链接,重构你的思维。

    20197 引用 • 78022 回帖
  • C#
    29 引用 • 34 回帖 • 5 关注
  • Quicker

    Quicker 您的指尖工具箱!操作更少,收获更多!

    26 引用 • 85 回帖 • 1 关注
1 操作
ttChen 在 2023-07-08 20:51:27 更新了该帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • 只能通过更新块 API 做到更新行内元素。

    2 回复
  • 其他回帖
  • 是的,做不到仅修改部分行级元素,用 kramdown 只能整块更新。

    1 回复
  • ttChen

    @88250 最近在开发一款 Siyuan 的文献管理插件。已知 Siyuan 可以通过 setBlockAttrs API 函数修改块的属性,通过·updateBlock API 函数更新块的内容,都是基于块的,请问有没有一种 API 函数能更新行内元素的内容和属性?这对开发文献管理插件非常有帮助。

    image.png

    1 回复
  • 只能把加背景的这几个字改成加粗,比如:

    {
        "id": "20230712190919-obqieuq",
        "dataType": "markdown",
        "data": "foo ((20230712211410-ktc4oa8 'bar')) baz **bazz**{: style=\"background-color: var(--b3-font-background1);\"}^[1]^\n{: updated=\"20230712211420\" id=\"20230712190919-obqieuq\"}"
    }
    
    1 回复
  • 查看全部回帖

推荐标签 标签

  • Wide

    Wide 是一款基于 Web 的 Go 语言 IDE。通过浏览器就可以进行 Go 开发,并有代码自动完成、查看表达式、编译反馈、Lint、实时结果输出等功能。

    欢迎访问我们运维的实例: https://wide.b3log.org

    30 引用 • 218 回帖 • 615 关注
  • Markdown

    Markdown 是一种轻量级标记语言,用户可使用纯文本编辑器来排版文档,最终通过 Markdown 引擎将文档转换为所需格式(比如 HTML、PDF 等)。

    165 引用 • 1475 回帖
  • Swagger

    Swagger 是一款非常流行的 API 开发工具,它遵循 OpenAPI Specification(这是一种通用的、和编程语言无关的 API 描述规范)。Swagger 贯穿整个 API 生命周期,如 API 的设计、编写文档、测试和部署。

    26 引用 • 35 回帖
  • BookxNote

    BookxNote 是一款全新的电子书学习工具,助力您的学习与思考,让您的大脑更高效的记忆。

    笔记整理交给我,一心只读圣贤书。

    1 引用 • 1 回帖 • 1 关注
  • Google

    Google(Google Inc.,NASDAQ:GOOG)是一家美国上市公司(公有股份公司),于 1998 年 9 月 7 日以私有股份公司的形式创立,设计并管理一个互联网搜索引擎。Google 公司的总部称作“Googleplex”,它位于加利福尼亚山景城。Google 目前被公认为是全球规模最大的搜索引擎,它提供了简单易用的免费服务。不作恶(Don't be evil)是谷歌公司的一项非正式的公司口号。

    49 引用 • 192 回帖
  • CentOS

    CentOS(Community Enterprise Operating System)是 Linux 发行版之一,它是来自于 Red Hat Enterprise Linux 依照开放源代码规定释出的源代码所编译而成。由于出自同样的源代码,因此有些要求高度稳定的服务器以 CentOS 替代商业版的 Red Hat Enterprise Linux 使用。两者的不同在于 CentOS 并不包含封闭源代码软件。

    238 引用 • 224 回帖
  • Sandbox

    如果帖子标签含有 Sandbox ,则该帖子会被视为“测试帖”,主要用于测试社区功能,排查 bug 等,该标签下内容不定期进行清理。

    390 引用 • 1246 回帖 • 593 关注
  • Laravel

    Laravel 是一套简洁、优雅的 PHP Web 开发框架。它采用 MVC 设计,是一款崇尚开发效率的全栈框架。

    19 引用 • 23 回帖 • 704 关注
  • 深度学习

    深度学习(Deep Learning)是机器学习的分支,是一种试图使用包含复杂结构或由多重非线性变换构成的多个处理层对数据进行高层抽象的算法。

    41 引用 • 40 回帖
  • Sphinx

    Sphinx 是一个基于 SQL 的全文检索引擎,可以结合 MySQL、PostgreSQL 做全文搜索,它可以提供比数据库本身更专业的搜索功能,使得应用程序更容易实现专业化的全文检索。

    1 引用 • 193 关注
  • 开源中国

    开源中国是目前中国最大的开源技术社区。传播开源的理念,推广开源项目,为 IT 开发者提供了一个发现、使用、并交流开源技术的平台。目前开源中国社区已收录超过两万款开源软件。

    7 引用 • 86 回帖
  • 友情链接

    确认过眼神后的灵魂连接,站在链在!

    24 引用 • 373 回帖
  • 负能量

    上帝为你关上了一扇门,然后就去睡觉了....努力不一定能成功,但不努力一定很轻松 (° ー °〃)

    88 引用 • 1234 回帖 • 438 关注
  • abitmean

    有点意思就行了

    36 关注
  • OkHttp

    OkHttp 是一款 HTTP & HTTP/2 客户端库,专为 Android 和 Java 应用打造。

    16 引用 • 6 回帖 • 50 关注
  • WebComponents

    Web Components 是 W3C 定义的标准,它给了前端开发者扩展浏览器标签的能力,可以方便地定制可复用组件,更好的进行模块化开发,解放了前端开发者的生产力。

    1 引用 • 3 关注
  • Q&A

    提问之前请先看《提问的智慧》,好的问题比好的答案更有价值。

    7042 引用 • 31864 回帖 • 218 关注
  • Flutter

    Flutter 是谷歌的移动 UI 框架,可以快速在 iOS 和 Android 上构建高质量的原生用户界面。 Flutter 可以与现有的代码一起工作,它正在被越来越多的开发者和组织使用,并且 Flutter 是完全免费、开源的。

    39 引用 • 92 回帖
  • 尊园地产

    昆明尊园房地产经纪有限公司,即:Kunming Zunyuan Property Agency Company Limited(简称“尊园地产”)于 2007 年 6 月开始筹备,2007 年 8 月 18 日正式成立,注册资本 200 万元,公司性质为股份经纪有限公司,主营业务为:代租、代售、代办产权过户、办理银行按揭、担保、抵押、评估等。

    1 引用 • 22 回帖 • 709 关注
  • 数据库

    据说 99% 的性能瓶颈都在数据库。

    333 引用 • 619 回帖
  • RYMCU

    RYMCU 致力于打造一个即严谨又活泼、专业又不失有趣,为数百万人服务的开源嵌入式知识学习交流平台。

    4 引用 • 6 回帖 • 43 关注
  • Shell

    Shell 脚本与 Windows/Dos 下的批处理相似,也就是用各类命令预先放入到一个文件中,方便一次性执行的一个程序文件,主要是方便管理员进行设置或者管理用的。但是它比 Windows 下的批处理更强大,比用其他编程程序编辑的程序效率更高,因为它使用了 Linux/Unix 下的命令。

    122 引用 • 73 回帖
  • 酷鸟浏览器

    安全 · 稳定 · 快速
    为跨境从业人员提供专业的跨境浏览器

    3 引用 • 59 回帖 • 25 关注
  • Webswing

    Webswing 是一个能将任何 Swing 应用通过纯 HTML5 运行在浏览器中的 Web 服务器,详细介绍请看 将 Java Swing 应用变成 Web 应用

    1 引用 • 15 回帖 • 622 关注
  • Windows

    Microsoft Windows 是美国微软公司研发的一套操作系统,它问世于 1985 年,起初仅仅是 Microsoft-DOS 模拟环境,后续的系统版本由于微软不断的更新升级,不但易用,也慢慢的成为家家户户人们最喜爱的操作系统。

    216 引用 • 463 回帖
  • TGIF

    Thank God It's Friday! 感谢老天,总算到星期五啦!

    285 引用 • 4482 回帖 • 660 关注
  • Typecho

    Typecho 是一款博客程序,它在 GPLv2 许可证下发行,基于 PHP 构建,可以运行在各种平台上,支持多种数据库(MySQL、PostgreSQL、SQLite)。

    12 引用 • 60 回帖 • 464 关注