This commit is contained in:
Heekang Park 2023-02-14 01:02:21 +09:00
parent ed6fae3a67
commit e7b6d543bb
14 changed files with 252 additions and 85 deletions

4
.gitignore vendored
View file

@ -2,5 +2,7 @@
node_modules
# ignore files for local testing
main.js
styles.css
styles.css
data.json

View file

@ -88,15 +88,23 @@ If you want to explicitly hide the line numbers, you can do it like this.
You can highlight specific lines in the code block with commas like this.
```python highlight:"2,3"
print("Hello world")
print("I love you")
print("Wow")
```python highlight:"2-4,8,10"
print("line 1")
print("line 2")
print("line 3")
print("line 4")
print("line 5")
print("line 6")
print("line 7")
print("line 8")
print("line 9")
print("line 10")
print("line 11")
```
![highlight1](https://github.com/HeekangPark/obsidian-hk-code-block/raw/master/imgs/highlight1.png)
You must put the line numbers in quotes. You can use both single and double quotes.
You must put the line numbers in quotes. You can use both single and double quotes. You can also use a dash to specify a range of line numbers.
If you use the line numbers feature and set the line numbers don't start from 1, you must enter the line numbers to be highlighted according to that.
@ -345,8 +353,19 @@ MIT License
- [Typewriter](https://github.com/crashmoney/obsidian-typewriter)
- Most of the theme problem is caused by the usage of `!important` keywords in the theme CSS. HK Code Block does not use `!important` keywords at all in order to avoid conflicts with other themes or plugins. If you want to use HK Code Block plugin with those themes, you should modify the theme CSS files, or by using `!important` keywords, you should explicitly increase the priority of the HK Code Block CSS rules.
## Bug Report, Feature Request
If you find any bugs or have any feature requests, please report them on the GitHub Issues. Thank you!
## Changelog
Versions are controlled by the rule below.
- Version x.y.z
- x : increased when huge changes are made(ex. change of logic, etc.)
- y : increased when features are newly added or changed
- z : increased when bug fixes are made
### 0.1.0
- Initial release
@ -359,4 +378,11 @@ MIT License
### 0.2.1
- Bug fix
- Fix that prompted code blocks with multiple lines always show horizontal scrollbars
- Fix that prompted code blocks with multiple lines always show horizontal scrollbars
### 0.3.0
- Bug fix
- Fix that code blocks inside other elements(ex. li) are not rendered properly
- Add features
- Now you can use `-` symbols in the highlight statement so that you can easily highlight multiple, continuous lines.

View file

@ -88,15 +88,23 @@ HK CodeBlock을 이용하면 Code Block에 다양한 기능들을 추가할 수
다음과 같이 강조하고 싶은 줄의 번호를 콤마로 구분하여 입력하면 해당 줄에 강조 효과를 줄 수 있습니다.
```python highlight:"2,3"
print("Hello world")
print("I love you")
print("Wow")
```python highlight:"2-4,8,10"
print("line 1")
print("line 2")
print("line 3")
print("line 4")
print("line 5")
print("line 6")
print("line 7")
print("line 8")
print("line 9")
print("line 10")
print("line 11")
```
![highlight1](https://github.com/HeekangPark/obsidian-hk-code-block/raw/master/imgs/highlight1.png)
반드시 따옴표 안에 줄 번호를 넣어야 합니다. 큰따옴표와 작은 따옴표 모두 사용 가능합니다.
반드시 따옴표 안에 줄 번호를 넣어야 합니다. 큰따옴표와 작은 따옴표 모두 사용 가능합니다. 범위를 강조하고 싶다면 대시(`-`)를 사용하면 됩니다.
만약 줄 번호 기능을 사용해 줄 번호가 1부터 시작하지 않도록 했다면, 강조할 줄 번호를 입력할 때도 이에 맞춰서 입력해야 합니다.
@ -345,8 +353,19 @@ MIT License
- [Typewriter](https://github.com/crashmoney/obsidian-typewriter)
- 테마 문제의 대부분은 해당 테마들이 CSS에 `!important` 키워드를 붙여 HK Code Block의 CSS 우선순위가 밀려 발생합니다. HK Code Block은 다른 테마, 플러그인과의 호환성을 위해 `!important` 키워드를 사용하지 않습니다. 만약 이런 테마들에서도 HK Code Block을 사용하고 싶다면 해당 테마의 CSS를 수정하거나 `!important` 등을 사용, HK Code Block의 CSS 우선순위를 직접 높여야 합니다.
## 버그 제보, 기능 추가 요청
만약 사용 중 버그를 발견하거나, 기능 추가 요청이 있으시다면 GitHub Issues에 등록해주세요. 감사합니다!
## Changelog
버전은 다음과 같은 규칙으로 관리됩니다.
- 버전 x.y.z
- x : 전체 기능의 큰 변화가 있을 때(ex. 로직 변경 등) 증가합니다.
- y : 기능 추가 또는 수정이 있을 때 증가합니다.
- z : 버그 수정이 있을 때 증가합니다.
### 0.1.0
- 최초 배포
@ -359,4 +378,11 @@ MIT License
### 0.2.1
- 버그 수정
- 여러 줄의 소스 코드가 있는 code block에서 프롬프트 기능 활성화 시 가로 스크롤이 생기는 문제 수정
- 여러 줄의 소스 코드가 있는 code block에서 프롬프트 기능 활성화 시 가로 스크롤이 생기는 문제 수정
### 0.3.0
- 버그 수정
- 다른 요소(ex. li) 아래에 있는 code block이 이상하게 렌더링되던 문제 해결
- 기능 추가
- 이젠 줄 강조 시 `-` 기호를 사용해 손쉽게 여러 줄을 연속적으로 강조할 수 있음

95
dist/main.js vendored

File diff suppressed because one or more lines are too long

2
dist/manifest.json vendored
View file

@ -1,7 +1,7 @@
{
"id": "hk-code-block",
"name": "HK Code Block",
"version": "0.2.1",
"version": "0.3.0",
"minAppVersion": "1.0.0",
"description": "Obsidian plugin developed by Heekang Park; Make code block looking good on reading view",
"author": "Heekang Park",

14
dist/styles.css vendored

File diff suppressed because one or more lines are too long

3
dist/versions.json vendored
View file

@ -1,5 +1,6 @@
{
"0.1.0": "1.0.0",
"0.2.0": "1.0.0",
"0.2.1": "1.0.0"
"0.2.1": "1.0.0",
"0.3.0": "1.0.0"
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

After

Width:  |  Height:  |  Size: 18 KiB

View file

@ -1,7 +1,7 @@
{
"id": "hk-code-block",
"name": "HK Code Block",
"version": "0.2.1",
"version": "0.3.0",
"minAppVersion": "1.0.0",
"description": "Obsidian plugin developed by Heekang Park; Make code block looking good on reading view",
"author": "Heekang Park",

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "obsidian-hk-code-block",
"version": "1.0.0",
"version": "0.2.2",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "obsidian-hk-code-block",
"version": "1.0.0",
"version": "0.2.2",
"license": "MIT",
"devDependencies": {
"@types/node": "^16.11.6",

View file

@ -1,6 +1,6 @@
{
"name": "obsidian-hk-code-block",
"version": "0.2.1",
"version": "0.3.0",
"description": "Obsidian plugin developed by Heekang Park; Make code block looking good on reading view",
"main": "./dist/main.js",
"scripts": {

View file

@ -19,6 +19,7 @@ const REGEX = {
RESULT: /^```result\s/,
PROMPT_SIMPLE: /\sprompt\s/,
PROMPT_COMPLICATE: /\sprompt:(true|false|'(.*?)'|"(.*?)")\s/,
NUMBER: /^-{0,1}\d+$/,
}
function getMeta(view: MarkdownView, elem_code: HTMLElement, section_code: MarkdownSectionInformation, settings: HKCodeBlockSettings): {
@ -38,7 +39,29 @@ function getMeta(view: MarkdownView, elem_code: HTMLElement, section_code: Markd
showPrompt: (boolean | undefined),
prompt: string
} {
const firstline = view.editor.getLine(section_code.lineStart) + " "; // add a space to the end of the line to make sure the regex works
const lineStart = (() => {
for(let i = section_code.lineStart; i <= section_code.lineEnd; i++) {
const line = view.editor.getLine(i);
if (line.trim().startsWith("```")) return i;
}
return -1;
})();
const lineEnd = (() => {
for(let i = section_code.lineEnd; i >= section_code.lineStart; i--) {
const line = view.editor.getLine(i);
if (line.trim().startsWith("```")) return i;
}
return -1;
})();
if (lineStart < 0 || lineEnd < 0 || lineStart >= lineEnd) {
throw new Error("Cannot find the first line or the last line of the code block");
}
const firstline = view.editor.getLine(lineStart) + " "; // add a space to the end of the line to make sure the regex works
// title
let showTitle: (boolean | undefined) = undefined;
@ -66,7 +89,7 @@ function getMeta(view: MarkdownView, elem_code: HTMLElement, section_code: Markd
// linenos
let showLinenos: (boolean | undefined) = undefined;
let linenosStart = settings.defaultLinenosStart;
const linenosNum = section_code.lineEnd - section_code.lineStart - 1;
const linenosNum = lineEnd - lineStart - 1;
const regexResult_linenosSimple = REGEX.LINENOS_SIMPLE.exec(firstline);
const regexResult_linenosComplicate = REGEX.LINENOS_COMPLICATE.exec(firstline);
if (regexResult_linenosSimple) {
@ -89,7 +112,23 @@ function getMeta(view: MarkdownView, elem_code: HTMLElement, section_code: Markd
if (regexResult_highlight) {
showHighlight = true;
const highlightLines_str = regexResult_highlight[1] || regexResult_highlight[2];
highlightLines = highlightLines_str.split(",").map((line) => parseInt(line));
highlightLines = highlightLines_str.split(",").map((item) => {
item = item.trim();
if (REGEX.NUMBER.test(item)) return parseInt(item);
const multiple_lines = item.split("-");
if (multiple_lines.length === 2) {
const start = parseInt(multiple_lines[0].trim());
const end = parseInt(multiple_lines[1].trim());
if (!isNaN(start) && !isNaN(end)) {
return Array.from({ length: end - start + 1 }, (_, i) => i + start);
}
}
return NaN;
}).flat().filter((item) => !isNaN(item));
if (highlightLines.some((line) => isNaN(line))) {
// if any element is nan, then set showHighlight to false
@ -207,7 +246,7 @@ export async function HKCodeBlockProcessor(
const view = app.workspace.getActiveViewOfType(MarkdownView);
if (!view) return;
const elem_code: (HTMLElement | null) = el.querySelector("pre:not(.frontmatter) > code");
const elem_code: (HTMLElement | null) = el.querySelector("pre:not(.frontmatter) > code"); // skip front matter
if (!elem_code) return;
const elem_pre: (HTMLElement | null) = elem_code.parentElement;
@ -223,28 +262,27 @@ export async function HKCodeBlockProcessor(
if (!section_code) return;
// get metadata
const {
showTitle,
title,
isCollapsible,
showLinenos,
linenosStart,
linenosNum,
showHighlight,
highlightLines,
showLanguage,
language,
showCopyBtn,
isResult,
resultPrompt,
showPrompt,
prompt
} = getMeta(view, elem_code, section_code, settings);
if (settings.debugMode) {
console.log({
let
showTitle: (boolean | undefined),
title: string,
isCollapsible: (boolean | undefined),
showLinenos: (boolean | undefined),
linenosStart: number,
linenosNum: number,
showHighlight: (boolean | undefined),
highlightLines: number[],
showLanguage: (boolean | undefined),
language: string,
showCopyBtn: (boolean | undefined),
isResult: boolean,
resultPrompt: string,
showPrompt: (boolean | undefined),
prompt: string;
try {
({
showTitle: showTitle,
title: title,
isCollapsible: isCollapsible,
showLinenos: showLinenos,
linenosStart: linenosStart,
linenosNum: linenosNum,
@ -257,7 +295,29 @@ export async function HKCodeBlockProcessor(
resultPrompt: resultPrompt,
showPrompt: showPrompt,
prompt: prompt,
})
} = getMeta(view, elem_code, section_code, settings));
if (settings.debugMode) {
console.log({
showTitle: showTitle,
title: title,
isCollapsible: isCollapsible,
showLinenos: showLinenos,
linenosStart: linenosStart,
linenosNum: linenosNum,
showHighlight: showHighlight,
highlightLines: highlightLines,
showLanguage: showLanguage,
language: language,
showCopyBtn: showCopyBtn,
isResult: isResult,
resultPrompt: resultPrompt,
showPrompt: showPrompt,
prompt: prompt,
})
}
} catch (e) { // if cannot find metadata, skip this code block
return;
}
// create HTML elements
@ -341,7 +401,7 @@ export async function HKCodeBlockProcessor(
elem_div.style.setProperty("--hk-codeblock-highlight-background-color", settings.highlightColor);
const elem_highlight = document.createElement("code");
const elem_highlight = document.createElement("div");
elem_highlight.classList.add("hk-codeblock-highlight");
elem_highlight.innerHTML = Array(linenosNum).fill(0).map((_, idx) => {
const classNames: string[] = [];
@ -383,22 +443,24 @@ export async function HKCodeBlockProcessor(
const elem_prompt = document.createElement("div");
elem_prompt.classList.add("hk-codeblock-prompt");
const lines = elem_code.innerText.split("\n");
elem_prompt.innerText = Array(linenosNum).fill(0).map((_, idx) => {
if (idx < 0 || idx >= lines.length) return null;
const line = lines[idx].trim();
const prevLine = idx > 0 ? lines[idx - 1].trim(): "";
const prevLine = idx > 0 ? lines[idx - 1].trim() : "";
if (
(line === "") || // check if the line is empty
(line.startsWith("#")) || // check if the line is a comment
(prevLine.endsWith("\\")) // check if the line is a continuation of the previous line
) {
) {
return " ".repeat(prompt.length);
}
return prompt;
}).join("\n");
}).filter((line) => line !== null).join("\n");
elem_pre.insertBefore(elem_prompt, elem_code);
}

View file

@ -19,7 +19,6 @@
}
position: relative;
background-color: var(--hk-codeblock-background-color);
margin-bottom: var(--hk-codeblock-margin);
pre {
@ -37,6 +36,7 @@
white-space: pre;
overflow-x: auto;
padding: 0;
background-color: var(--hk-codeblock-background-color);
}
}
}
@ -72,9 +72,10 @@
display: inline-flex;
align-items: center;
justify-content: center;
margin-right: 4px;
margin-right: 2px;
position: relative;
top: -1px;
left: -3px;
.hk-codeblock-collapse-btn {
width: 16px;
@ -147,7 +148,7 @@
/* highlight */
.hk-codeblock.hk-codeblock-show-highlight {
pre {
code.hk-codeblock-highlight {
.hk-codeblock-highlight {
display: flex;
flex-direction: column;
position: absolute;
@ -160,6 +161,9 @@
padding-top: var(--hk-codeblock-vertical-padding);
padding-bottom: var(--hk-codeblock-vertical-padding);
opacity: 0.2;
font-family: var(--hk-codeblock-linenos-text-font);
font-size: var(--hk-codeblock-font-size);
background-color: transparent;
.line.highlight {
background-color: var(--hk-codeblock-highlight-background-color);

View file

@ -1,5 +1,6 @@
{
"0.1.0": "1.0.0",
"0.2.0": "1.0.0",
"0.2.1": "1.0.0"
"0.2.1": "1.0.0",
"0.3.0": "1.0.0"
}