Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

代码高亮不指定语言时使用 hljs.defaultLang 进行渲染 #1382

Closed
raisetwist opened this issue Apr 2, 2023 · 5 comments
Closed
Assignees
Milestone

Comments

@raisetwist
Copy link

raisetwist commented Apr 2, 2023

你在什么场景下需要该功能?

现在如果代码块里不指定语言,代码高亮器会猜一个语言,而如果指定一个不存在的语言,会fallback到不高亮模式。

因为不少自然的md code里都会有不指定语言的代码块,依照情境有时会希望在不指定语言的时候也不高亮,或是当成plaintext处理。大概就是每次parse到一个纯的代码块,在传给hljs之前可以预处理一下。

描述最优的解决方案

在options.preview.hljs里增加一个类似defaultLang的项,可选值最好可以包括

  • guess(默认)
  • disabled(相当于hljs.enable=false,也可叫nohighlight)
  • plaintext(仍apply hljs style但不高亮,相当于```plaintext
  • 或者plaintext之外的任意已有语言。

描述候选的解决方案

因为目前如果要(对部分代码块)跳过hljs,得故意指定一个不存在的语言,希望至少可以有一个无warning实现nohighlight的方法。

@Vanessa219
Copy link
Owner

加一个 ignore 是否够用了?

@raisetwist
Copy link
Author

嗯能够解决主要问题,谢谢啦,以后有机会可以再完善。

@Vanessa219
Copy link
Owner

好像可以用 enable

/** @link https://ld246.com/article/1549638745630#options-preview-hljs */
interface IHljs {
    /** 是否启用行号。默认值: false */
    lineNumber?: boolean;
    /** 代码风格,可选值参见 [Chroma](https://xyproto.github.io/splash/docs/longer/all.html)。 默认值: 'github' */
    style?: string;
    /** 是否启用代码高亮。默认值: true */
    enable?: boolean;
}

@raisetwist
Copy link
Author

啊不是,原来的enable我知道…是这样,markdown里既有不指定语言的代码块,又有指定语言的,如果preview.hljs.enable = false,则一切代码块都不高亮了。

例:

```
I don't want to highlight this.
```

```python
print("but highlight this")
```

@raisetwist
Copy link
Author

不太会pull request,我觉得在src/ts/markdown/highlightRender.ts中调用hljs.highlightElement之前,加入:

if(hljsOption.defaultLang && !block.matches("[class*=language-]")) {
  // no language specified
  if(hljsOption.defaultLang === "nohighlight") block.classList.add("nohighlight"); // hljs supports this and will skip; alternatively, just "return;"
  else if(hljsOption.defaultLang !== "auto") block.classList.add("language-" + hljsOption.defaultLang); // deals with everything else
}

就完全ok了

@Vanessa219 Vanessa219 changed the title 代码高亮不指定语言时的渲染方式 代码高亮不指定语言时使用 hljs.defaultLang 进行渲染 Apr 11, 2023
@Vanessa219 Vanessa219 self-assigned this Apr 11, 2023
@Vanessa219 Vanessa219 added this to the 3.9 milestone Apr 11, 2023
Vanessa219 added a commit that referenced this issue Apr 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants