Skip to content

Commit

Permalink
update to 1.0.5
Browse files Browse the repository at this point in the history
  • Loading branch information
stargrey committed Jun 5, 2022
1 parent 0b07a14 commit eb0d2c9
Show file tree
Hide file tree
Showing 6 changed files with 203 additions and 84 deletions.
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,15 @@ https://github.com/nyable/obsidian-code-block-enhancer
I have merged the code in both plugins and modified some of their functionality.

### Features
Enhancer the markdown code block in preview mode. Add title(have a bug now), line number to code blocks, you can click on the title to collapse or expand the block.
Enhancer the markdown code block in preview mode. Add title, line number, highlight to code blocks, you can click on the title to collapse or expand the block.

Use the syntax in the diagram below to set the block title, whether it is collapsed by default.
In version 1.0.5, use the syntax in the diagram below to set the block title, highlight, fold

![image-20220402200431096](screenshots/image-20220402200431096.png)
- Use `TI:"your title"` to add title
- Use `HL:"numbers"` to add highlight, such as `HL:"1,2,3"`, `HL:"1-3"`, separate by `,`
- Use `"FOLD"` to set the default fold

![image20220606011534.png](screenshots/image20220606011534.png)

In version 1.0.4, add the language in the top right, like this:
![screenshots/image-20220601202203.png](screenshots/image-20220601202203.png)
Expand Down
104 changes: 71 additions & 33 deletions main.js

Large diffs are not rendered by default.

150 changes: 103 additions & 47 deletions main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting, MarkdownPostProcessorContext, Menu, SettingTab } from 'obsidian';
import { linkSync } from 'fs';
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting, MarkdownPostProcessorContext, Menu, SettingTab, TAbstractFile, TFile } from 'obsidian';

const DEFAULT_LANG_ATTR = 'language-text'
const DEFAULT_LANG = ''
Expand All @@ -11,22 +12,26 @@ interface Settings {
substitutionTokenForSpace: string;
titleBackgroundColor: string;
titleFontColor: string;
highLightColor: string;

excludeLangs: string[]; // 需要排除的语言

showLineNumber: boolean; // 显示行号
showDividingLine: boolean
showDividingLine: boolean;
showLangNameInTopRight: boolean;
}

const DEFAULT_SETTINGS: Settings = {
substitutionTokenForSpace: undefined,
titleBackgroundColor: "#00000020",
titleFontColor: undefined,
highLightColor: "#2d82cc20",

excludeLangs: [],

showLineNumber: true,
showDividingLine: false
showDividingLine: false,
showLangNameInTopRight: true
};

interface CodeBlockMeta {
Expand All @@ -48,6 +53,7 @@ interface CodeBlockMeta {
// Code block wrap div
div: HTMLElement;
contentList: string[];
highLightLines: number[];
}

// Refer https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
Expand All @@ -63,7 +69,7 @@ export default class BetterCodeBlock extends Plugin {
await this.loadSettings();
this.addSettingTab(new BetterCodeBlockTab(this.app, this));
this.registerMarkdownPostProcessor((el, ctx) => {
BetterCodeBlocks(el, this)
BetterCodeBlocks(el, ctx, this)
})
}

Expand Down Expand Up @@ -103,18 +109,6 @@ class BetterCodeBlockTab extends PluginSettingTab {
await this.plugin.saveSettings();
})
)
new Setting(containerEl)
.setName("Substitution token for space")
.setDesc("The token which substitutes to space.")
.addText((tc) =>
tc
.setPlaceholder("Enter a token")
.setValue(this.plugin.settings.substitutionTokenForSpace)
.onChange(async (value) => {
this.plugin.settings.substitutionTokenForSpace = value;
await this.plugin.saveSettings();
})
);

new Setting(containerEl).setName("Font color of title").addText((tc) =>
tc
Expand All @@ -138,6 +132,18 @@ class BetterCodeBlockTab extends PluginSettingTab {
})
);

new Setting(containerEl)
.setName("HighLight Color")
.addText((tc) =>
tc
.setPlaceholder("#2d82cc20")
.setValue(this.plugin.settings.highLightColor)
.onChange(async (value) => {
this.plugin.settings.highLightColor = value;
await this.plugin.saveSettings();
})
);

new Setting(containerEl)
.setName("Show line number")
.addToggle((tc) =>
Expand All @@ -157,12 +163,22 @@ class BetterCodeBlockTab extends PluginSettingTab {
await this.plugin.saveSettings();
})
)

new Setting(containerEl)
.setName("Show language name in the top right")
.addToggle((tc) =>
tc.setValue(this.plugin.settings.showLangNameInTopRight)
.onChange(async(value) => {
this.plugin.settings.showLangNameInTopRight = value;
await this.plugin.saveSettings();
})
)
}
}

export function BetterCodeBlocks(el: HTMLElement, plugin: BetterCodeBlock) {
export function BetterCodeBlocks(el: HTMLElement, context: MarkdownPostProcessorContext, plugin: BetterCodeBlock) {
const settings = plugin.settings

const codeElm: HTMLElement = el.querySelector('pre > code')
// only change pre>code
if (!codeElm) {
Expand All @@ -181,43 +197,44 @@ export function BetterCodeBlocks(el: HTMLElement, plugin: BetterCodeBlock) {
return
}
})

// if the code block is not described, return
if(lang == DEFAULT_LANG) {
return
}

let title;
let isCollapse = false;
let titleRegExp = /TI:"([^"]*)"/i
let highLightLinesRegExp = /HL:"([^"]*)"/i
let foldRegExp = /"FOLD"/i

if(codeElm.className.contains(":-")) {
isCollapse = true;
}
const classNames = codeElm.className.split(":");
title = classNames?.[1];
let codeBlock = context.getSectionInfo(codeElm)
let view = app.workspace.getActiveViewOfType(MarkdownView)
let codeBlockFirstLine = view.editor.getLine(codeBlock.lineStart)

if(title == undefined){
title = ""
let title: string = ""
let highLightLines: number[] = []
if(codeBlockFirstLine.match(titleRegExp) != null) {
title = codeBlockFirstLine.match(titleRegExp)[1]
}
if(title.startsWith("-")) {
title = title.substring(1)
if(codeBlockFirstLine.match(highLightLinesRegExp) != null) {
let highLightLinesInfo = codeBlockFirstLine.match(highLightLinesRegExp)[1]
highLightLines = analyseHighLightLines(highLightLinesInfo)
}

if (settings.substitutionTokenForSpace) {
title = title.replace(
new RegExp(escapeRegExp(settings.substitutionTokenForSpace), "g"),
" "
);
let isCollapse = false;
if(foldRegExp.test(codeBlockFirstLine)) {
isCollapse = true
}

const pre = codeElm.parentElement
const div = pre.parentElement
const pre = codeElm.parentElement // code-block-pre__has-linenum
const div = pre.parentElement // class code-block-wrap

/* const { lineStart, lineEnd } = ctx.getSectionInfo(el)
const lineSize = lineEnd - lineStart - 1 */
const contentList: string[] = codeElm.textContent.split(LINE_SPLIT_MARK)
const lineSize = contentList.length - 1

const cbMeta: CodeBlockMeta = { langName: lang, lineSize, pre, code: codeElm, title, isCollapse, div, contentList }
const cbMeta: CodeBlockMeta = { langName: lang, lineSize, pre, code: codeElm, title, isCollapse, div, contentList, highLightLines}

const {showLineNumber} = plugin.settings

Expand All @@ -227,6 +244,8 @@ export function BetterCodeBlocks(el: HTMLElement, plugin: BetterCodeBlock) {
if (showLineNumber) {
addLineNumber(plugin, cbMeta)
}

addLineHighLight(plugin, pre, cbMeta)
}

function createElement (tagName: string, defaultClassName?: string) {
Expand Down Expand Up @@ -259,16 +278,19 @@ function addLineNumber (plugin: BetterCodeBlock, cbMeta: CodeBlockMeta) {
pre.classList.add('code-block-pre__has-linenum')
}


function addCodeTitle (plugin: BetterCodeBlock, wrapperElm: HTMLElement, cbMeta: CodeBlockMeta) {
wrapperElm.style.setProperty("position", "relative", "important");
wrapperElm.style.setProperty("padding-top", CB_PADDING_TOP, "important");

wrapperElm
.querySelectorAll(".obsidian-embedded-code-title__code-block-title")
.forEach((x) => x.remove());
.forEach((x) => x.remove()); // 防抖动

let d = document.createElement("pre");
d.appendText(cbMeta.title);
// d.appendText(cbMeta.title);
d.appendText(cbMeta.title)

if(cbMeta.isCollapse) {
d.setAttribute("closed","")
}
Expand All @@ -284,14 +306,14 @@ function addCodeTitle (plugin: BetterCodeBlock, wrapperElm: HTMLElement, cbMeta:
collapser.appendChild(handle)
d.appendChild(collapser)


let langName = document.createElement("div"); // 在右侧添加代码类型
let langNameString = cbMeta.langName.split(":")[0]
langNameString = langNameString[0].toUpperCase() + langNameString.slice(1) // 首字母大写
langName.appendText(langNameString);
langName.className = "langName";
d.appendChild(langName);

if(plugin.settings.showLangNameInTopRight) {
let langName = document.createElement("div"); // 在右侧添加代码类型
let langNameString = cbMeta.langName
langNameString = langNameString[0].toUpperCase() + langNameString.slice(1) // 首字母大写
langName.appendText(langNameString);
langName.className = "langName";
d.appendChild(langName);
}
d.addEventListener('click',function(this) {
if(d.hasAttribute("closed")){
d.removeAttribute("closed")
Expand All @@ -301,3 +323,37 @@ function addCodeTitle (plugin: BetterCodeBlock, wrapperElm: HTMLElement, cbMeta:
})
wrapperElm.prepend(d);
}

function addLineHighLight(plugin: BetterCodeBlock, wrapperElm: HTMLElement, cbMeta: CodeBlockMeta) {
if(cbMeta.highLightLines.length == 0) return

let highLightWrap = document.createElement("pre")
highLightWrap.className = "code-block-highlight-wrap"
for(let i = 0; i < cbMeta.lineSize; i++) {
const singleLine = createElement("span", 'code-block-highlight')
if(cbMeta.highLightLines.contains(i+1)) {
singleLine.style.backgroundColor = plugin.settings.highLightColor || "#2d82cc20"
}
highLightWrap.appendChild(singleLine)
}

wrapperElm.appendChild(highLightWrap)
}

function analyseHighLightLines(str: string): number[] {
str = str.replace(/\s*/g, "") // 去除字符串中所有空格
const result: number[] = []

let strs = str.split(",")
strs.forEach(it => {
if(/\w-\w/.test(it)) { // 如果匹配 1-3 这样的格式,依次添加数字
for(let i = Number(it[0]); i <= Number(it[2]); i++) {
result.push(i)
}
} else {
result.push(Number(it))
}
})

return result
}
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "obsidian-better-codeblock",
"name": "Better CodeBlock",
"version": "1.0.4",
"version": "1.0.5",
"minAppVersion": "0.12.0",
"description": "Add title, line number to Obsidian code block",
"author": "StarGrey",
Expand Down
Binary file added screenshots/image20220606011534.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
21 changes: 21 additions & 0 deletions styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
pre[class*=language-] {
font-size: var(--editor-font-size);
line-height: 1.5em;
padding-bottom: 0px;
}
.obsidian-embedded-code-title__code-block-title + code[class*=language-]{
padding: 0em 0em 0em 0em !important;
Expand Down Expand Up @@ -66,6 +67,25 @@ pre[class*=language-].code-block-pre__has-linenum {
content: counter(line-num);
}

/* 代码高亮 */
pre[class*=language-] .code-block-highlight-wrap {
margin: 0;
padding: 0;
position: absolute;
left: 0px;
top: 35px;
width: 100%;
height: 100%;
background-color: transparent;
pointer-events: none;
}

pre[class*=language-] .code-block-highlight-wrap span {
display: block;
height: 1.5em;
width: 100%;
}

/* 折叠代码块 */

:root {
Expand All @@ -84,6 +104,7 @@ pre[class*=language-].code-block-pre__has-linenum {
margin-right: 35px;
font-weight: bold;
font-size: 14px;
font-family: var(--font-default);
}

.obsidian-embedded-code-title__code-block-title .collapser {
Expand Down

0 comments on commit eb0d2c9

Please sign in to comment.