repo stringlengths 5 106 | file_url stringlengths 78 301 | file_path stringlengths 4 211 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:56:49 2026-01-05 02:23:25 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/imagePicker/index.js | src/muya/lib/ui/imagePicker/index.js | import BaseScrollFloat from '../baseScrollFloat'
import { patch, h } from '../../parser/render/snabbdom'
import FolderIcon from '../../assets/icons/folder.svg'
import ImageIcon from '../../assets/icons/image.svg'
import UploadIcon from '../../assets/icons/upload.svg'
import './index.css'
const iconhash = {
'icon-image': ImageIcon,
'icon-folder': FolderIcon,
'icon-upload': UploadIcon
}
class ImagePathPicker extends BaseScrollFloat {
static pluginName = 'imagePathPicker'
constructor (muya) {
const name = 'ag-list-picker'
super(muya, name)
this.renderArray = []
this.oldVnode = null
this.activeItem = null
this.floatBox.classList.add('ag-image-picker-wrapper')
this.listen()
}
listen () {
super.listen()
const { eventCenter } = this.muya
eventCenter.subscribe('muya-image-picker', ({ reference, list, cb }) => {
if (list.length) {
this.show(reference, cb)
this.renderArray = list
this.activeItem = list[0]
this.render()
} else {
this.hide()
}
})
}
render () {
const { renderArray, oldVnode, scrollElement, activeItem } = this
const children = renderArray.map((item) => {
const { text, iconClass } = item
const icon = h('div.icon-wrapper', h('svg', {
attrs: {
viewBox: iconhash[iconClass].viewBox,
'aria-hidden': 'true'
},
hook: {
prepatch (oldvnode, vnode) {
// cheat snabbdom that the pre block is changed!!!
oldvnode.children = []
oldvnode.elm.innerHTML = ''
}
}
}, h('use', {
attrs: {
'xlink:href': iconhash[iconClass].url
}
}))
)
const textEle = h('div.language', text)
const selector = activeItem === item ? 'li.item.active' : 'li.item'
return h(selector, {
dataset: {
label: item.text
},
on: {
click: () => {
this.selectItem(item)
}
}
}, [icon, textEle])
})
const vnode = h('ul', children)
if (oldVnode) {
patch(oldVnode, vnode)
} else {
patch(scrollElement, vnode)
}
this.oldVnode = vnode
}
getItemElement (item) {
const { text } = item
return this.floatBox.querySelector(`[data-label="${text}"]`)
}
}
export default ImagePathPicker
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/baseScrollFloat/index.js | src/muya/lib/ui/baseScrollFloat/index.js | import BaseFloat from '../baseFloat'
import { EVENT_KEYS } from '../../config'
class BaseScrollFloat extends BaseFloat {
constructor (muya, name, options = {}) {
super(muya, name, options)
this.scrollElement = null
this.reference = null
this.activeItem = null
this.createScrollElement()
}
createScrollElement () {
const { container } = this
const scrollElement = document.createElement('div')
container.appendChild(scrollElement)
this.scrollElement = scrollElement
}
activeEleScrollIntoView (ele) {
if (ele) {
ele.scrollIntoView({
behavior: 'auto',
block: 'center',
inline: 'start'
})
}
}
listen () {
super.listen()
const { eventCenter, container } = this.muya
const handler = event => {
if (!this.status) return
switch (event.key) {
case EVENT_KEYS.ArrowUp:
this.step('previous')
break
case EVENT_KEYS.ArrowDown:
case EVENT_KEYS.Tab:
this.step('next')
break
case EVENT_KEYS.Enter:
this.selectItem(this.activeItem)
break
default:
break
}
}
eventCenter.attachDOMEvent(container, 'keydown', handler)
}
hide () {
super.hide()
this.reference = null
}
show (reference, cb) {
this.cb = cb
if (reference instanceof HTMLElement) {
if (this.reference && this.reference === reference && this.status) return
} else {
if (this.reference && this.reference.id === reference.id && this.status) return
}
this.reference = reference
super.show(reference, cb)
}
step (direction) {
let index = this.renderArray.findIndex(item => {
return item === this.activeItem
})
index = direction === 'next' ? index + 1 : index - 1
if (index < 0 || index >= this.renderArray.length) {
return
}
this.activeItem = this.renderArray[index]
this.render()
const activeEle = this.getItemElement(this.activeItem)
this.activeEleScrollIntoView(activeEle)
}
selectItem (item) {
const { cb } = this
cb(item)
// delay hide to avoid dispatch enter hander
setTimeout(this.hide.bind(this))
}
getItemElement () {}
}
export default BaseScrollFloat
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/imageToolbar/index.js | src/muya/lib/ui/imageToolbar/index.js | import BaseFloat from '../baseFloat'
import { patch, h } from '../../parser/render/snabbdom'
import icons from './config'
import './index.css'
const defaultOptions = {
placement: 'top',
modifiers: {
offset: {
offset: '0, 10'
}
},
showArrow: false
}
class ImageToolbar extends BaseFloat {
static pluginName = 'imageToolbar'
constructor (muya, options = {}) {
const name = 'ag-image-toolbar'
const opts = Object.assign({}, defaultOptions, options)
super(muya, name, opts)
this.oldVnode = null
this.imageInfo = null
this.options = opts
this.icons = icons
this.reference = null
const toolbarContainer = this.toolbarContainer = document.createElement('div')
this.container.appendChild(toolbarContainer)
this.floatBox.classList.add('ag-image-toolbar-container')
this.listen()
}
listen () {
const { eventCenter } = this.muya
super.listen()
eventCenter.subscribe('muya-image-toolbar', ({ reference, imageInfo }) => {
this.reference = reference
if (reference) {
this.imageInfo = imageInfo
setTimeout(() => {
this.show(reference)
this.render()
}, 0)
} else {
this.hide()
}
})
}
render () {
const { icons, oldVnode, toolbarContainer, imageInfo } = this
const { attrs } = imageInfo.token
const dataAlign = attrs['data-align']
const children = icons.map(i => {
let icon
let iconWrapperSelector
if (i.icon) {
// SVG icon Asset
iconWrapperSelector = 'div.icon-wrapper'
icon = h('i.icon', h('i.icon-inner', {
style: {
background: `url(${i.icon}) no-repeat`,
'background-size': '100%'
}
}, ''))
}
const iconWrapper = h(iconWrapperSelector, icon)
let itemSelector = `li.item.${i.type}`
if (i.type === dataAlign || !dataAlign && i.type === 'inline') {
itemSelector += '.active'
}
return h(itemSelector, {
dataset: {
tip: i.tooltip
},
on: {
click: event => {
this.selectItem(event, i)
}
}
}, [h('div.tooltip', i.tooltip), iconWrapper])
})
const vnode = h('ul', children)
if (oldVnode) {
patch(oldVnode, vnode)
} else {
patch(toolbarContainer, vnode)
}
this.oldVnode = vnode
}
selectItem (event, item) {
event.preventDefault()
event.stopPropagation()
const { imageInfo } = this
switch (item.type) {
// Delete image.
case 'delete':
this.muya.contentState.deleteImage(imageInfo)
// Hide image transformer
this.muya.eventCenter.dispatch('muya-transformer', {
reference: null
})
return this.hide()
// Edit image, for example: editor alt and title, replace image.
case 'edit': {
const rect = this.reference.getBoundingClientRect()
const reference = {
getBoundingClientRect () {
rect.height = 0
return rect
}
}
// Hide image transformer
this.muya.eventCenter.dispatch('muya-transformer', {
reference: null
})
this.muya.eventCenter.dispatch('muya-image-selector', {
reference,
imageInfo,
cb: () => {}
})
return this.hide()
}
case 'inline':
case 'left':
case 'center':
case 'right': {
this.muya.contentState.updateImage(this.imageInfo, 'data-align', item.type)
return this.hide()
}
}
}
}
export default ImageToolbar
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/imageToolbar/config.js | src/muya/lib/ui/imageToolbar/config.js | import editIcon from '../../assets/pngicon/imageEdit/2.png'
import inlineIcon from '../../assets/pngicon/inline_image/2.png'
import leftIcon from '../../assets/pngicon/algin_left/2.png'
import middleIcon from '../../assets/pngicon/algin_center/2.png'
import rightIcon from '../../assets/pngicon/algin_right/2.png'
import deleteIcon from '../../assets/pngicon/image_delete/2.png'
const icons = [
{
type: 'edit',
tooltip: 'Edit Image',
icon: editIcon
},
{
type: 'inline',
tooltip: 'Inline Image',
icon: inlineIcon
},
{
type: 'left',
tooltip: 'Align Left',
icon: leftIcon
},
{
type: 'center',
tooltip: 'Align Middle',
icon: middleIcon
},
{
type: 'right',
tooltip: 'Align Right',
icon: rightIcon
},
{
type: 'delete',
tooltip: 'Remove Image',
icon: deleteIcon
}
]
export default icons
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/baseFloat/index.js | src/muya/lib/ui/baseFloat/index.js | import Popper from 'popper.js/dist/esm/popper'
import resizeDetector from 'element-resize-detector'
import { noop } from '../../utils'
import { EVENT_KEYS } from '../../config'
import './index.css'
const defaultOptions = () => ({
placement: 'bottom-start',
modifiers: {
offset: {
offset: '0, 12'
}
},
showArrow: true
})
class BaseFloat {
constructor (muya, name, options = {}) {
this.name = name
this.muya = muya
this.options = Object.assign({}, defaultOptions(), options)
this.status = false
this.floatBox = null
this.container = null
this.popper = null
this.lastScrollTop = null
this.resizeDetector = null
this.cb = noop
this.init()
}
init () {
const { showArrow } = this.options
const floatBox = document.createElement('div')
const container = document.createElement('div')
// Use to remember whick float container is shown.
container.classList.add(this.name)
container.classList.add('ag-float-container')
floatBox.classList.add('ag-float-wrapper')
if (showArrow) {
const arrow = document.createElement('div')
arrow.setAttribute('x-arrow', '')
arrow.classList.add('ag-popper-arrow')
floatBox.appendChild(arrow)
}
floatBox.appendChild(container)
document.body.appendChild(floatBox)
this.resizeDetector = resizeDetector({
strategy: 'scroll'
})
// use polyfill
this.resizeDetector.listenTo(container, ele => {
const { offsetWidth, offsetHeight } = ele
Object.assign(floatBox.style, { width: `${offsetWidth}px`, height: `${offsetHeight}px` })
this.popper && this.popper.update()
})
// const ro = new ResizeObserver(entries => {
// for (const entry of entries) {
// const { offsetWidth, offsetHeight } = entry.target
// Object.assign(floatBox.style, { width: `${offsetWidth + 2}px`, height: `${offsetHeight + 2}px` })
// this.popper && this.popper.update()
// }
// })
// ro.observe(container)
this.floatBox = floatBox
this.container = container
}
listen () {
const { eventCenter, container } = this.muya
const { floatBox } = this
const keydownHandler = event => {
if (event.key === EVENT_KEYS.Escape) {
this.hide()
}
}
const scrollHandler = event => {
if (typeof this.lastScrollTop !== 'number') {
this.lastScrollTop = event.target.scrollTop
return
}
// only when scoll distance great than 50px, then hide the float box.
if (this.status && Math.abs(event.target.scrollTop - this.lastScrollTop) > 50) {
this.hide()
}
}
eventCenter.attachDOMEvent(document, 'click', this.hide.bind(this))
eventCenter.attachDOMEvent(floatBox, 'click', event => {
event.stopPropagation()
event.preventDefault()
})
eventCenter.attachDOMEvent(container, 'keydown', keydownHandler)
eventCenter.attachDOMEvent(container, 'scroll', scrollHandler)
}
hide () {
const { eventCenter } = this.muya
if (!this.status) return
this.status = false
if (this.popper && this.popper.destroy) {
this.popper.destroy()
}
this.cb = noop
eventCenter.dispatch('muya-float', this, false)
this.lastScrollTop = null
}
show (reference, cb = noop) {
const { floatBox } = this
const { eventCenter } = this.muya
const { placement, modifiers } = this.options
if (this.popper && this.popper.destroy) {
this.popper.destroy()
}
this.cb = cb
this.popper = new Popper(reference, floatBox, {
placement,
modifiers
})
this.status = true
eventCenter.dispatch('muya-float', this, true)
}
destroy () {
if (this.popper && this.popper.destroy) {
this.popper.destroy()
}
if (this.resizeDetector && this.container) {
this.resizeDetector.uninstall(this.container)
}
this.floatBox.remove()
}
}
export default BaseFloat
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/footnoteTool/index.js | src/muya/lib/ui/footnoteTool/index.js | import BaseFloat from '../baseFloat'
import { patch, h } from '../../parser/render/snabbdom'
import WarningIcon from '../../assets/pngicon/warning/2.png'
import './index.css'
const getFootnoteText = block => {
let text = ''
const travel = block => {
if (block.children.length === 0 && block.text) {
text += block.text
} else if (block.children.length) {
for (const b of block.children) {
travel(b)
}
}
}
const blocks = block.children.slice(1)
for (const b of blocks) {
travel(b)
}
return text
}
const defaultOptions = {
placement: 'bottom',
modifiers: {
offset: {
offset: '0, 5'
}
},
showArrow: false
}
class LinkTools extends BaseFloat {
static pluginName = 'footnoteTool'
constructor (muya, options = {}) {
const name = 'ag-footnote-tool'
const opts = Object.assign({}, defaultOptions, options)
super(muya, name, opts)
this.oldVnode = null
this.identifier = null
this.footnotes = null
this.options = opts
this.hideTimer = null
const toolContainer = this.toolContainer = document.createElement('div')
this.container.appendChild(toolContainer)
this.floatBox.classList.add('ag-footnote-tool-container')
this.listen()
}
listen () {
const { eventCenter } = this.muya
super.listen()
eventCenter.subscribe('muya-footnote-tool', ({ reference, identifier, footnotes }) => {
if (reference) {
this.footnotes = footnotes
this.identifier = identifier
setTimeout(() => {
this.show(reference)
this.render()
}, 0)
} else {
if (this.hideTimer) {
clearTimeout(this.hideTimer)
}
this.hideTimer = setTimeout(() => {
this.hide()
}, 500)
}
})
const mouseOverHandler = () => {
if (this.hideTimer) {
clearTimeout(this.hideTimer)
}
}
const mouseOutHandler = () => {
this.hide()
}
eventCenter.attachDOMEvent(this.container, 'mouseover', mouseOverHandler)
eventCenter.attachDOMEvent(this.container, 'mouseleave', mouseOutHandler)
}
render () {
const { oldVnode, toolContainer, identifier, footnotes } = this
const hasFootnote = footnotes.has(identifier)
const iconWrapperSelector = 'div.icon-wrapper'
const icon = h('i.icon', h('i.icon-inner', {
style: {
background: `url(${WarningIcon}) no-repeat`,
'background-size': '100%'
}
}, ''))
const iconWrapper = h(iconWrapperSelector, icon)
let text = 'Can\'t find footnote with syntax [^abc]:'
if (hasFootnote) {
const footnoteBlock = footnotes.get(identifier)
text = getFootnoteText(footnoteBlock)
if (!text) {
text = 'Input the footnote definition...'
}
}
const textNode = h('span.text', text)
const button = h('a.btn', {
on: {
click: event => {
this.buttonClick(event, hasFootnote)
}
}
}, hasFootnote ? 'Go to' : 'Create')
const children = [textNode, button]
if (!hasFootnote) {
children.unshift(iconWrapper)
}
const vnode = h('div', children)
if (oldVnode) {
patch(oldVnode, vnode)
} else {
patch(toolContainer, vnode)
}
this.oldVnode = vnode
}
buttonClick (event, hasFootnote) {
event.preventDefault()
event.stopPropagation()
const { identifier, footnotes } = this
if (hasFootnote) {
const block = footnotes.get(identifier)
const key = block.key
const ele = document.querySelector(`#${key}`)
ele.scrollIntoView({ behavior: 'smooth' })
} else {
this.muya.contentState.createFootnote(identifier)
}
return this.hide()
}
}
export default LinkTools
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/index.js | src/muya/lib/parser/index.js | import { beginRules, inlineRules, inlineExtensionRules } from './rules'
import { isLengthEven, union } from '../utils'
import { findClosingBracket } from './marked/utils'
import { getAttributes, parseSrcAndTitle, validateEmphasize, lowerPriority } from './utils'
// const CAN_NEST_RULES = ['strong', 'em', 'link', 'del', 'a_link', 'reference_link', 'html_tag']
// disallowed html tags in https://github.github.com/gfm/#raw-html
const disallowedHtmlTag = /(?:title|textarea|style|xmp|iframe|noembed|noframes|script|plaintext)/i
const validateRules = Object.assign({}, inlineRules)
delete validateRules.em
delete validateRules.strong
delete validateRules.tail_header
delete validateRules.backlash
const correctUrl = token => {
if (token && typeof token[4] === 'string') {
const lastParenIndex = findClosingBracket(token[4], '()')
if (lastParenIndex > -1) {
const len = token[0].length - (token[4].length - lastParenIndex)
token[0] = token[0].substring(0, len)
const originSrc = token[4].substring(0, lastParenIndex)
const match = /(\\+)$/.exec(originSrc)
if (match) {
token[4] = originSrc.substring(0, originSrc.length - match[1].length)
token[5] = match[1]
} else {
token[4] = originSrc
token[5] = ''
}
}
}
}
const matchHtmlTag = (src, disableHtml) => {
const match = inlineRules.html_tag.exec(src)
if (!match) {
return null
}
// Ignore HTML tag when HTML rendering is disabled and import it as plain text.
// NB: We have to allow img tag to support image resizer and options.
if (disableHtml && (!match[3] || !/^img$/i.test(match[3]))) {
return null
}
return match
}
const tokenizerFac = (src, beginRules, inlineRules, pos = 0, top, labels, options) => {
const originSrc = src
const tokens = []
let pending = ''
let pendingStartPos = pos
const { disableHtml, superSubScript, footnote } = options
const pushPending = () => {
if (pending) {
tokens.push({
type: 'text',
raw: pending,
content: pending,
range: {
start: pendingStartPos,
end: pos
}
})
}
pendingStartPos = pos
pending = ''
}
if (beginRules && pos === 0) {
const beginRuleList = ['header', 'hr', 'code_fense', 'multiple_math']
for (const ruleName of beginRuleList) {
const to = beginRules[ruleName].exec(src)
if (to) {
const token = {
type: ruleName,
raw: to[0],
parent: tokens,
marker: to[1],
content: to[2] || '',
backlash: to[3] || '',
range: {
start: pos,
end: pos + to[0].length
}
}
tokens.push(token)
src = src.substring(to[0].length)
pos = pos + to[0].length
break
}
}
const def = beginRules.reference_definition.exec(src)
if (def && isLengthEven(def[3])) {
const token = {
type: 'reference_definition',
parent: tokens,
leftBracket: def[1],
label: def[2],
backlash: def[3] || '',
rightBracket: def[4],
leftHrefMarker: def[5] || '',
href: def[6],
rightHrefMarker: def[7] || '',
leftTitlespace: def[8],
titleMarker: def[9] || '',
title: def[10] || '',
rightTitleSpace: def[11] || '',
raw: def[0],
range: {
start: pos,
end: pos + def[0].length
}
}
tokens.push(token)
src = src.substring(def[0].length)
pos = pos + def[0].length
}
}
while (src.length) {
// backlash
const backTo = inlineRules.backlash.exec(src)
if (backTo) {
pushPending()
tokens.push({
type: 'backlash',
raw: backTo[1],
marker: backTo[1],
parent: tokens,
content: '',
range: {
start: pos,
end: pos + backTo[1].length
}
})
pending += pending + backTo[2]
pendingStartPos = pos + backTo[1].length
src = src.substring(backTo[0].length)
pos = pos + backTo[0].length
continue
}
// strong | em
const emRules = ['strong', 'em']
let inChunk
for (const rule of emRules) {
const to = inlineRules[rule].exec(src)
if (to && isLengthEven(to[3])) {
const isValid = validateEmphasize(src, to[0].length, to[1], pending, validateRules)
if (isValid) {
inChunk = true
pushPending()
const range = {
start: pos,
end: pos + to[0].length
}
const marker = to[1]
tokens.push({
type: rule,
raw: to[0],
range,
marker,
parent: tokens,
children: tokenizerFac(to[2], undefined, inlineRules, pos + to[1].length, false, labels, options),
backlash: to[3]
})
src = src.substring(to[0].length)
pos = pos + to[0].length
}
break
}
}
if (inChunk) continue
// strong | em | emoji | inline_code | del | inline_math
const chunks = ['inline_code', 'del', 'emoji', 'inline_math']
for (const rule of chunks) {
const to = inlineRules[rule].exec(src)
if (to && isLengthEven(to[3])) {
if (rule === 'emoji' && !lowerPriority(src, to[0].length, validateRules)) break
inChunk = true
pushPending()
const range = {
start: pos,
end: pos + to[0].length
}
const marker = to[1]
if (rule === 'inline_code' || rule === 'emoji' || rule === 'inline_math') {
tokens.push({
type: rule,
raw: to[0],
range,
marker,
parent: tokens,
content: to[2],
backlash: to[3]
})
} else {
tokens.push({
type: rule,
raw: to[0],
range,
marker,
parent: tokens,
children: tokenizerFac(to[2], undefined, inlineRules, pos + to[1].length, false, labels, options),
backlash: to[3]
})
}
src = src.substring(to[0].length)
pos = pos + to[0].length
break
}
}
if (inChunk) continue
// superscript and subscript
if (superSubScript) {
const superSubTo = inlineRules.superscript.exec(src) || inlineRules.subscript.exec(src)
if (superSubTo) {
pushPending()
tokens.push({
type: 'super_sub_script',
raw: superSubTo[0],
marker: superSubTo[1],
range: {
start: pos,
end: pos + superSubTo[0].length
},
parent: tokens,
content: superSubTo[2]
})
src = src.substring(superSubTo[0].length)
pos = pos + superSubTo[0].length
continue
}
}
// footnote identifier
if (pos !== 0 && footnote) {
const footnoteTo = inlineRules.footnote_identifier.exec(src)
if (footnoteTo) {
pushPending()
tokens.push({
type: 'footnote_identifier',
raw: footnoteTo[0],
marker: footnoteTo[1],
range: {
start: pos,
end: pos + footnoteTo[0].length
},
parent: tokens,
content: footnoteTo[2]
})
src = src.substring(footnoteTo[0].length)
pos = pos + footnoteTo[0].length
continue
}
}
// image
const imageTo = inlineRules.image.exec(src)
correctUrl(imageTo)
if (imageTo && isLengthEven(imageTo[3]) && isLengthEven(imageTo[5])) {
const { src: imageSrc, title } = parseSrcAndTitle(imageTo[4])
pushPending()
tokens.push({
type: 'image',
raw: imageTo[0],
marker: imageTo[1],
srcAndTitle: imageTo[4],
// This `attrs` used for render image.
attrs: {
src: imageSrc + encodeURI(imageTo[5]),
title,
alt: imageTo[2] + encodeURI(imageTo[3])
},
src: imageSrc,
title,
parent: tokens,
range: {
start: pos,
end: pos + imageTo[0].length
},
alt: imageTo[2],
backlash: {
first: imageTo[3],
second: imageTo[5]
}
})
src = src.substring(imageTo[0].length)
pos = pos + imageTo[0].length
continue
}
// link
const linkTo = inlineRules.link.exec(src)
correctUrl(linkTo)
if (linkTo && isLengthEven(linkTo[3]) && isLengthEven(linkTo[5])) {
const { src: href, title } = parseSrcAndTitle(linkTo[4])
pushPending()
tokens.push({
type: 'link',
raw: linkTo[0],
marker: linkTo[1],
hrefAndTitle: linkTo[4],
href,
title,
parent: tokens,
anchor: linkTo[2],
range: {
start: pos,
end: pos + linkTo[0].length
},
children: tokenizerFac(linkTo[2], undefined, inlineRules, pos + linkTo[1].length, false, labels, options),
backlash: {
first: linkTo[3],
second: linkTo[5]
}
})
src = src.substring(linkTo[0].length)
pos = pos + linkTo[0].length
continue
}
const rLinkTo = inlineRules.reference_link.exec(src)
if (rLinkTo && labels.has(rLinkTo[3] || rLinkTo[1]) && isLengthEven(rLinkTo[2]) && isLengthEven(rLinkTo[4])) {
pushPending()
tokens.push({
type: 'reference_link',
raw: rLinkTo[0],
isFullLink: !!rLinkTo[3],
parent: tokens,
anchor: rLinkTo[1],
backlash: {
first: rLinkTo[2],
second: rLinkTo[4] || ''
},
label: rLinkTo[3] || rLinkTo[1],
range: {
start: pos,
end: pos + rLinkTo[0].length
},
children: tokenizerFac(rLinkTo[1], undefined, inlineRules, pos + 1, false, labels, options)
})
src = src.substring(rLinkTo[0].length)
pos = pos + rLinkTo[0].length
continue
}
const rImageTo = inlineRules.reference_image.exec(src)
if (rImageTo && labels.has(rImageTo[3] || rImageTo[1]) && isLengthEven(rImageTo[2]) && isLengthEven(rImageTo[4])) {
pushPending()
tokens.push({
type: 'reference_image',
raw: rImageTo[0],
isFullLink: !!rImageTo[3],
parent: tokens,
alt: rImageTo[1],
backlash: {
first: rImageTo[2],
second: rImageTo[4] || ''
},
label: rImageTo[3] || rImageTo[1],
range: {
start: pos,
end: pos + rImageTo[0].length
}
})
src = src.substring(rImageTo[0].length)
pos = pos + rImageTo[0].length
continue
}
// html escape
const htmlEscapeTo = inlineRules.html_escape.exec(src)
if (htmlEscapeTo) {
const len = htmlEscapeTo[0].length
pushPending()
tokens.push({
type: 'html_escape',
raw: htmlEscapeTo[0],
escapeCharacter: htmlEscapeTo[1],
parent: tokens,
range: {
start: pos,
end: pos + len
}
})
src = src.substring(len)
pos = pos + len
continue
}
// auto link extension
const autoLinkExtTo = inlineRules.auto_link_extension.exec(src)
if (autoLinkExtTo && top && (pos === 0 || /[* _~(]{1}/.test(originSrc[pos - 1]))) {
pushPending()
tokens.push({
type: 'auto_link_extension',
raw: autoLinkExtTo[0],
www: autoLinkExtTo[1],
url: autoLinkExtTo[2],
email: autoLinkExtTo[3],
linkType: autoLinkExtTo[1] ? 'www' : (autoLinkExtTo[2] ? 'url' : 'email'),
parent: tokens,
range: {
start: pos,
end: pos + autoLinkExtTo[0].length
}
})
src = src.substring(autoLinkExtTo[0].length)
pos = pos + autoLinkExtTo[0].length
continue
}
// auto link
const autoLTo = inlineRules.auto_link.exec(src)
if (autoLTo) {
pushPending()
tokens.push({
type: 'auto_link',
raw: autoLTo[0],
href: autoLTo[1],
email: autoLTo[2],
isLink: !!autoLTo[1], // It is a link or email.
marker: '<',
parent: tokens,
range: {
start: pos,
end: pos + autoLTo[0].length
}
})
src = src.substring(autoLTo[0].length)
pos = pos + autoLTo[0].length
continue
}
// html-tag
const htmlTo = matchHtmlTag(src, disableHtml)
let attrs
// handle comment
if (htmlTo && htmlTo[1] && !htmlTo[3]) {
const len = htmlTo[0].length
pushPending()
tokens.push({
type: 'html_tag',
raw: htmlTo[0],
tag: '<!---->',
openTag: htmlTo[1],
parent: tokens,
attrs: {},
range: {
start: pos,
end: pos + len
}
})
src = src.substring(len)
pos = pos + len
continue
} else if (htmlTo && !(disallowedHtmlTag.test(htmlTo[3])) && (attrs = getAttributes(htmlTo[0]))) {
const tag = htmlTo[3]
const html = htmlTo[0]
const len = htmlTo[0].length
pushPending()
tokens.push({
type: 'html_tag',
raw: html,
tag,
openTag: htmlTo[2],
closeTag: htmlTo[5],
parent: tokens,
attrs,
content: htmlTo[4],
children: htmlTo[4] ? tokenizerFac(htmlTo[4], undefined, inlineRules, pos + htmlTo[2].length, false, labels, options) : '',
range: {
start: pos,
end: pos + len
}
})
src = src.substring(len)
pos = pos + len
continue
}
// soft line break
const softTo = inlineRules.soft_line_break.exec(src)
if (softTo) {
const len = softTo[0].length
pushPending()
tokens.push({
type: 'soft_line_break',
raw: softTo[0],
lineBreak: softTo[1],
isAtEnd: softTo.input.length === softTo[0].length,
parent: tokens,
range: {
start: pos,
end: pos + len
}
})
src = src.substring(len)
pos += len
continue
}
// hard line break
const hardTo = inlineRules.hard_line_break.exec(src)
if (hardTo) {
const len = hardTo[0].length
pushPending()
tokens.push({
type: 'hard_line_break',
raw: hardTo[0],
spaces: hardTo[1], // The space in hard line break
lineBreak: hardTo[2], // \n
isAtEnd: hardTo.input.length === hardTo[0].length,
parent: tokens,
range: {
start: pos,
end: pos + len
}
})
src = src.substring(len)
pos += len
continue
}
// tail header
const tailTo = inlineRules.tail_header.exec(src)
if (tailTo && top) {
pushPending()
tokens.push({
type: 'tail_header',
raw: tailTo[1],
marker: tailTo[1],
parent: tokens,
range: {
start: pos,
end: pos + tailTo[1].length
}
})
src = src.substring(tailTo[1].length)
pos += tailTo[1].length
continue
}
if (!pending) pendingStartPos = pos
pending += src[0]
src = src.substring(1)
pos++
}
pushPending()
return tokens
}
export const tokenizer = (src, {
highlights = [],
hasBeginRules = true,
labels = new Map(),
options = {}
} = {}) => {
const rules = Object.assign({}, inlineRules, inlineExtensionRules)
const tokens = tokenizerFac(src, hasBeginRules ? beginRules : null, rules, 0, true, labels, options)
const postTokenizer = tokens => {
for (const token of tokens) {
for (const light of highlights) {
const highlight = union(token.range, light)
if (highlight) {
if (token.highlights && Array.isArray(token.highlights)) {
token.highlights.push(highlight)
} else {
token.highlights = [highlight]
}
}
}
if (token.children && Array.isArray(token.children)) {
postTokenizer(token.children)
}
}
}
if (highlights.length) {
postTokenizer(tokens)
}
return tokens
}
// transform `tokens` to text ignore the range of token
// the opposite of tokenizer
export const generator = tokens => {
let result = ''
for (const token of tokens) {
result += token.raw
}
return result
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/rules.js | src/muya/lib/parser/rules.js | import { escapeCharacters } from './escapeCharacter'
/* eslint-disable no-useless-escape */
export const beginRules = {
hr: /^(\*{3,}$|^\-{3,}$|^\_{3,}$)/,
code_fense: /^(`{3,})([^`]*)$/,
header: /(^ {0,3}#{1,6}(\s{1,}|$))/,
reference_definition: /^( {0,3}\[)([^\]]+?)(\\*)(\]: *)(<?)([^\s>]+)(>?)(?:( +)(["'(]?)([^\n"'\(\)]+)\9)?( *)$/,
// extra syntax (not belogs to GFM)
multiple_math: /^(\$\$)$/
}
export const inlineRules = {
strong: /^(\*\*|__)(?=\S)([\s\S]*?[^\s\\])(\\*)\1(?!(\*|_))/, // can nest
em: /^(\*|_)(?=\S)([\s\S]*?[^\s\*\\])(\\*)\1(?!\1)/, // can nest
inline_code: /^(`{1,3})([^`]+?|.{2,})\1/,
image: /^(\!\[)(.*?)(\\*)\]\((.*)(\\*)\)/,
link: /^(\[)((?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*?)(\\*)\]\((.*)(\\*)\)/, // can nest
emoji: /^(:)([a-z_\d+-]+?)\1/,
del: /^(~{2})(?=\S)([\s\S]*?\S)(\\*)\1/, // can nest
auto_link: /^<(?:([a-zA-Z]{1}[a-zA-Z\d\+\.\-]{1,31}:[^ <>]*)|([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*))>/,
// (extended www autolink|extended url autolink|extended email autolink) the email regexp is the same as auto_link.
auto_link_extension: /^(?:(www\.[a-z_-]+\.[a-z]{2,}(?::[0-9]{1,5})?(?:\/[\S]*)?)|(http(?:s)?:\/\/(?:[a-z0-9\-._~]+\.[a-z]{2,}|[0-9.]+|localhost|\[[a-f0-9.:]+\])(?::[0-9]{1,5})?(?:\/[\S]*)?)|([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*))(?=\s|$)/,
reference_link: /^\[([^\]]+?)(\\*)\](?:\[([^\]]*?)(\\*)\])?/,
reference_image: /^\!\[([^\]]+?)(\\*)\](?:\[([^\]]*?)(\\*)\])?/,
tail_header: /^(\s{1,}#{1,})(\s*)$/,
html_tag: /^(<!--[\s\S]*?-->|(<([a-zA-Z]{1}[a-zA-Z\d-]*) *[^\n<>]* *(?:\/)?>)(?:([\s\S]*?)(<\/\3 *>))?)/, // raw html
html_escape: new RegExp(`^(${escapeCharacters.join('|')})`, 'i'),
soft_line_break: /^(\n)(?!\n)/,
hard_line_break: /^( {2,})(\n)(?!\n)/,
// patched math marker `$`
backlash: /^(\\)([\\`*{}\[\]()#+\-.!_>~:\|\<\>$]{1})/,
// Markdown extensions (not belongs to GFM and Commonmark)
inline_math: /^(\$)([^\$]*?[^\$\\])(\\*)\1(?!\1)/
}
// Markdown extensions (not belongs to GFM and Commonmark)
export const inlineExtensionRules = {
// This is not the best regexp, because it not support `2^2\\^`.
superscript: /^(\^)((?:[^\^\s]|(?<=\\)\1|(?<=\\) )+?)(?<!\\)\1(?!\1)/,
subscript: /^(~)((?:[^~\s]|(?<=\\)\1|(?<=\\) )+?)(?<!\\)\1(?!\1)/,
footnote_identifier: /^(\[\^)([^\^\[\]\s]+?)(?<!\\)\]/
}
/* eslint-enable no-useless-escape */
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/escapeCharacter.js | src/muya/lib/parser/escapeCharacter.js | // special character
const charachers = [
'"', '&', '<', '>',
' ', ' ', ' ', ' ',
'<', '>', '&', '"',
'©', '®', '™', '×', '÷',
' ', '¡', '¢', '£', '¤',
'¥', '¦', '§', '¨', '©',
'ª', '«', '¬', '', '®',
'¯', '°', '±', '²', '³',
'´', 'µ', '¶', '·', '¸',
'¹', 'º', '»', '¼', '½',
'¾', '¿', 'À', 'Á', 'Â',
'Ã', 'Ä', 'Å', 'Æ', 'Ç',
'È', 'É', 'Ê', 'Ë', 'Ì',
'Í', 'Î', 'Ï', 'Ð', 'Ñ',
'Ò', 'Ó', 'Ô', 'Õ', 'Ö',
'×', 'Ø', 'Ù', 'Ú', 'Û',
'Ü', 'Ý', 'Þ', 'ß', 'à',
'á', 'â', 'ã', 'ä', 'å',
'æ', 'ç', 'è', 'é', 'ê',
'ë', 'ì', 'í', 'î', 'ï',
'ð', 'ñ', 'ò', 'ó', 'ô',
'õ', 'ö', '÷', 'ø', 'ù',
'ú', 'û', 'ü', 'ý', 'þ', 'ÿ',
'ƒ', 'Α', 'Β', 'Γ', 'Δ',
'Ε', 'Ζ', 'Η', 'Θ', 'Ι',
'Κ', 'Λ', 'Μ', 'Ν', 'Ξ',
'Ο', 'Π', 'Ρ', 'Σ', 'Τ',
'Υ', 'Φ', 'Χ', 'Ψ', 'Ω',
'α', 'β', 'γ', 'δ', 'ε',
'ζ', 'η', 'θ', 'ι', 'κ',
'λ', 'μ', 'ν', 'ξ', 'ο',
'π', 'ρ', 'ς', 'σ', 'τ',
'υ', 'φ', 'χ', 'ψ', 'ω',
'ϑ', 'ϒ', 'ϖ', '•', '…',
'′', '″', '‾', '⁄', '℘',
'ℑ', 'ℜ', '™', 'ℵ', '←',
'↑', '→', '↓', '↔', '↵',
'⇐', '⇑', '⇒', '⇓', '⇔',
'∀', '∂', '∃', '∅', '∇',
'∈', '∉', '∋', '∏', '∑',
'−', '∗', '√', '∝', '∞',
'∠', '∧', '∨', '∩', '∪',
'∫', '∴', '∼', '≅', '≈',
'≠', '≡', '≤', '≥', '⊂',
'⊃', '⊄', '⊆', '⊇', '⊕',
'⊗', '⊥', '⋅', '⌈', '⌉',
'⌊', '⌋', '⟨', '⟩', '◊',
'♠', '♣', '♥', '♦',
'"', '&', '<', '>', 'Œ',
'œ', 'Š', 'š', 'Ÿ', 'ˆ',
'˜', ' ', ' ', ' ', '',
'', '', '', '–', '—',
'‘', '’', '‚', '“', '”',
'„', '†', '‡', '‰', '‹',
'›', '€'
]
export const escapeCharacters = [
'"', '&', '<', '>',
' ', ' ', ' ', ' ',
'<', '>', '&', '"',
'©', '®', '™', '×', '÷',
' ', '¡', '¢', '£', '¤',
'¥', '¦', '§', '¨', '©',
'ª', '«', '¬', '­', '®',
'¯', '°', '±', '²', '³',
'´', 'µ', '¶', '·', '¸',
'¹', 'º', '»', '¼', '½',
'¾', '¿', 'À', 'Á', 'Â',
'Ã', 'Ä', 'Å', 'Æ', 'Ç',
'È', 'É', 'Ê', 'Ë', 'Ì',
'Í', 'Î', 'Ï', 'Ð', 'Ñ',
'Ò', 'Ó', 'Ô', 'Õ', 'Ö',
'×', 'Ø', 'Ù', 'Ú', 'Û',
'Ü', 'Ý', 'Þ', 'ß', 'à',
'á', 'â', 'ã', 'ä', 'å',
'æ', 'ç', 'è', 'é', 'ê',
'ë', 'ì', 'í', 'î', 'ï',
'ð', 'ñ', 'ò', 'ó', 'ô',
'õ', 'ö', '÷', 'ø', 'ù',
'ú', 'û', 'ü', 'ý', 'þ', 'ÿ',
'ƒ', 'Α', 'Β', 'Γ', 'Δ',
'Ε', 'Ζ', 'Η', 'Θ', 'Ι',
'Κ', 'Λ', 'Μ', 'Ν', 'Ξ',
'Ο', 'Π', 'Ρ', 'Σ', 'Τ',
'Υ', 'Φ', 'Χ', 'Ψ', 'Ω',
'α', 'β', 'γ', 'δ', 'ε',
'ζ', 'η', 'θ', 'ι', 'κ',
'λ', 'μ', 'ν', 'ξ', 'ο',
'π', 'ρ', 'ς', 'σ', 'τ',
'υ', 'φ', 'χ', 'ψ', 'ω',
'ϑ', 'ϒ', 'ϖ', '•', '…',
'′', '″', '‾', '⁄', '℘',
'ℑ', 'ℜ', '™', 'ℵ', '←',
'↑', '→', '↓', '↔', '↵',
'⇐', '⇑', '⇒', '⇓', '⇔',
'∀', '∂', '∃', '∅', '∇',
'∈', '∉', '∋', '∏', '∑',
'−', '∗', '√', '∝', '∞',
'∠', '∧', '∨', '∩', '∪',
'∫', '∴', '∼', '≅', '≈',
'≠', '≡', '≤', '≥', '⊂',
'⊃', '⊄', '⊆', '⊇', '⊕',
'⊗', '⊥', '⋅', '⌈', '⌉',
'⌊', '⌋', '⟨', '⟩', '◊',
'♠', '♣', '♥', '♦',
'"', '&', '<', '>', 'Œ',
'œ', 'Š', 'š', 'Ÿ', 'ˆ',
'˜', ' ', ' ', ' ', '‌',
'‍', '‎', '‏', '–', '—',
'‘', '’', '‚', '“', '”',
'„', '†', '‡', '‰', '‹',
'›', '€'
]
const escapeCharactersMap = escapeCharacters.reduce((acc, escapeCharacter, index) => {
return Object.assign(acc, { [escapeCharacter]: charachers[index] })
}, {})
export default escapeCharactersMap
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/utils.js | src/muya/lib/parser/utils.js | // ASCII PUNCTUATION character
// export const punctuation = ['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~']
/* eslint-disable no-useless-escape, prefer-regex-literals */
export const PUNCTUATION_REG = new RegExp(/[!"#$%&'()*+,\-./:;<=>?@\[\]^_`{|}~\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E42\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDF3C-\uDF3E]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]/)
/* eslint-enable no-useless-escape, prefer-regex-literals */
// selected from https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
export const WHITELIST_ATTRIBUTES = Object.freeze([
'align', 'alt', 'checked', 'class', 'color', 'dir', 'disabled', 'for', 'height', 'hidden',
'href', 'id', 'lang', 'lazyload', 'rel', 'spellcheck', 'src', 'srcset', 'start', 'style',
'target', 'title', 'type', 'value', 'width',
// Used in img
'data-align'
])
// export const unicodeZsCategory = Object.freeze([
// '\u0020', '\u00A0', '\u1680', '\u2000', '\u2001', '\u2001',
// '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007',
// '\u2008', '\u2009', '\u200A', '\u202F', '\u205F', '\u3000'
// ])
// export const space = ['\u0020'] // space
// export const whitespaceCharacter = Object.freeze([
// ...space, // space
// '\u0009', // tab
// '\u000A', // newline
// '\u000B', // tabulation
// '\u000C', // form feed
// '\u000D' // carriage return
// ])
// export const unicodeWhitespaceCharacter = Object.freeze([
// ...unicodeZsCategory,
// '\u0009', // tab
// '\u000D', // carriage return
// '\u000A', // newline
// '\u000C' // form feed
// ])
const UNICODE_WHITESPACE_REG = /^\s/
const validWidthAndHeight = value => {
if (!/^\d{1,}$/.test(value)) return ''
value = parseInt(value)
return value >= 0 ? value : ''
}
export const lowerPriority = (src, offset, rules) => {
let i
const ignoreIndex = []
for (i = 0; i < offset; i++) {
if (ignoreIndex.includes(i)) {
continue
}
const text = src.substring(i)
for (const rule of Object.keys(rules)) {
const to = rules[rule].exec(text)
if (to && to[0].length <= offset - i) {
ignoreIndex.push(i + to[0].length - 1)
}
if (to && to[0].length > offset - i) {
return false
}
}
}
return true
}
export const getAttributes = html => {
const parser = new DOMParser()
const doc = parser.parseFromString(html, 'text/html')
const target = doc.querySelector('body').firstElementChild
if (!target) return null
const attrs = {}
if (target.tagName === 'IMG') {
Object.assign(attrs, {
title: '',
src: '',
alt: ''
})
}
for (const attr of target.getAttributeNames()) {
if (!WHITELIST_ATTRIBUTES.includes(attr)) continue
if (/width|height/.test(attr)) {
attrs[attr] = validWidthAndHeight(target.getAttribute(attr))
} else {
attrs[attr] = target.getAttribute(attr)
}
}
return attrs
}
export const parseSrcAndTitle = (text = '') => {
const parts = text.split(/\s+/)
if (parts.length === 1) {
return {
src: text.trim(),
title: ''
}
}
const rawTitle = text.replace(/^[^ ]+ +/, '')
let src = ''
const TITLE_REG = /^('|")(.*?)\1$/ // we only support use `'` and `"` to indicate a title now.
let title = ''
if (rawTitle && TITLE_REG.test(rawTitle)) {
title = rawTitle.replace(TITLE_REG, '$2')
}
if (title) {
src = text.substring(0, text.length - rawTitle.length).trim()
} else {
src = text.trim()
}
return { src, title }
}
const canOpenEmphasis = (src, marker, pending) => {
const precededChar = pending.charAt(pending.length - 1) || '\n'
const followedChar = src[marker.length]
// not followed by Unicode whitespace,
if (UNICODE_WHITESPACE_REG.test(followedChar)) {
return false
}
// and either (2a) not followed by a punctuation character,
// or (2b) followed by a punctuation character and preceded by Unicode whitespace or a punctuation character.
// For purposes of this definition, the beginning and the end of the line count as Unicode whitespace.
if (PUNCTUATION_REG.test(followedChar) && !(UNICODE_WHITESPACE_REG.test(precededChar) || PUNCTUATION_REG.test(precededChar))) {
return false
}
if (/_/.test(marker) && !(UNICODE_WHITESPACE_REG.test(precededChar) || PUNCTUATION_REG.test(precededChar))) {
return false
}
return true
}
const canCloseEmphasis = (src, offset, marker) => {
const precededChar = src[offset - marker.length - 1]
const followedChar = src[offset] || '\n'
// not preceded by Unicode whitespace,
if (UNICODE_WHITESPACE_REG.test(precededChar)) {
return false
}
// either (2a) not preceded by a punctuation character,
// or (2b) preceded by a punctuation character and followed by Unicode whitespace or a punctuation character.
if (PUNCTUATION_REG.test(precededChar) && !(UNICODE_WHITESPACE_REG.test(followedChar) || PUNCTUATION_REG.test(followedChar))) {
return false
}
if (/_/.test(marker) && !(UNICODE_WHITESPACE_REG.test(followedChar) || PUNCTUATION_REG.test(followedChar))) {
return false
}
return true
}
export const validateEmphasize = (src, offset, marker, pending, rules) => {
if (!canOpenEmphasis(src, marker, pending)) {
return false
}
if (!canCloseEmphasis(src, offset, marker)) {
return false
}
/**
* 16.When there are two potential emphasis or strong emphasis spans with the same closing delimiter,
* the shorter one (the one that opens later) takes precedence. Thus, for example, **foo **bar baz**
* is parsed as **foo <strong>bar baz</strong> rather than <strong>foo **bar baz</strong>.
*/
const mLen = marker.length
const emphasizeText = src.substring(mLen, offset - mLen)
const SHORTER_REG = new RegExp(` \\${marker.split('').join('\\')}[^\\${marker.charAt(0)}]`)
const CLOSE_REG = new RegExp(`[^\\${marker.charAt(0)}]\\${marker.split('').join('\\')}`)
if (emphasizeText.match(SHORTER_REG) && !emphasizeText.match(CLOSE_REG)) {
return false
}
/**
* 17.Inline code spans, links, images, and HTML tags group more tightly than emphasis.
* So, when there is a choice between an interpretation that contains one of these elements
* and one that does not, the former always wins. Thus, for example, *[foo*](bar) is parsed
* as *<a href="bar">foo*</a> rather than as <em>[foo</em>](bar).
*/
return lowerPriority(src, offset, rules)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/textRenderer.js | src/muya/lib/parser/marked/textRenderer.js | /**
* TextRenderer
* returns only the textual part of the token
*/
function TextRenderer () {}
// no need for block level renderers
TextRenderer.prototype.strong =
TextRenderer.prototype.em =
TextRenderer.prototype.codespan =
TextRenderer.prototype.del =
TextRenderer.prototype.text = function (text) {
return text
}
TextRenderer.prototype.html = function (html) {
return html
}
TextRenderer.prototype.inlineMath = function (math, displayMode) {
return math
}
TextRenderer.prototype.emoji = function (text, emoji) {
return emoji
}
TextRenderer.prototype.script = function (content, marker) {
const tagName = marker === '^' ? 'sup' : 'sub'
return `<${tagName}>${content}</${tagName}>`
}
TextRenderer.prototype.footnoteIdentifier = function (identifier, { footnoteId, footnoteIdentifierId, order }) {
return `<a href="#${footnoteId ? `fn${footnoteId}` : ''}" class="footnote-ref" id="fnref${footnoteIdentifierId}" role="doc-noteref"><sup>${order || identifier}</sup></a>`
}
TextRenderer.prototype.link =
TextRenderer.prototype.image = function (href, title, text) {
return '' + text
}
TextRenderer.prototype.br = function () {
return ''
}
export default TextRenderer
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/blockRules.js | src/muya/lib/parser/marked/blockRules.js | import { edit, noop } from './utils'
/* eslint-disable no-useless-escape */
/**
* Block-Level Rules
*/
export const block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/,
hr: /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,
heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,
blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
list: /^( {0,3})(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: '^ {0,3}(?:' + // optional indentation
'<(script|pre|style)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)' + // (1)
'|comment[^\\n]*(\\n+|$)' + // (2)
'|<\\?[\\s\\S]*?(?:\\?>\\n*|$)' + // (3)
'|<![A-Z][\\s\\S]*?(?:>\\n*|$)' + // (4)
'|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)' + // (5)
'|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:\\n{2,}|$)' + // (6)
'|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$)' + // (7) open tag
'|</(?!script|pre|style)[a-z][\\w-]*\\s*>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$)' + // (7) closing tag
')',
def: /^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,
nptable: noop,
table: noop,
lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,
// regex template, placeholders will be replaced according to different paragraph
// interruption rules of commonmark and the original markdown spec:
_paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html)[^\n]+)*)/,
text: /^[^\n]+/,
// extra
frontmatter: /^(?:(?:---\n([\s\S]+?)---)|(?:\+\+\+\n([\s\S]+?)\+\+\+)|(?:;;;\n([\s\S]+?);;;)|(?:\{\n([\s\S]+?)\}))(?:\n{2,}|\n{1,2}$)/,
multiplemath: /^\$\$\n([\s\S]+?)\n\$\$(?:\n+|$)/,
multiplemathGitlab: /^ {0,3}(`{3,})math\n(?:(|[\s\S]*?)\n)(?: {0,3}\1`* *(?:\n+|$)|$)/, // Math inside a code block (GitLab display math)
footnote: /^\[\^([^\^\[\]\s]+?)(?<!\\)\]:[\s\S]+?(?=\n *\n {0,3}[^ ]+|$)/
}
block._label = /(?!\s*\])(?:\\[\[\]]|[^\[\]])+/
block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/
block.def = edit(block.def)
.replace('label', block._label)
.replace('title', block._title)
.getRegex()
block.checkbox = /^\[([ xX])\] +/
block.bullet = /(?:[*+-]|\d{1,9}(?:\.|\)))/ // patched: support "(" as ordered list delimiter too
// patched: fix https://github.com/marktext/marktext/issues/831#issuecomment-477719256
// block.item = /^( *)(bull) ?[^\n]*(?:\n(?!\1bull ?)[^\n]*)*/
block.item = /^(( {0,3})(bull) [^\n]*(?:\n(?!(\2bull |\2bull\n))[^\n]*)*|( {0,3})(bull)(?:\n(?!(\2bull |\2bull\n)))*)/ // eslint-disable-line no-useless-backreference
block.item = edit(block.item, 'gm')
.replace(/bull/g, block.bullet)
.getRegex()
block.list = edit(block.list)
.replace(/bull/g, block.bullet)
.replace('hr', '\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))')
.replace('def', '\\n+(?=' + block.def.source + ')')
.getRegex()
block._tag = 'address|article|aside|base|basefont|blockquote|body|caption' +
'|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption' +
'|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe' +
'|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option' +
'|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr' +
'|track|ul'
block._comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/
block.html = edit(block.html, 'i')
.replace('comment', block._comment)
.replace('tag', block._tag)
.replace('attribute', / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/)
.getRegex()
block.paragraph = edit(block._paragraph)
.replace('hr', block.hr)
.replace('heading', ' {0,3}#{1,6} ')
.replace('|lheading', '') // setex headings don't interrupt commonmark paragraphs
.replace('blockquote', ' {0,3}>')
.replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
.replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
.replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)')
.replace('tag', block._tag) // pars can be interrupted by type (6) html blocks
.getRegex()
block.blockquote = edit(block.blockquote)
.replace('paragraph', block.paragraph)
.getRegex()
/**
* Normal Block Grammar
*/
export const normal = Object.assign({}, block)
/**
* GFM Block Grammar
*/
export const gfm = Object.assign({}, normal, {
nptable: '^ *([^|\\n ].*\\|.*)\\n' + // Header
' {0,3}([-:]+ *\\|[-| :]*)' + // Align
'(?:\\n((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)', // Cells
table: '^ *\\|(.+)\\n' + // Header
' {0,3}\\|?( *[-:]+[-| :]*)' + // Align
'(?:\\n *((?:(?!\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)' // Cells
})
gfm.nptable = edit(gfm.nptable)
.replace('hr', block.hr)
.replace('heading', ' {0,3}#{1,6} ')
.replace('blockquote', ' {0,3}>')
.replace('code', ' {4}[^\\n]')
.replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
.replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
.replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)')
.replace('tag', block._tag) // tables can be interrupted by type (6) html blocks
.getRegex()
gfm.table = edit(gfm.table)
.replace('hr', block.hr)
.replace('heading', ' {0,3}#{1,6} ')
.replace('blockquote', ' {0,3}>')
.replace('code', ' {4}[^\\n]')
.replace('fences', ' {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n')
.replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt
.replace('html', '</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|!--)')
.replace('tag', block._tag) // tables can be interrupted by type (6) html blocks
.getRegex()
/**
* Pedantic grammar (original John Gruber's loose markdown specification)
*/
export const pedantic = Object.assign({}, normal, {
html: edit(
'^ *(?:comment *(?:\\n|\\s*$)' +
'|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)' + // closed tag
'|<tag(?:"[^"]*"|\'[^\']*\'|\\s[^\'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))')
.replace('comment', block._comment)
.replace(/tag/g, '(?!(?:' +
'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub' +
'|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)' +
'\\b)\\w+(?!:|[^\\w\\s@]*@)\\b')
.getRegex(),
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
heading: /^(#{1,6})(.*)(?:\n+|$)/,
fences: noop, // fences not supported
paragraph: edit(normal._paragraph)
.replace('hr', block.hr)
.replace('heading', ' *#{1,6} *[^\n]')
.replace('lheading', block.lheading)
.replace('blockquote', ' {0,3}>')
.replace('|fences', '')
.replace('|list', '')
.replace('|html', '')
.getRegex()
})
/* eslint-ensable no-useless-escape */
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/urlify.js | src/muya/lib/parser/marked/urlify.js | // License: BSD
// Source: https://github.com/django/django/blob/master/django/contrib/admin/static/admin/js/urlify.js
//
// Copyright (c) Django Software Foundation and individual contributors.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of Django nor the names of its contributors may be used
// to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/* eslint-disable quote-props, object-property-newline */
const LATIN_MAP = {
'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'AE', 'Å': 'A', 'Æ': 'AE',
'Ç': 'C', 'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I',
'Î': 'I', 'Ï': 'I', 'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O',
'Õ': 'O', 'Ö': 'O', 'Ő': 'O', 'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U',
'Ü': 'U', 'Ű': 'U', 'Ý': 'Y', 'Þ': 'TH', 'Ÿ': 'Y', 'ß': 'ss', 'à': 'a',
'á': 'a', 'â': 'a', 'ã': 'a', 'ä': 'ae', 'å': 'a', 'æ': 'ae', 'ç': 'c',
'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e', 'ì': 'i', 'í': 'i', 'î': 'i',
'ï': 'i', 'ð': 'd', 'ñ': 'n', 'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o',
'ö': 'o', 'ő': 'o', 'ø': 'o', 'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u',
'ű': 'u', 'ý': 'y', 'þ': 'th', 'ÿ': 'y'
}
const LATIN_SYMBOLS_MAP = {
'©': '(c)',
'$': 'dollar',
'¢': 'cent',
'£': 'pound',
'¤': 'currency',
'¥': 'yen',
'%': 'percent',
'|': 'or',
// TODO: Not working
'&': 'and',
'<': 'less',
'>': 'greater',
'\'': 'single-quote',
'"': 'double-quote'
}
const GREEK_MAP = {
'α': 'a', 'β': 'b', 'γ': 'g', 'δ': 'd', 'ε': 'e', 'ζ': 'z', 'η': 'h',
'θ': '8', 'ι': 'i', 'κ': 'k', 'λ': 'l', 'μ': 'm', 'ν': 'n', 'ξ': '3',
'ο': 'o', 'π': 'p', 'ρ': 'r', 'σ': 's', 'τ': 't', 'υ': 'y', 'φ': 'f',
'χ': 'x', 'ψ': 'ps', 'ω': 'w', 'ά': 'a', 'έ': 'e', 'ί': 'i', 'ό': 'o',
'ύ': 'y', 'ή': 'h', 'ώ': 'w', 'ς': 's', 'ϊ': 'i', 'ΰ': 'y', 'ϋ': 'y',
'ΐ': 'i', 'Α': 'A', 'Β': 'B', 'Γ': 'G', 'Δ': 'D', 'Ε': 'E', 'Ζ': 'Z',
'Η': 'H', 'Θ': '8', 'Ι': 'I', 'Κ': 'K', 'Λ': 'L', 'Μ': 'M', 'Ν': 'N',
'Ξ': '3', 'Ο': 'O', 'Π': 'P', 'Ρ': 'R', 'Σ': 'S', 'Τ': 'T', 'Υ': 'Y',
'Φ': 'F', 'Χ': 'X', 'Ψ': 'PS', 'Ω': 'W', 'Ά': 'A', 'Έ': 'E', 'Ί': 'I',
'Ό': 'O', 'Ύ': 'Y', 'Ή': 'H', 'Ώ': 'W', 'Ϊ': 'I', 'Ϋ': 'Y'
}
const TURKISH_MAP = {
'ş': 's', 'Ş': 'S', 'ı': 'i', 'İ': 'I', 'ç': 'c', 'Ç': 'C', 'ü': 'u',
'Ü': 'U', 'ö': 'o', 'Ö': 'O', 'ğ': 'g', 'Ğ': 'G'
}
const ROMANIAN_MAP = {
'ă': 'a', 'î': 'i', 'ș': 's', 'ț': 't', 'â': 'a',
'Ă': 'A', 'Î': 'I', 'Ș': 'S', 'Ț': 'T', 'Â': 'A'
}
const RUSSIAN_MAP = {
'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'yo',
'ж': 'zh', 'з': 'z', 'и': 'i', 'й': 'j', 'к': 'k', 'л': 'l', 'м': 'm',
'н': 'n', 'о': 'o', 'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u',
'ф': 'f', 'х': 'h', 'ц': 'c', 'ч': 'ch', 'ш': 'sh', 'щ': 'sh', 'ъ': '',
'ы': 'y', 'ь': '', 'э': 'e', 'ю': 'yu', 'я': 'ya',
'А': 'A', 'Б': 'B', 'В': 'V', 'Г': 'G', 'Д': 'D', 'Е': 'E', 'Ё': 'Yo',
'Ж': 'Zh', 'З': 'Z', 'И': 'I', 'Й': 'J', 'К': 'K', 'Л': 'L', 'М': 'M',
'Н': 'N', 'О': 'O', 'П': 'P', 'Р': 'R', 'С': 'S', 'Т': 'T', 'У': 'U',
'Ф': 'F', 'Х': 'H', 'Ц': 'C', 'Ч': 'Ch', 'Ш': 'Sh', 'Щ': 'Sh', 'Ъ': '',
'Ы': 'Y', 'Ь': '', 'Э': 'E', 'Ю': 'Yu', 'Я': 'Ya'
}
const UKRAINIAN_MAP = {
'Є': 'Ye', 'І': 'I', 'Ї': 'Yi', 'Ґ': 'G', 'є': 'ye', 'і': 'i',
'ї': 'yi', 'ґ': 'g'
}
const CZECH_MAP = {
'č': 'c', 'ď': 'd', 'ě': 'e', 'ň': 'n', 'ř': 'r', 'š': 's', 'ť': 't',
'ů': 'u', 'ž': 'z', 'Č': 'C', 'Ď': 'D', 'Ě': 'E', 'Ň': 'N', 'Ř': 'R',
'Š': 'S', 'Ť': 'T', 'Ů': 'U', 'Ž': 'Z'
}
const SLOVAK_MAP = {
'á': 'a', 'ä': 'a', 'č': 'c', 'ď': 'd', 'é': 'e', 'í': 'i', 'ľ': 'l',
'ĺ': 'l', 'ň': 'n', 'ó': 'o', 'ô': 'o', 'ŕ': 'r', 'š': 's', 'ť': 't',
'ú': 'u', 'ý': 'y', 'ž': 'z',
'Á': 'a', 'Ä': 'A', 'Č': 'C', 'Ď': 'D', 'É': 'E', 'Í': 'I', 'Ľ': 'L',
'Ĺ': 'L', 'Ň': 'N', 'Ó': 'O', 'Ô': 'O', 'Ŕ': 'R', 'Š': 'S', 'Ť': 'T',
'Ú': 'U', 'Ý': 'Y', 'Ž': 'Z'
}
const POLISH_MAP = {
'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's',
'ź': 'z', 'ż': 'z',
'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ó': 'O', 'Ś': 'S',
'Ź': 'Z', 'Ż': 'Z'
}
const LATVIAN_MAP = {
'ā': 'a', 'č': 'c', 'ē': 'e', 'ģ': 'g', 'ī': 'i', 'ķ': 'k', 'ļ': 'l',
'ņ': 'n', 'š': 's', 'ū': 'u', 'ž': 'z',
'Ā': 'A', 'Č': 'C', 'Ē': 'E', 'Ģ': 'G', 'Ī': 'I', 'Ķ': 'K', 'Ļ': 'L',
'Ņ': 'N', 'Š': 'S', 'Ū': 'U', 'Ž': 'Z'
}
const ARABIC_MAP = {
'أ': 'a', 'ب': 'b', 'ت': 't', 'ث': 'th', 'ج': 'g', 'ح': 'h', 'خ': 'kh', 'د': 'd',
'ذ': 'th', 'ر': 'r', 'ز': 'z', 'س': 's', 'ش': 'sh', 'ص': 's', 'ض': 'd', 'ط': 't',
'ظ': 'th', 'ع': 'aa', 'غ': 'gh', 'ف': 'f', 'ق': 'k', 'ك': 'k', 'ل': 'l', 'م': 'm',
'ن': 'n', 'ه': 'h', 'و': 'o', 'ي': 'y'
}
const LITHUANIAN_MAP = {
'ą': 'a', 'č': 'c', 'ę': 'e', 'ė': 'e', 'į': 'i', 'š': 's', 'ų': 'u',
'ū': 'u', 'ž': 'z',
'Ą': 'A', 'Č': 'C', 'Ę': 'E', 'Ė': 'E', 'Į': 'I', 'Š': 'S', 'Ų': 'U',
'Ū': 'U', 'Ž': 'Z'
}
const SERBIAN_MAP = {
'ђ': 'dj', 'ј': 'j', 'љ': 'lj', 'њ': 'nj', 'ћ': 'c', 'џ': 'dz',
'đ': 'dj', 'Ђ': 'Dj', 'Ј': 'j', 'Љ': 'Lj', 'Њ': 'Nj', 'Ћ': 'C',
'Џ': 'Dz', 'Đ': 'Dj'
}
const AZERBAIJANI_MAP = {
'ç': 'c', 'ə': 'e', 'ğ': 'g', 'ı': 'i', 'ö': 'o', 'ş': 's', 'ü': 'u',
'Ç': 'C', 'Ə': 'E', 'Ğ': 'G', 'İ': 'I', 'Ö': 'O', 'Ş': 'S', 'Ü': 'U'
}
const GEORGIAN_MAP = {
'ა': 'a', 'ბ': 'b', 'გ': 'g', 'დ': 'd', 'ე': 'e', 'ვ': 'v', 'ზ': 'z',
'თ': 't', 'ი': 'i', 'კ': 'k', 'ლ': 'l', 'მ': 'm', 'ნ': 'n', 'ო': 'o',
'პ': 'p', 'ჟ': 'j', 'რ': 'r', 'ს': 's', 'ტ': 't', 'უ': 'u', 'ფ': 'f',
'ქ': 'q', 'ღ': 'g', 'ყ': 'y', 'შ': 'sh', 'ჩ': 'ch', 'ც': 'c', 'ძ': 'dz',
'წ': 'w', 'ჭ': 'ch', 'ხ': 'x', 'ჯ': 'j', 'ჰ': 'h'
}
const ALL_DOWNCODE_MAPS = [
LATIN_MAP,
LATIN_SYMBOLS_MAP,
GREEK_MAP,
TURKISH_MAP,
ROMANIAN_MAP,
RUSSIAN_MAP,
UKRAINIAN_MAP,
CZECH_MAP,
SLOVAK_MAP,
POLISH_MAP,
LATVIAN_MAP,
ARABIC_MAP,
LITHUANIAN_MAP,
SERBIAN_MAP,
AZERBAIJANI_MAP,
GEORGIAN_MAP
]
let downcoderMap = {}
let downcoderRegex = null
const initialize = () => {
if (downcoderRegex) {
return
}
downcoderMap = {}
for (const lookup of ALL_DOWNCODE_MAPS) {
Object.assign(downcoderMap, lookup)
}
downcoderRegex = new RegExp(Object.keys(downcoderMap).map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), 'g')
}
export const downcode = slug => {
initialize()
return slug.replace(downcoderRegex, function (m) {
return downcoderMap[m]
})
}
export const slugify = s => {
let slug = downcode(s)
.toLowerCase()
.trim()
.replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '')
.replace(/\s/g, '-')
// TODO: Use LRU-Cache?
return slug
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/index.js | src/muya/lib/parser/marked/index.js | import Renderer from './renderer'
import Lexer from './lexer'
import Parser from './parser'
import options from './options'
/**
* Marked
*/
function marked (src, opt = {}) {
// throw error in case of non string input
if (typeof src === 'undefined' || src === null) {
throw new Error('marked(): input parameter is undefined or null')
}
if (typeof src !== 'string') {
throw new Error('marked(): input parameter is of type ' +
Object.prototype.toString.call(src) + ', string expected')
}
try {
opt = Object.assign({}, options, opt)
return new Parser(opt).parse(new Lexer(opt).lex(src))
} catch (e) {
e.message += '\nPlease report this to https://github.com/marktext/marktext/issues.'
if (opt.silent) {
return '<p>An error occurred:</p><pre>' +
escape(e.message + '', true) +
'</pre>'
}
throw e
}
}
export {
Renderer, Lexer, Parser
}
export default marked
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/lexer.js | src/muya/lib/parser/marked/lexer.js | import { normal, gfm, pedantic } from './blockRules'
import options from './options'
import { splitCells, rtrim, getUniqueId } from './utils'
/**
* Block Lexer
*/
function Lexer (opts) {
this.tokens = []
this.tokens.links = Object.create(null)
this.tokens.footnotes = Object.create(null)
this.footnoteOrder = 0
this.options = Object.assign({}, options, opts)
this.rules = normal
if (this.options.pedantic) {
this.rules = pedantic
} else if (this.options.gfm) {
this.rules = gfm
}
}
/**
* Preprocessing
*/
Lexer.prototype.lex = function (src) {
src = src
.replace(/\r\n|\r/g, '\n')
.replace(/\t/g, ' ')
this.checkFrontmatter = true
this.footnoteOrder = 0
this.token(src, true)
// Move footnote token to the end of tokens.
const { tokens } = this
const hasNoFootnoteTokens = []
const footnoteTokens = []
let isInFootnote = false
for (const token of tokens) {
const { type } = token
if (type === 'footnote_start') {
isInFootnote = true
footnoteTokens.push(token)
} else if (type === 'footnote_end') {
isInFootnote = false
footnoteTokens.push(token)
} else if (isInFootnote) {
footnoteTokens.push(token)
} else {
hasNoFootnoteTokens.push(token)
}
}
const result = [...hasNoFootnoteTokens, ...footnoteTokens]
result.links = tokens.links
result.footnotes = tokens.footnotes
return result
}
/**
* Lexing
*/
Lexer.prototype.token = function (src, top) {
const {
footnote,
frontMatter,
isGitlabCompatibilityEnabled,
math
} = this.options
src = src.replace(/^ +$/gm, '')
let loose
let cap
let bull
let b
let item
let space
let i
let tag
let l
// Only check front matter at the begining of a markdown file.
// Please see note in "blockquote" why we need "checkFrontmatter" and "top".
if (frontMatter) {
cap = this.rules.frontmatter.exec(src)
if (this.checkFrontmatter && top && cap) {
src = src.substring(cap[0].length)
let lang
let style
let text
if (cap[1]) {
lang = 'yaml'
style = '-'
text = cap[1]
} else if (cap[2]) {
lang = 'toml'
style = '+'
text = cap[2]
} else if (cap[3] || cap[4]) {
lang = 'json'
style = cap[3] ? ';' : '{'
text = cap[3] || cap[4]
}
this.tokens.push({
type: 'frontmatter',
text,
style,
lang
})
}
this.checkFrontmatter = false
}
while (src) {
// newline
cap = this.rules.newline.exec(src)
if (cap) {
src = src.substring(cap[0].length)
if (cap[0].length > 1) {
this.tokens.push({
type: 'space'
})
}
}
// code
// An indented code block cannot interrupt a paragraph.
cap = this.rules.code.exec(src)
if (cap) {
const lastToken = this.tokens[this.tokens.length - 1]
src = src.substring(cap[0].length)
if (lastToken && lastToken.type === 'paragraph') {
lastToken.text += `\n${cap[0].trimRight()}`
} else {
cap = cap[0].replace(/^ {4}/gm, '')
this.tokens.push({
type: 'code',
codeBlockStyle: 'indented',
text: !this.options.pedantic
? rtrim(cap, '\n')
: cap
})
}
continue
}
// multiple line math
if (math) {
cap = this.rules.multiplemath.exec(src)
if (cap) {
src = src.substring(cap[0].length)
this.tokens.push({
type: 'multiplemath',
text: cap[1],
mathStyle: ''
})
continue
}
// match GitLab display math blocks (```math)
if (isGitlabCompatibilityEnabled) {
cap = this.rules.multiplemathGitlab.exec(src)
if (cap) {
src = src.substring(cap[0].length)
this.tokens.push({
type: 'multiplemath',
text: cap[2] || '',
mathStyle: 'gitlab'
})
continue
}
}
}
// footnote
if (footnote) {
cap = this.rules.footnote.exec(src)
if (top && cap) {
src = src.substring(cap[0].length)
const identifier = cap[1]
this.tokens.push({
type: 'footnote_start',
identifier
})
// NOTE: Order is wrong if footnote identifier 1 is behind footnote identifier 2 in text.
this.tokens.footnotes[identifier] = {
order: ++this.footnoteOrder,
identifier,
footnoteId: getUniqueId()
}
/* eslint-disable no-useless-escape */
// Remove the footnote identifer prefix. eg: `[^identifier]: `.
cap = cap[0].replace(/^\[\^[^\^\[\]\s]+?(?<!\\)\]:\s*/gm, '')
// Remove the four whitespace before each block of footnote.
cap = cap.replace(/\n {4}(?=[^\s])/g, '\n')
/* eslint-enable no-useless-escape */
this.token(cap, top)
this.tokens.push({
type: 'footnote_end'
})
continue
}
}
// fences
cap = this.rules.fences.exec(src)
if (cap) {
src = src.substring(cap[0].length)
const raw = cap[0]
const text = indentCodeCompensation(raw, cap[3] || '')
this.tokens.push({
type: 'code',
codeBlockStyle: 'fenced',
lang: cap[2] ? cap[2].trim() : cap[2],
text
})
continue
}
// heading
cap = this.rules.heading.exec(src)
if (cap) {
src = src.substring(cap[0].length)
let text = cap[2] ? cap[2].trim() : ''
if (text.endsWith('#')) {
let trimmed = rtrim(text, '#')
if (this.options.pedantic) {
text = trimmed.trim()
} else if (!trimmed || trimmed.endsWith(' ')) {
// CommonMark requires space before trailing #s
text = trimmed.trim()
}
}
this.tokens.push({
type: 'heading',
headingStyle: 'atx',
depth: cap[1].length,
text
})
continue
}
// table no leading pipe (gfm)
cap = this.rules.nptable.exec(src)
if (cap) {
item = {
type: 'table',
header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : []
}
if (item.header.length === item.align.length) {
src = src.substring(cap[0].length)
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right'
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center'
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left'
} else {
item.align[i] = null
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = splitCells(item.cells[i], item.header.length)
}
this.tokens.push(item)
continue
}
}
// hr
cap = this.rules.hr.exec(src)
if (cap) {
const marker = cap[0].replace(/\n*$/, '')
src = src.substring(cap[0].length)
this.tokens.push({
type: 'hr',
marker
})
continue
}
// blockquote
cap = this.rules.blockquote.exec(src)
if (cap) {
src = src.substring(cap[0].length)
this.tokens.push({
type: 'blockquote_start'
})
cap = cap[0].replace(/^ *> ?/gm, '')
// Pass `top` to keep the current
// "toplevel" state. This is exactly
// how markdown.pl works.
this.token(cap, top)
this.tokens.push({
type: 'blockquote_end'
})
continue
}
// NOTE: Complete list lexer part is a custom implementation based on an older marked.js version.
// list
cap = this.rules.list.exec(src)
if (cap) {
let checked
src = src.substring(cap[0].length)
bull = cap[2]
let isOrdered = bull.length > 1
this.tokens.push({
type: 'list_start',
ordered: isOrdered,
listType: bull.length > 1 ? 'order' : (/^( {0,3})([-*+]) \[[xX ]\]/.test(cap[0]) ? 'task' : 'bullet'),
start: isOrdered ? +(bull.slice(0, -1)) : ''
})
let next = false
let prevNext = true
let listItemIndices = []
let isTaskList = false
// Get each top-level item.
cap = cap[0].match(this.rules.item)
l = cap.length
i = 0
for (; i < l; i++) {
const itemWithBullet = cap[i]
item = itemWithBullet
let newIsTaskListItem = false
// Remove the list item's bullet so it is seen as the next token.
space = item.length
let newBull
item = item.replace(/^ *([*+-]|\d+(?:\.|\))) {0,4}/, function (m, p1) {
// Get and remove list item bullet
newBull = p1 || bull
return ''
})
const newIsOrdered = bull.length > 1 && /\d{1,9}/.test(newBull)
if (!newIsOrdered && this.options.gfm) {
checked = this.rules.checkbox.exec(item)
if (checked) {
checked = checked[1] === 'x' || checked[1] === 'X'
newIsTaskListItem = true
// Remove the list item's checkbox and adjust indentation by removing checkbox length.
item = item.replace(this.rules.checkbox, '')
space -= 4
} else {
checked = undefined
}
}
if (i === 0) {
isTaskList = newIsTaskListItem
} else if (
// Changing the bullet or ordered list delimiter starts a new list (CommonMark 264 and 265)
// - unordered, unordered --> bull !== newBull --> new list (e.g "-" --> "*")
// - ordered, ordered --> lastChar !== lastChar --> new list (e.g "." --> ")")
// - else --> new list (e.g. ordered --> unordered)
i !== 0 &&
(
(!isOrdered && !newIsOrdered && bull !== newBull) ||
(isOrdered && newIsOrdered && bull.slice(-1) !== newBull.slice(-1)) ||
(isOrdered !== newIsOrdered) ||
// Changing to/from task list item from/to bullet, starts a new list(work for marktext issue #870)
// Because we distinguish between task list and bullet list in MarkText,
// the parsing here is somewhat different from the commonmark Spec,
// and the task list needs to be a separate list.
(isTaskList !== newIsTaskListItem)
)
) {
this.tokens.push({
type: 'list_end'
})
// Start a new list
bull = newBull
isOrdered = newIsOrdered
isTaskList = newIsTaskListItem
this.tokens.push({
type: 'list_start',
ordered: isOrdered,
listType: bull.length > 1 ? 'order' : (/^( {0,3})([-*+]) \[[xX ]\]/.test(itemWithBullet) ? 'task' : 'bullet'),
start: isOrdered ? +(bull.slice(0, -1)) : ''
})
}
// Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) {
space -= item.length
item = !this.options.pedantic
? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
: item.replace(/^ {1,4}/gm, '')
}
// Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (i !== l - 1) {
b = this.rules.bullet.exec(cap[i + 1])[0]
if (bull.length > 1
? b.length === 1
: (b.length > 1 || (this.options.smartLists && b !== bull))) {
src = cap.slice(i + 1).join('\n') + src
i = l - 1
}
}
let prevItem = ''
if (i === 0) {
prevItem = item
} else {
prevItem = cap[i - 1]
}
// Determine whether item is loose or not. If previous item is loose
// this item is also loose.
// A list is loose if any of its constituent list items are separated by blank lines,
// or if any of its constituent list items directly contain two block-level elements with a blank line between them.
// loose = next = next || /^ *([*+-]|\d{1,9}(?:\.|\)))( +\S+\n\n(?!\s*$)|\n\n(?!\s*$))/.test(itemWithBullet)
loose = next = next || /\n\n(?!\s*$)/.test(item)
// Check if previous line ends with a new line.
if (!loose && (i !== 0 || l > 1) && prevItem.length !== 0 && prevItem.charAt(prevItem.length - 1) === '\n') {
loose = next = true
}
// A list is either loose or tight, so update previous list items but not nested list items.
if (next && prevNext !== next) {
for (const index of listItemIndices) {
this.tokens[index].type = 'loose_item_start'
}
listItemIndices = []
}
prevNext = next
if (!loose) {
listItemIndices.push(this.tokens.length)
}
const isOrderedListItem = /\d/.test(bull)
this.tokens.push({
checked,
listItemType: bull.length > 1 ? 'order' : (isTaskList ? 'task' : 'bullet'),
bulletMarkerOrDelimiter: isOrderedListItem ? bull.slice(-1) : bull.charAt(0),
type: loose ? 'loose_item_start' : 'list_item_start'
})
if (/^\s*$/.test(item)) {
this.tokens.push({
type: 'text',
text: ''
})
} else {
// Recurse.
this.token(item, false)
}
this.tokens.push({
type: 'list_item_end'
})
}
this.tokens.push({
type: 'list_end'
})
continue
}
// html
cap = this.rules.html.exec(src)
if (cap) {
src = src.substring(cap[0].length)
this.tokens.push({
type: this.options.sanitize
? 'paragraph'
: 'html',
pre: !this.options.sanitizer &&
(cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
text: this.options.sanitize ? (this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0])) : cap[0]
})
continue
}
// def
cap = this.rules.def.exec(src)
if (top && cap) {
let text = ''
do {
src = src.substring(cap[0].length)
if (cap[3]) cap[3] = cap[3].substring(1, cap[3].length - 1)
tag = cap[1].toLowerCase().replace(/\s+/g, ' ')
if (!this.tokens.links[tag]) {
this.tokens.links[tag] = {
href: cap[2],
title: cap[3]
}
}
text += cap[0]
if (cap[0].endsWith('\n\n')) break
cap = this.rules.def.exec(src)
} while (cap)
if (this.options.disableInline) {
this.tokens.push({
type: 'paragraph',
text: text.replace(/\n*$/, '')
})
}
continue
}
// table (gfm)
cap = this.rules.table.exec(src)
if (cap) {
item = {
type: 'table',
header: splitCells(cap[1].replace(/^ *| *\| *$/g, '')),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3] ? cap[3].replace(/\n$/, '').split('\n') : []
}
if (item.header.length === item.align.length) {
src = src.substring(cap[0].length)
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right'
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center'
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left'
} else {
item.align[i] = null
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = splitCells(
item.cells[i].replace(/^ *\| *| *\| *$/g, ''),
item.header.length)
}
this.tokens.push(item)
continue
}
}
// lheading
cap = this.rules.lheading.exec(src)
if (cap) {
const precededToken = this.tokens[this.tokens.length - 1]
const chops = cap[0].trim().split(/\n/)
const marker = chops[chops.length - 1]
src = src.substring(cap[0].length)
if (precededToken && precededToken.type === 'paragraph') {
this.tokens.pop()
this.tokens.push({
type: 'heading',
headingStyle: 'setext',
depth: cap[2].charAt(0) === '=' ? 1 : 2,
text: precededToken.text + '\n' + cap[1],
marker
})
} else {
this.tokens.push({
type: 'heading',
headingStyle: 'setext',
depth: cap[2].charAt(0) === '=' ? 1 : 2,
text: cap[1],
marker
})
}
continue
}
// top-level paragraph
cap = this.rules.paragraph.exec(src)
if (top && cap) {
src = src.substring(cap[0].length)
if (/^\[toc\]\n?$/i.test(cap[1])) {
this.tokens.push({ type: 'toc', text: '[TOC]' })
continue
}
this.tokens.push({
type: 'paragraph',
text: cap[1].charAt(cap[1].length - 1) === '\n'
? cap[1].slice(0, -1)
: cap[1]
})
continue
}
// text
cap = this.rules.text.exec(src)
if (cap) {
// Top-level should never reach here.
src = src.substring(cap[0].length)
this.tokens.push({
type: 'text',
text: cap[0]
})
continue
}
if (src) {
throw new Error('Infinite loop on byte: ' + src.charCodeAt(0))
}
}
}
function indentCodeCompensation (raw, text) {
const matchIndentToCode = raw.match(/^(\s+)(?:```)/)
if (matchIndentToCode === null) {
return text
}
const indentToCode = matchIndentToCode[1]
return text
.split('\n')
.map(node => {
const matchIndentInNode = node.match(/^\s+/)
if (matchIndentInNode === null) {
return node
}
const [indentInNode] = matchIndentInNode
if (indentInNode.length >= indentToCode.length) {
return node.slice(indentToCode.length)
}
return node
})
.join('\n')
}
export default Lexer
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/inlineRules.js | src/muya/lib/parser/marked/inlineRules.js | import { block } from './blockRules'
import { edit, noop } from './utils'
/* eslint-disable no-useless-escape */
/**
* Inline-Level Grammar
*/
const inline = {
escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/, // eslint-disable-line no-control-regex
url: noop,
tag: '^comment' +
'|^</[a-zA-Z][\\w:-]*\\s*>' + // self-closing tag
'|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>' + // open tag
'|^<\\?[\\s\\S]*?\\?>' + // processing instruction, e.g. <?php ?>
'|^<![a-zA-Z]+\\s[\\s\\S]*?>' + // declaration, e.g. <!DOCTYPE html>
'|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>', // CDATA section
link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,
reflink: /^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,
nolink: /^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,
strong: /^__([^\s_])__(?!_)|^\*\*([^\s*])\*\*(?!\*)|^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)/,
em: /^_([^\s_])_(?!_)|^\*([^\s*<\[])\*(?!\*)|^_([^\s<][\s\S]*?[^\s_])_(?!_|[^\spunctuation])|^_([^\s_<][\s\S]*?[^\s])_(?!_|[^\spunctuation])|^\*([^\s<"][\s\S]*?[^\s\*])\*(?!\*|[^\spunctuation])|^\*([^\s*"<\[][\s\S]*?[^\s])\*(?!\*)/,
code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
br: /^( {2,}|\\)\n(?!\s*$)/,
del: noop,
// ------------------------
// patched
// allow inline math "$" and superscript ("?=[\\<!\[`*]" to "?=[\\<!\[`*\$^]")
text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*\$^]|\b_|$)|[^ ](?= {2,}\n))|(?= {2,}\n))/, // emoji is patched in gfm
// ------------------------
// extra
emoji: noop,
// TODO: make math optional GH#740
math: /^\$([^$]*?[^\$\\])\$(?!\$)/,
// superscript and subScript
superscript: /^(\^)((?:[^\^\s]|(?<=\\)\1|(?<=\\) )+?)(?<!\\)\1(?!\1)/,
subscript: /^(~)((?:[^~\s]|(?<=\\)\1|(?<=\\) )+?)(?<!\\)\1(?!\1)/,
footnoteIdentifier: /^\[\^([^\^\[\]\s]+?)(?<!\\)\]/
}
// list of punctuation marks from common mark spec
// without ` and ] to workaround Rule 17 (inline code blocks/links)
// without , to work around example 393
inline._punctuation = '!"#$%&\'()+\\-.,/:;<=>?@\\[\\]`^{|}~'
inline._comment = edit(block._comment).replace('(?:-->|$)', '-->').getRegex()
inline.em = edit(inline.em).replace(/punctuation/g, inline._punctuation).getRegex()
inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g
inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/
inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/
inline.autolink = edit(inline.autolink)
.replace('scheme', inline._scheme)
.replace('email', inline._email)
.getRegex()
inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/
inline.tag = edit(inline.tag)
.replace('comment', inline._comment)
.replace('attribute', inline._attribute)
.getRegex()
inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/
inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/ // eslint-disable-line no-control-regex
inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/
inline.link = edit(inline.link)
.replace('label', inline._label)
.replace('href', inline._href)
.replace('title', inline._title)
.getRegex()
inline.reflink = edit(inline.reflink)
.replace('label', inline._label)
.getRegex()
/**
* Normal Inline Grammar
*/
export const normal = Object.assign({}, inline)
/**
* Pedantic Inline Grammar
*/
export const pedantic = Object.assign({}, normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,
link: edit(/^!?\[(label)\]\((.*?)\)/)
.replace('label', inline._label)
.getRegex(),
reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/)
.replace('label', inline._label)
.getRegex()
})
/**
* GFM Inline Grammar
*/
export const gfm = Object.assign({}, normal, {
escape: edit(inline.escape).replace('])', '~|])').getRegex(),
_extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,
url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
_backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,
del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
// ------------------------
// patched
// allow inline math "$" and emoji ":" and superscrpt "^" ("?=[\\<!\[`*~]|" to "?=[\\<!\[`*~:\$^]|")
text: /^([`~]+|[^`~])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*~:\$^]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))|(?= {2,}\n|[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))/,
// ------------------------
// extra
emoji: /^(:)([a-z_\d+-]+?)\1/ // not real GFM but put it in here
})
gfm.url = edit(gfm.url, 'i')
.replace('email', gfm._extended_email)
.getRegex()
/**
* GFM + Line Breaks Inline Grammar
*/
export const breaks = Object.assign({}, gfm, {
br: edit(inline.br).replace('{2,}', '*').getRegex(),
text: edit(gfm.text)
.replace('\\b_', '\\b_| {2,}\\n')
.replace(/\{2,\}/g, '*')
.getRegex()
})
/* eslint-ensable no-useless-escape */
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/slugger.js | src/muya/lib/parser/marked/slugger.js | import { downcode } from './urlify'
/**
* Slugger generates header id
*/
function Slugger () {
this.seen = {}
this.downcodeUnicode = true
}
/**
* Convert string to unique id
*/
Slugger.prototype.slug = function (value) {
let slug = this.downcodeUnicode ? downcode(value) : value
slug = slug
.toLowerCase()
.trim()
// remove html tags
.replace(/<[!\/a-z].*?>/ig, '') // eslint-disable-line no-useless-escape
// remove unwanted chars
.replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '')
.replace(/\s/g, '-')
if (this.seen.hasOwnProperty(slug)) {
const originalSlug = slug
do {
this.seen[originalSlug]++
slug = originalSlug + '-' + this.seen[originalSlug]
} while (this.seen.hasOwnProperty(slug))
}
this.seen[slug] = 0
return slug
}
export default Slugger
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/inlineLexer.js | src/muya/lib/parser/marked/inlineLexer.js | import Renderer from './renderer'
import { normal, breaks, gfm, pedantic } from './inlineRules'
import defaultOptions from './options'
import { escape, findClosingBracket, getUniqueId, rtrim } from './utils'
import { validateEmphasize, lowerPriority } from '../utils'
/**
* Inline Lexer & Compiler
*/
function InlineLexer (links, footnotes, options) {
this.options = options || defaultOptions
this.links = links
this.footnotes = footnotes
this.rules = normal
this.renderer = this.options.renderer || new Renderer()
this.renderer.options = this.options
if (!this.links) {
throw new Error('Tokens array requires a `links` property.')
}
if (this.options.pedantic) {
this.rules = pedantic
} else if (this.options.gfm) {
if (this.options.breaks) {
this.rules = breaks
} else {
this.rules = gfm
}
}
this.highPriorityEmpRules = {}
this.highPriorityLinkRules = {}
for (const key of Object.keys(this.rules)) {
if (/^(?:autolink|link|code|tag)$/.test(key) && this.rules[key] instanceof RegExp) {
this.highPriorityEmpRules[key] = this.rules[key]
}
}
for (const key of Object.keys(this.rules)) {
if (/^(?:autolink|code|tag)$/.test(key) && this.rules[key] instanceof RegExp) {
this.highPriorityLinkRules[key] = this.rules[key]
}
}
}
/**
* Lexing/Compiling
*/
InlineLexer.prototype.output = function (src) {
// src = src
// .replace(/\u00a0/g, ' ')
const { disableInline, emoji, math, superSubScript, footnote } = this.options
if (disableInline) {
return escape(src)
}
let out = ''
let link
let text
let href
let title
let cap
let prevCapZero
let lastChar = ''
while (src) {
// escape
cap = this.rules.escape.exec(src)
if (cap) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
out += escape(cap[1])
continue
}
// footnote identifier
if (footnote) {
cap = this.rules.footnoteIdentifier.exec(src)
if (cap) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
const identifier = cap[1]
const footnoteInfo = this.footnotes[identifier] || {}
if (footnoteInfo.footnoteIdentifierId === undefined) {
footnoteInfo.footnoteIdentifierId = getUniqueId()
}
out += this.renderer.footnoteIdentifier(identifier, footnoteInfo)
}
}
// tag
cap = this.rules.tag.exec(src)
if (cap) {
if (!this.inLink && /^<a /i.test(cap[0])) {
this.inLink = true
} else if (this.inLink && /^<\/a>/i.test(cap[0])) {
this.inLink = false
}
if (!this.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
this.inRawBlock = true
} else if (this.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
this.inRawBlock = false
}
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
out += this.renderer.html(this.options.sanitize
? (this.options.sanitizer
? this.options.sanitizer(cap[0])
: escape(cap[0]))
: cap[0])
continue
}
// link
cap = this.rules.link.exec(src)
if (cap && lowerPriority(src, cap[0].length, this.highPriorityLinkRules)) {
const trimmedUrl = cap[2].trim()
if (!this.options.pedantic && trimmedUrl.startsWith('<')) {
// commonmark requires matching angle brackets
if (!trimmedUrl.endsWith('>')) {
return
}
// ending angle bracket cannot be escaped
const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\')
if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
return
}
} else {
// find closing parenthesis
const lastParenIndex = findClosingBracket(cap[2], '()')
if (lastParenIndex > -1) {
const start = cap[0].indexOf('!') === 0 ? 5 : 4
const linkLen = start + cap[1].length + lastParenIndex
cap[2] = cap[2].substring(0, lastParenIndex)
cap[0] = cap[0].substring(0, linkLen).trim()
cap[3] = ''
}
}
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
href = cap[2]
if (this.options.pedantic) {
// split pedantic href and title
link = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href)
if (link) {
href = link[1]
title = link[3]
}
} else {
title = cap[3] ? cap[3].slice(1, -1) : ''
}
href = href.trim()
if (href.startsWith('<')) {
if (this.options.pedantic && !trimmedUrl.endsWith('>')) {
// pedantic allows starting angle bracket without ending angle bracket
href = href.slice(1)
} else {
href = href.slice(1, -1)
}
}
this.inLink = true
out += this.outputLink(cap, {
href: this.escapes(href),
title: this.escapes(title)
})
this.inLink = false
continue
}
// reflink, nolink
cap = this.rules.reflink.exec(src) || this.rules.nolink.exec(src)
if (cap) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
link = (cap[2] || cap[1]).replace(/\s+/g, ' ')
link = this.links[link.toLowerCase()]
if (!link || !link.href) {
out += cap[0].charAt(0)
src = cap[0].substring(1) + src
continue
}
this.inLink = true
out += this.outputLink(cap, link)
this.inLink = false
continue
}
// math
if (math) {
cap = this.rules.math.exec(src)
if (cap) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
text = cap[1]
out += this.renderer.inlineMath(text)
}
}
// emoji
if (emoji) {
cap = this.rules.emoji.exec(src)
if (cap) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
text = cap[0]
out += this.renderer.emoji(text, cap[2])
}
}
// superSubScript
if (superSubScript) {
cap = this.rules.superscript.exec(src) || this.rules.subscript.exec(src)
if (cap) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
const content = cap[2]
const marker = cap[1]
out += this.renderer.script(content, marker)
}
}
// strong
cap = this.rules.strong.exec(src)
if (cap) {
const marker = cap[0].match(/^(?:_{1,2}|\*{1,2})/)[0]
const isValid = validateEmphasize(src, cap[0].length, marker, lastChar, this.highPriorityEmpRules)
if (isValid) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
out += this.renderer.strong(this.output(cap[4] || cap[3] || cap[2] || cap[1]))
continue
}
}
// em
cap = this.rules.em.exec(src)
if (cap) {
const marker = cap[0].match(/^(?:_{1,2}|\*{1,2})/)[0]
const isValid = validateEmphasize(src, cap[0].length, marker, lastChar, this.highPriorityEmpRules)
if (isValid) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
out += this.renderer.em(this.output(cap[6] || cap[5] || cap[4] || cap[3] || cap[2] || cap[1]))
continue
}
}
// code
cap = this.rules.code.exec(src)
if (cap) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
let text = cap[2].replace(/\n/g, ' ')
const hasNonSpaceChars = /[^ ]/.test(text)
const hasSpaceCharsOnBothEnds = text.startsWith(' ') && text.endsWith(' ')
if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
text = text.substring(1, text.length - 1)
}
text = escape(text, true)
out += this.renderer.codespan(text)
continue
}
// br
cap = this.rules.br.exec(src)
if (cap) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
out += this.renderer.br()
continue
}
// del (gfm)
cap = this.rules.del.exec(src)
if (cap) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
out += this.renderer.del(this.output(cap[2]))
continue
}
// autolink
cap = this.rules.autolink.exec(src)
if (cap) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
if (cap[2] === '@') {
text = escape(this.mangle(cap[1]))
href = 'mailto:' + text
} else {
text = escape(cap[1])
href = text
}
out += this.renderer.link(href, null, text)
continue
}
// url (gfm)
cap = this.rules.url.exec(src)
if (!this.inLink && cap) {
if (cap[2] === '@') {
text = escape(cap[0])
href = 'mailto:' + text
} else {
// do extended autolink path validation
do {
prevCapZero = cap[0]
cap[0] = this.rules._backpedal.exec(cap[0])[0]
} while (prevCapZero !== cap[0])
text = escape(cap[0])
if (cap[1] === 'www.') {
href = 'http://' + text
} else {
href = text
}
}
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
out += this.renderer.link(href, null, text)
continue
}
// text
cap = this.rules.text.exec(src)
if (cap) {
src = src.substring(cap[0].length)
lastChar = cap[0].charAt(cap[0].length - 1)
if (this.inRawBlock) {
out += this.renderer.text(this.options.sanitize ? (this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape(cap[0])) : cap[0])
} else {
out += this.renderer.text(escape(this.smartypants(cap[0])))
}
continue
}
if (src) {
throw new Error('Infinite loop on byte: ' + src.charCodeAt(0))
}
}
return out
}
InlineLexer.prototype.escapes = function (text) {
return text ? text.replace(this.rules._escapes, '$1') : text
}
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function (cap, link) {
const href = link.href
const title = link.title ? escape(link.title) : null
const text = cap[1].replace(/\\([\[\]])/g, '$1') // eslint-disable-line no-useless-escape
return cap[0].charAt(0) !== '!'
? this.renderer.link(href, title, this.output(text))
: this.renderer.image(href, title, escape(text))
}
/**
* Smartypants Transformations
*/
InlineLexer.prototype.smartypants = function (text) {
/* eslint-disable no-useless-escape */
if (!this.options.smartypants) return text
return text
// em-dashes
.replace(/---/g, '\u2014')
// en-dashes
.replace(/--/g, '\u2013')
// opening singles
.replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
// closing singles & apostrophes
.replace(/'/g, '\u2019')
// opening doubles
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
// closing doubles
.replace(/"/g, '\u201d')
// ellipses
.replace(/\.{3}/g, '\u2026')
/* eslint-ensable no-useless-escape */
}
/**
* Mangle Links
*/
InlineLexer.prototype.mangle = function (text) {
if (!this.options.mangle) return text
const l = text.length
let out = ''
let ch
for (let i = 0; i < l; i++) {
ch = text.charCodeAt(i)
if (Math.random() > 0.5) {
ch = 'x' + ch.toString(16)
}
out += '&#' + ch + ';'
}
return out
}
export default InlineLexer
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/renderer.js | src/muya/lib/parser/marked/renderer.js | import defaultOptions from './options'
import { cleanUrl, escape } from './utils'
/**
* Renderer
*/
function Renderer (options = {}) {
this.options = options || defaultOptions
}
Renderer.prototype.frontmatter = function (text) {
return `<pre class="front-matter">\n${text}</pre>\n`
}
Renderer.prototype.multiplemath = function (text) {
let output = ''
if (this.options.mathRenderer) {
const displayMode = true
output = this.options.mathRenderer(text, displayMode)
}
return output || `<pre class="multiple-math">\n${text}</pre>\n`
}
Renderer.prototype.inlineMath = function (math) {
let output = ''
if (this.options.mathRenderer) {
const displayMode = false
output = this.options.mathRenderer(math, displayMode)
}
return output || math
}
Renderer.prototype.emoji = function (text, emoji) {
if (this.options.emojiRenderer) {
return this.options.emojiRenderer(emoji)
} else {
return text
}
}
Renderer.prototype.script = function (content, marker) {
const tagName = marker === '^' ? 'sup' : 'sub'
return `<${tagName}>${content}</${tagName}>`
}
Renderer.prototype.footnoteIdentifier = function (identifier, { footnoteId, footnoteIdentifierId, order }) {
return `<a href="#${footnoteId ? `fn${footnoteId}` : ''}" class="footnote-ref" id="fnref${footnoteIdentifierId}" role="doc-noteref"><sup>${order || identifier}</sup></a>`
}
Renderer.prototype.footnote = function (footnote) {
return '<section class="footnotes" role="doc-endnotes">\n<hr />\n<ol>\n' + footnote + '</ol>\n</section>\n'
}
Renderer.prototype.footnoteItem = function (content, { footnoteId, footnoteIdentifierId }) {
return `<li id="fn${footnoteId}" role="doc-endnote">${content}<a href="#${footnoteIdentifierId ? `fnref${footnoteIdentifierId}` : ''}" class="footnote-back" role="doc-backlink">↩︎</a></li>`
}
Renderer.prototype.code = function (code, infostring, escaped, codeBlockStyle) {
const lang = (infostring || '').match(/\S*/)[0]
if (this.options.highlight) {
const out = this.options.highlight(code, lang)
if (out !== null && out !== code) {
escaped = true
code = out
}
}
let className = codeBlockStyle === 'fenced' ? 'fenced-code-block' : 'indented-code-block'
className = lang ? `${className} ${this.options.langPrefix}${escape(lang, true)}` : className
return '<pre><code class="' +
className +
'">' +
(escaped ? code : escape(code, true)) +
'</code></pre>\n'
}
Renderer.prototype.blockquote = function (quote) {
return '<blockquote>\n' + quote + '</blockquote>\n'
}
Renderer.prototype.html = function (html) {
return html
}
Renderer.prototype.heading = function (text, level, raw, slugger, headingStyle) {
if (this.options.headerIds) {
return '<h' +
level +
' id="' +
this.options.headerPrefix +
slugger.slug(raw) +
'" class="' +
headingStyle +
'">' +
text +
'</h' +
level +
'>\n'
}
// ignore IDs
return '<h' + level + '>' + text + '</h' + level + '>\n'
}
Renderer.prototype.hr = function () {
return this.options.xhtml ? '<hr/>\n' : '<hr>\n'
}
Renderer.prototype.list = function (body, ordered, start, taskList) {
const type = ordered ? 'ol' : 'ul'
const startatt = (ordered && start !== 1) ? (' start="' + start + '"') : ''
return '<' + type + startatt + '>\n' + body + '</' + type + '>\n'
}
Renderer.prototype.listitem = function (text, checked) {
// normal list
if (checked === undefined) {
return '<li>' + text + '</li>\n'
}
// task list
return '<li class="task-list-item"><input type="checkbox"' +
(checked ? ' checked=""' : '') +
' disabled=""' +
(this.options.xhtml ? ' /' : '') +
'> ' +
text +
'</li>\n'
}
Renderer.prototype.paragraph = function (text) {
return '<p>' + text + '</p>\n'
}
Renderer.prototype.table = function (header, body) {
if (body) body = '<tbody>' + body + '</tbody>'
return '<table>\n' +
'<thead>\n' +
header +
'</thead>\n' +
body +
'</table>\n'
}
Renderer.prototype.tablerow = function (content) {
return '<tr>\n' + content + '</tr>\n'
}
Renderer.prototype.tablecell = function (content, flags) {
const type = flags.header ? 'th' : 'td'
const tag = flags.align
? '<' + type + ' align="' + flags.align + '">'
: '<' + type + '>'
return tag + content + '</' + type + '>\n'
}
// span level renderer
Renderer.prototype.strong = function (text) {
return '<strong>' + text + '</strong>'
}
Renderer.prototype.em = function (text) {
return '<em>' + text + '</em>'
}
Renderer.prototype.codespan = function (text) {
return '<code>' + text + '</code>'
}
Renderer.prototype.br = function () {
return this.options.xhtml ? '<br/>' : '<br>'
}
Renderer.prototype.del = function (text) {
return '<del>' + text + '</del>'
}
Renderer.prototype.link = function (href, title, text) {
href = cleanUrl(this.options.sanitize, this.options.baseUrl, href)
if (href === null) {
return text
}
let out = '<a href="' + escape(href) + '"'
if (title) {
out += ' title="' + title + '"'
}
out += '>' + text + '</a>'
return out
}
Renderer.prototype.image = function (href, title, text) {
if (!href) {
return text
}
// Fix ASCII and UNC paths on Windows (#1997).
if (/^(?:[a-zA-Z]:\\|[a-zA-Z]:\/).+/.test(href)) {
href = 'file:///' + href.replace(/\\/g, '/')
} else if (/^\\\?\\.+/.test(href)) {
// NOTE: Only check for "\?\" instead of "\\?\" because URL escaping removes the first "\".
href = 'file:///' + href.substring(3).replace(/\\/g, '/')
} else if (/^\/.+/.test(href)) {
// Be consistent but it's not needed.
href = 'file://' + href
}
href = cleanUrl(this.options.sanitize, this.options.baseUrl, href)
if (href === null) {
return text
}
let out = '<img src="' + href + '" alt="' + text.replace(/\*/g, '') + '"'
if (title) {
out += ' title="' + title + '"'
}
out += this.options.xhtml ? '/>' : '>'
return out
}
Renderer.prototype.text = function (text) {
return text
}
Renderer.prototype.toc = function () {
if (this.options.tocRenderer) {
return this.options.tocRenderer()
}
return ''
}
export default Renderer
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/options.js | src/muya/lib/parser/marked/options.js | export default {
baseUrl: null,
breaks: false,
gfm: true,
headerIds: true,
headerPrefix: '',
highlight: null,
mathRenderer: null,
emojiRenderer: null,
tocRenderer: null,
langPrefix: 'language-',
mangle: true,
pedantic: false,
renderer: null, // new Renderer(),
silent: false,
smartLists: false,
smartypants: false,
xhtml: false,
disableInline: false,
// NOTE: sanitize and sanitizer are deprecated since version 0.7.0, should not be used and will be removed in the future.
sanitize: false,
sanitizer: null,
// Markdown extensions:
// TODO: We set whether to support `emoji`, `math`, `frontMatter` default value to `true`
// After we add user setting, we maybe set math and frontMatter default value to false.
// User need to enable them in the user setting.
emoji: true,
math: true,
frontMatter: true,
superSubScript: false,
footnote: false,
isGitlabCompatibilityEnabled: false,
isHtmlEnabled: true
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/parser.js | src/muya/lib/parser/marked/parser.js | import Renderer from './renderer'
import InlineLexer from './inlineLexer'
import Slugger from './slugger'
import TextRenderer from './textRenderer'
import defaultOptions from './options'
/**
* Parsing & Compiling
*/
function Parser (options) {
this.tokens = []
this.token = null
this.footnotes = null
this.footnoteIdentifier = ''
this.options = options || defaultOptions
this.options.renderer = this.options.renderer || new Renderer()
this.renderer = this.options.renderer
this.renderer.options = this.options
this.slugger = new Slugger()
}
/**
* Parse Loop
*/
Parser.prototype.parse = function (src) {
this.inline = new InlineLexer(src.links, src.footnotes, this.options)
// use an InlineLexer with a TextRenderer to extract pure text
this.inlineText = new InlineLexer(
src.links,
src.footnotes,
Object.assign({}, this.options, { renderer: new TextRenderer() })
)
this.tokens = src.reverse()
this.footnotes = src.footnotes
let out = ''
while (this.next()) {
out += this.tok()
}
return out
}
/**
* Next Token
*/
Parser.prototype.next = function () {
this.token = this.tokens.pop()
return this.token
}
/**
* Preview Next Token
*/
Parser.prototype.peek = function () {
return this.tokens[this.tokens.length - 1] || 0
}
/**
* Parse Text Tokens
*/
Parser.prototype.parseText = function () {
let body = this.token.text
while (this.peek().type === 'text') {
body += '\n' + this.next().text
}
return this.inline.output(body)
}
/**
* Parse Current Token
*/
Parser.prototype.tok = function () {
switch (this.token.type) {
case 'frontmatter': {
return this.renderer.frontmatter(this.token.text)
}
case 'space': {
return ''
}
case 'hr': {
return this.renderer.hr()
}
case 'heading': {
return this.renderer.heading(
this.inline.output(this.token.text),
this.token.depth,
unescape(this.inlineText.output(this.token.text)),
this.slugger,
this.token.headingStyle
)
}
case 'multiplemath': {
const { text } = this.token
return this.renderer.multiplemath(text)
}
case 'code': {
const { codeBlockStyle, text, lang, escaped } = this.token
return this.renderer.code(text, lang, escaped, codeBlockStyle)
}
case 'table': {
let header = ''
let body = ''
let i
let row
let cell
let j
// header
cell = ''
for (i = 0; i < this.token.header.length; i++) {
cell += this.renderer.tablecell(
this.inline.output(this.token.header[i]), {
header: true,
align: this.token.align[i]
}
)
}
header += this.renderer.tablerow(cell)
for (i = 0; i < this.token.cells.length; i++) {
row = this.token.cells[i]
cell = ''
for (j = 0; j < row.length; j++) {
cell += this.renderer.tablecell(
this.inline.output(row[j]), {
header: false,
align: this.token.align[j]
}
)
}
body += this.renderer.tablerow(cell)
}
return this.renderer.table(header, body)
}
case 'blockquote_start': {
let body = ''
while (this.next().type !== 'blockquote_end') {
body += this.tok()
}
return this.renderer.blockquote(body)
}
// All the tokens will be footnotes if it after a footnote_start token. Because we put all footnote token at the end.
case 'footnote_start': {
let body = ''
let itemBody = ''
this.footnoteIdentifier = this.token.identifier
while (this.next()) {
if (this.token.type === 'footnote_end') {
const footnoteInfo = this.footnotes[this.footnoteIdentifier]
body += this.renderer.footnoteItem(itemBody, footnoteInfo)
this.footnoteIdentifier = ''
itemBody = ''
} else if (this.token.type === 'footnote_start') {
this.footnoteIdentifier = this.token.identifier
itemBody = ''
} else {
itemBody += this.tok()
}
}
return this.renderer.footnote(body)
}
case 'list_start': {
let body = ''
let taskList = false
const { ordered, start } = this.token
while (this.next().type !== 'list_end') {
if (this.token.checked !== undefined) {
taskList = true
}
body += this.tok()
}
return this.renderer.list(body, ordered, start, taskList)
}
case 'list_item_start': {
let body = ''
const { checked } = this.token
while (this.next().type !== 'list_item_end') {
body += this.token.type === 'text' ? this.parseText() : this.tok()
}
return this.renderer.listitem(body, checked)
}
case 'loose_item_start': {
let body = ''
const { checked } = this.token
while (this.next().type !== 'list_item_end') {
body += this.tok()
}
return this.renderer.listitem(body, checked)
}
case 'html': {
// TODO parse inline content if parameter markdown=1
return this.renderer.html(this.token.text)
}
case 'paragraph': {
return this.renderer.paragraph(this.inline.output(this.token.text))
}
case 'text': {
return this.renderer.paragraph(this.parseText())
}
case 'toc': {
return this.renderer.toc()
}
default: {
const errMsg = 'Token with "' + this.token.type + '" type was not found.'
if (this.options.silent) {
console.error(errMsg)
} else {
throw new Error(errMsg)
}
}
}
}
export default Parser
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/marked/utils.js | src/muya/lib/parser/marked/utils.js | /**
* Helpers
*/
let uniqueIdCounter = 0
export const getUniqueId = () => ++uniqueIdCounter
export const escape = function escape (html, encode) {
if (encode) {
if (escape.escapeTest.test(html)) {
return html.replace(escape.escapeReplace, function (ch) { return escape.replacements[ch] })
}
} else {
if (escape.escapeTestNoEncode.test(html)) {
return html.replace(escape.escapeReplaceNoEncode, function (ch) { return escape.replacements[ch] })
}
}
return html
}
escape.escapeTest = /[&<>"']/
escape.escapeReplace = /[&<>"']/g
escape.replacements = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}
escape.escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/
escape.escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g
export const unescape = function unescape (html) {
// explicitly match decimal, hex, and named HTML entities
return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, function (_, n) {
n = n.toLowerCase()
if (n === 'colon') return ':'
if (n.charAt(0) === '#') {
return n.charAt(1) === 'x'
? String.fromCharCode(parseInt(n.substring(2), 16))
: String.fromCharCode(+n.substring(1))
}
return ''
})
}
export const edit = function edit (regex, opt) {
regex = regex.source || regex
opt = opt || ''
return {
replace: function (name, val) {
val = val.source || val
val = val.replace(/(^|[^\[])\^/g, '$1') // eslint-disable-line no-useless-escape
regex = regex.replace(name, val)
return this
},
getRegex: function () {
return new RegExp(regex, opt)
}
}
}
export const cleanUrl = function cleanUrl (sanitize, base, href) {
if (sanitize) {
let prot = ''
try {
prot = decodeURIComponent(unescape(href))
.replace(/[^\w:]/g, '')
.toLowerCase()
} catch (e) {
return null
}
if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
return null
}
}
if (base && !originIndependentUrl.test(href)) {
href = resolveUrl(base, href)
}
try {
href = encodeURI(href).replace(/%25/g, '%')
} catch (e) {
return null
}
return href
}
const resolveUrl = function resolveUrl (base, href) {
if (!baseUrls[' ' + base]) {
// we can ignore everything in base after the last slash of its path component,
// but we might need to add _that_
// https://tools.ietf.org/html/rfc3986#section-3
if (/^[^:]+:\/*[^/]*$/.test(base)) {
baseUrls[' ' + base] = base + '/'
} else {
baseUrls[' ' + base] = rtrim(base, '/', true)
}
}
base = baseUrls[' ' + base]
let relativeBase = base.indexOf(':') === -1
if (href.slice(0, 2) === '//') {
if (relativeBase) {
return href
}
return base.replace(/^([^:]+:)[\s\S]*$/, '$1') + href
} else if (href.charAt(0) === '/') {
if (relativeBase) {
return href
}
return base.replace(/^([^:]+:\/*[^/]*)[\s\S]*$/, '$1') + href
} else {
return base + href
}
}
const baseUrls = {}
const originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i
export const noop = function noop () {}
noop.exec = noop
export const splitCells = function splitCells (tableRow, count) {
// ensure that every cell-delimiting pipe has a space
// before it to distinguish it from an escaped pipe
const row = tableRow.replace(/\|/g, function (match, offset, str) {
let escaped = false
let curr = offset
while (--curr >= 0 && str[curr] === '\\') escaped = !escaped
if (escaped) {
// odd number of slashes means | is escaped
// so we leave it alone
return '|'
} else {
// add space before unescaped |
return ' |'
}
})
const cells = row.split(/ \|/)
let i = 0
if (cells.length > count) {
cells.splice(count)
} else {
while (cells.length < count) cells.push('')
}
for (; i < cells.length; i++) {
// leading or trailing whitespace is ignored per the gfm spec
cells[i] = cells[i].trim().replace(/\\\|/g, '|')
}
return cells
}
// Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').
// /c*$/ is vulnerable to REDOS.
// invert: Remove suffix of non-c chars instead. Default falsey.
export const rtrim = function rtrim (str, c, invert) {
if (str.length === 0) {
return ''
}
// Length of suffix matching the invert condition.
let suffLen = 0
// Step left until we fail to match the invert condition.
while (suffLen < str.length) {
const currChar = str.charAt(str.length - suffLen - 1)
if (currChar === c && !invert) {
suffLen++
} else if (currChar !== c && invert) {
suffLen++
} else {
break
}
}
return str.substr(0, str.length - suffLen)
}
export const findClosingBracket = function findClosingBracket (str, b) {
if (str.indexOf(b[1]) === -1) {
return -1
}
let level = 0
for (let i = 0; i < str.length; i++) {
if (str[i] === '\\') {
i++
} else if (str[i] === b[0]) {
level++
} else if (str[i] === b[1]) {
level--
if (level < 0) {
return i
}
}
}
return -1
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/plantuml.js | src/muya/lib/parser/render/plantuml.js | import zlib from 'zlib'
import { toHTML, h } from './snabbdom'
const PLANTUML_URL = 'https://www.plantuml.com/plantuml'
function replaceChar (tableIn, tableOut, char) {
const charIndex = tableIn.indexOf(char)
return tableOut[charIndex]
}
function maketrans (tableIn, tableOut, value) {
return [...value].map(i => replaceChar(tableIn, tableOut, i)).join('')
}
export default class Diagram {
encodedInput = ''
/**
* Builds a Diagram object storing the encoded input value
*/
static parse (input) {
const diagram = new Diagram()
diagram.encodedInput = Diagram.encode(input)
return diagram
}
/**
* Encodes a diagram following PlantUML specs
*
* From https://plantuml.com/text-encoding
* 1. Encoded in UTF-8
* 2. Compressed using Deflate or Brotli algorithm
* 3. Reencoded in ASCII using a transformation close to base64
*/
static encode (value) {
const tableIn =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
const tableOut =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'
const utf8Value = decodeURIComponent(encodeURIComponent(value))
const compressedValue = zlib.deflateSync(utf8Value, { level: 3 })
const base64Value = compressedValue.toString('base64')
return maketrans(tableIn, tableOut, base64Value)
}
insertImgElement (container) {
const div = typeof container === 'string'
? document.getElementById(container)
: container
if (div === null || !div.tagName) {
throw new Error('Invalid container: ' + container)
}
const src = `${PLANTUML_URL}/svg/~1${this.encodedInput}`
const node = h('img', { attrs: { src } })
div.innerHTML = toHTML(node)
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/sequence.js | src/muya/lib/parser/render/sequence.js |
import Diagram from '../../assets/libs/sequence-diagram-snap'
import '../../assets/styles/sequence-diagram.css'
export default Diagram
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/index.js | src/muya/lib/parser/render/index.js | import loadRenderer from '../../renderers'
import { CLASS_OR_ID, PREVIEW_DOMPURIFY_CONFIG } from '../../config'
import { conflict, mixins, camelToSnake, sanitize } from '../../utils'
import { patch, toVNode, toHTML, h } from './snabbdom'
import { beginRules } from '../rules'
import renderInlines from './renderInlines'
import renderBlock from './renderBlock'
class StateRender {
constructor (muya) {
this.muya = muya
this.eventCenter = muya.eventCenter
this.codeCache = new Map()
this.loadImageMap = new Map()
this.loadMathMap = new Map()
this.mermaidCache = new Map()
this.diagramCache = new Map()
this.tokenCache = new Map()
this.labels = new Map()
this.urlMap = new Map()
this.renderingTable = null
this.renderingRowContainer = null
this.container = null
}
setContainer (container) {
this.container = container
}
// collect link reference definition
collectLabels (blocks) {
this.labels.clear()
const travel = block => {
const { text, children } = block
if (children && children.length) {
children.forEach(c => travel(c))
} else if (text) {
const tokens = beginRules.reference_definition.exec(text)
if (tokens) {
const key = (tokens[2] + tokens[3]).toLowerCase()
if (!this.labels.has(key)) {
this.labels.set(key, {
href: tokens[6],
title: tokens[10] || ''
})
}
}
}
}
blocks.forEach(b => travel(b))
}
checkConflicted (block, token, cursor) {
const { start, end } = cursor
const key = block.key
const { start: tokenStart, end: tokenEnd } = token.range
if (key !== start.key && key !== end.key) {
return false
} else if (key === start.key && key !== end.key) {
return conflict([tokenStart, tokenEnd], [start.offset, start.offset])
} else if (key !== start.key && key === end.key) {
return conflict([tokenStart, tokenEnd], [end.offset, end.offset])
} else {
return conflict([tokenStart, tokenEnd], [start.offset, start.offset]) ||
conflict([tokenStart, tokenEnd], [end.offset, end.offset])
}
}
getClassName (outerClass, block, token, cursor) {
return outerClass || (this.checkConflicted(block, token, cursor) ? CLASS_OR_ID.AG_GRAY : CLASS_OR_ID.AG_HIDE)
}
getHighlightClassName (active) {
return active ? CLASS_OR_ID.AG_HIGHLIGHT : CLASS_OR_ID.AG_SELECTION
}
getSelector (block, activeBlocks) {
const { cursor, selectedBlock } = this.muya.contentState
const type = block.type === 'hr' ? 'p' : block.type
const isActive = activeBlocks.some(b => b.key === block.key) || block.key === cursor.start.key
let selector = `${type}#${block.key}.${CLASS_OR_ID.AG_PARAGRAPH}`
if (isActive) {
selector += `.${CLASS_OR_ID.AG_ACTIVE}`
}
if (type === 'span') {
selector += `.ag-${camelToSnake(block.functionType)}`
}
if (!block.parent && selectedBlock && block.key === selectedBlock.key) {
selector += `.${CLASS_OR_ID.AG_SELECTED}`
}
return selector
}
async renderMermaid () {
if (this.mermaidCache.size) {
const mermaid = await loadRenderer('mermaid')
mermaid.initialize({
securityLevel: 'strict',
theme: this.muya.options.mermaidTheme
})
for (const [key, value] of this.mermaidCache.entries()) {
const { code } = value
const target = document.querySelector(key)
if (!target) {
continue
}
try {
mermaid.parse(code)
target.innerHTML = sanitize(code, PREVIEW_DOMPURIFY_CONFIG, true)
mermaid.init(undefined, target)
} catch (err) {
target.innerHTML = '< Invalid Mermaid Codes >'
target.classList.add(CLASS_OR_ID.AG_MATH_ERROR)
}
}
this.mermaidCache.clear()
}
}
async renderDiagram () {
const cache = this.diagramCache
if (cache.size) {
const RENDER_MAP = {
flowchart: await loadRenderer('flowchart'),
sequence: await loadRenderer('sequence'),
plantuml: await loadRenderer('plantuml'),
'vega-lite': await loadRenderer('vega-lite')
}
for (const [key, value] of cache.entries()) {
const target = document.querySelector(key)
if (!target) {
continue
}
const { code, functionType } = value
const render = RENDER_MAP[functionType]
const options = {}
if (functionType === 'sequence') {
Object.assign(options, { theme: this.muya.options.sequenceTheme })
} else if (functionType === 'vega-lite') {
Object.assign(options, {
actions: false,
tooltip: false,
renderer: 'svg',
theme: this.muya.options.vegaTheme
})
}
try {
if (functionType === 'flowchart' || functionType === 'sequence') {
const diagram = render.parse(code)
target.innerHTML = ''
diagram.drawSVG(target, options)
} else if (functionType === 'plantuml') {
const diagram = render.parse(code)
target.innerHTML = ''
diagram.insertImgElement(target)
} else if (functionType === 'vega-lite') {
await render(key, JSON.parse(code), options)
}
} catch (err) {
target.innerHTML = `< Invalid ${functionType === 'flowchart' ? 'Flow Chart' : 'Sequence'} Codes >`
target.classList.add(CLASS_OR_ID.AG_MATH_ERROR)
}
}
this.diagramCache.clear()
}
}
render (blocks, activeBlocks, matches) {
const selector = `div#${CLASS_OR_ID.AG_EDITOR_ID}`
const children = blocks.map(block => {
return this.renderBlock(null, block, activeBlocks, matches, true)
})
const newVdom = h(selector, children)
const rootDom = document.querySelector(selector) || this.container
const oldVdom = toVNode(rootDom)
patch(oldVdom, newVdom)
this.renderMermaid()
this.renderDiagram()
this.codeCache.clear()
}
// Only render the blocks which you updated
partialRender (blocks, activeBlocks, matches, startKey, endKey) {
const cursorOutMostBlock = activeBlocks[activeBlocks.length - 1]
// If cursor is not in render blocks, need to render cursor block independently
const needRenderCursorBlock = blocks.indexOf(cursorOutMostBlock) === -1
const newVnode = h('section', blocks.map(block => this.renderBlock(null, block, activeBlocks, matches)))
const html = toHTML(newVnode).replace(/^<section>([\s\S]+?)<\/section>$/, '$1')
const needToRemoved = []
const firstOldDom = startKey
? document.querySelector(`#${startKey}`)
: document.querySelector(`div#${CLASS_OR_ID.AG_EDITOR_ID}`).firstElementChild
if (!firstOldDom) {
// TODO@Jocs Just for fix #541, Because I'll rewrite block and render method, it will nolonger have this issue.
return
}
needToRemoved.push(firstOldDom)
let nextSibling = firstOldDom.nextElementSibling
while (nextSibling && nextSibling.id !== endKey) {
needToRemoved.push(nextSibling)
nextSibling = nextSibling.nextElementSibling
}
nextSibling && needToRemoved.push(nextSibling)
firstOldDom.insertAdjacentHTML('beforebegin', html)
Array.from(needToRemoved).forEach(dom => dom.remove())
// Render cursor block independently
if (needRenderCursorBlock) {
const { key } = cursorOutMostBlock
const cursorDom = document.querySelector(`#${key}`)
if (cursorDom) {
const oldCursorVnode = toVNode(cursorDom)
const newCursorVnode = this.renderBlock(null, cursorOutMostBlock, activeBlocks, matches)
patch(oldCursorVnode, newCursorVnode)
}
}
this.renderMermaid()
this.renderDiagram()
this.codeCache.clear()
}
/**
* Only render one block.
*
* @param {object} block
* @param {array} activeBlocks
* @param {array} matches
*/
singleRender (block, activeBlocks, matches) {
const selector = `#${block.key}`
const newVdom = this.renderBlock(null, block, activeBlocks, matches, true)
const rootDom = document.querySelector(selector)
const oldVdom = toVNode(rootDom)
patch(oldVdom, newVdom)
this.renderMermaid()
this.renderDiagram()
this.codeCache.clear()
}
invalidateImageCache () {
this.loadImageMap.forEach((imageInfo, key) => {
imageInfo.touchMsec = Date.now()
this.loadImageMap.set(key, imageInfo)
})
}
}
mixins(StateRender, renderInlines, renderBlock)
export default StateRender
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/snabbdom.js | src/muya/lib/parser/render/snabbdom.js | import {
init,
classModule,
attributesModule,
datasetModule,
propsModule,
styleModule,
eventListenersModule,
h as sh,
toVNode as sToVNode
} from 'snabbdom'
export const patch = init([
classModule,
attributesModule,
styleModule,
propsModule,
datasetModule,
eventListenersModule
])
export const h = sh
export const toVNode = sToVNode
export const toHTML = require('snabbdom-to-html') // helper function for convert vnode to HTML string
export const htmlToVNode = html => { // helper function for convert html to vnode
const wrapper = document.createElement('div')
wrapper.innerHTML = html
return toVNode(wrapper).children
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/em.js | src/muya/lib/parser/render/renderInlines/em.js | export default function em (h, cursor, block, token, outerClass) {
return this.delEmStrongFac('em', h, cursor, block, token, outerClass)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/header.js | src/muya/lib/parser/render/renderInlines/header.js | import { CLASS_OR_ID } from '../../../config'
export default function header (h, cursor, block, token, outerClass) {
const { content } = token
const { start, end } = token.range
const className = this.getClassName(outerClass, block, {
range: {
start,
end: end - content.length
}
}, cursor)
const markerVnode = this.highlight(h, block, start, end - content.length, token)
const contentVnode = this.highlight(h, block, end - content.length, end, token)
const spaceSelector = className === CLASS_OR_ID.AG_HIDE
? `span.${CLASS_OR_ID.AG_HEADER_TIGHT_SPACE}.${CLASS_OR_ID.AG_REMOVE}`
: `span.${CLASS_OR_ID.AG_GRAY}.${CLASS_OR_ID.AG_REMOVE}`
return [
h(`span.${className}.${CLASS_OR_ID.AG_REMOVE}`, markerVnode),
h(spaceSelector, contentVnode)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/hardLineBreak.js | src/muya/lib/parser/render/renderInlines/hardLineBreak.js | import { CLASS_OR_ID } from '../../../config'
export default function softLineBreak (h, cursor, block, token, outerClass) {
const { spaces, lineBreak, isAtEnd } = token
const className = CLASS_OR_ID.AG_HARD_LINE_BREAK
const spaceClass = CLASS_OR_ID.AG_HARD_LINE_BREAK_SPACE
if (isAtEnd) {
return [
h(`span.${className}`, h(`span.${spaceClass}`, spaces)),
h(`span.${CLASS_OR_ID.AG_LINE_END}`, lineBreak)
]
} else {
return [
h(`span.${className}`, [h(`span.${spaceClass}`, spaces), lineBreak])
]
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/referenceImage.js | src/muya/lib/parser/render/renderInlines/referenceImage.js | import { CLASS_OR_ID } from '../../../config'
import { getImageInfo } from '../../../utils'
// reference_image
export default function referenceImage (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const imageClass = CLASS_OR_ID.AG_IMAGE_MARKED_TEXT
const { start, end } = token.range
const tag = this.highlight(h, block, start, end, token)
const { label, backlash, alt } = token
const rawSrc = label + backlash.second
let href = ''
let title = ''
if (this.labels.has((rawSrc).toLowerCase())) {
({ href, title } = this.labels.get(rawSrc.toLowerCase()))
}
const imageInfo = getImageInfo(href)
const { src } = imageInfo
let id
let isSuccess
let domsrc
let selector
if (src) {
({ id, isSuccess, domsrc } = this.loadImageAsync(imageInfo, { alt }, className, CLASS_OR_ID.AG_COPY_REMOVE))
}
selector = id ? `span#${id}.${imageClass}` : `span.${imageClass}`
selector += `.${CLASS_OR_ID.AG_OUTPUT_REMOVE}`
if (isSuccess) {
selector += `.${className}`
} else {
selector += `.${CLASS_OR_ID.AG_IMAGE_FAIL}`
}
return isSuccess
? [
h(selector, tag),
h(`img.${CLASS_OR_ID.AG_COPY_REMOVE}`, { props: { alt, src: domsrc, title } })
]
: [h(selector, tag)]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/htmlRuby.js | src/muya/lib/parser/render/renderInlines/htmlRuby.js | import { CLASS_OR_ID } from '../../../config'
import { htmlToVNode } from '../snabbdom'
export default function htmlRuby (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const { children } = token
const { start, end } = token.range
const content = this.highlight(h, block, start, end, token)
const vNode = htmlToVNode(token.raw)
const previewSelector = `span.${CLASS_OR_ID.AG_RUBY_RENDER}`
return children
? [
h(`span.${className}.${CLASS_OR_ID.AG_RUBY}`, [
h(`span.${CLASS_OR_ID.AG_INLINE_RULE}.${CLASS_OR_ID.AG_RUBY_TEXT}`, content),
h(previewSelector, {
attrs: {
contenteditable: 'false',
spellcheck: 'false'
}
}, vNode)
])
// if children is empty string, no need to render ruby charactors...
]
: [
h(`span.${className}.${CLASS_OR_ID.AG_RUBY}`, [
h(`span.${CLASS_OR_ID.AG_INLINE_RULE}.${CLASS_OR_ID.AG_RUBY_TEXT}`, content)
])
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/emoji.js | src/muya/lib/parser/render/renderInlines/emoji.js | import { CLASS_OR_ID } from '../../../config'
import { validEmoji } from '../../../ui/emojis'
// render token of emoji to vdom
export default function emoji (h, cursor, block, token, outerClass) {
const { start: rStart, end: rEnd } = token.range
const className = this.getClassName(outerClass, block, token, cursor)
const validation = validEmoji(token.content)
const finalClass = validation ? className : CLASS_OR_ID.AG_WARN
const contentSelector = finalClass !== CLASS_OR_ID.AG_GRAY
? `span.${finalClass}.${CLASS_OR_ID.AG_INLINE_RULE}.${CLASS_OR_ID.AG_EMOJI_MARKED_TEXT}`
: `span.${CLASS_OR_ID.AG_INLINE_RULE}.${CLASS_OR_ID.AG_EMOJI_MARKED_TEXT}`
let startMarkerSelector = `span.${finalClass}.${CLASS_OR_ID.AG_EMOJI_MARKER}`
let endMarkerSelector = startMarkerSelector
let content = token.content
let pos = rStart + token.marker.length
if (token.highlights && token.highlights.length) {
content = []
for (const light of token.highlights) {
let { start, end, active } = light
const HIGHLIGHT_CLASSNAME = this.getHighlightClassName(active)
if (start === rStart) {
startMarkerSelector += `.${HIGHLIGHT_CLASSNAME}`
start++
}
if (end === rEnd) {
endMarkerSelector += `.${HIGHLIGHT_CLASSNAME}`
end--
}
if (pos < start) {
content.push(block.text.substring(pos, start))
}
if (start < end) {
content.push(h(`span.${HIGHLIGHT_CLASSNAME}`, block.text.substring(start, end)))
}
pos = end
}
if (pos < rEnd - token.marker.length) {
content.push(block.text.substring(pos, rEnd - 1))
}
}
const emojiVdom = validation
? h(contentSelector, {
attrs: {
spellcheck: 'false'
},
dataset: {
emoji: validation.emoji
}
}, content)
: h(contentSelector, content)
return [
h(startMarkerSelector, token.marker),
emojiVdom,
h(endMarkerSelector, token.marker)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/backlashInToken.js | src/muya/lib/parser/render/renderInlines/backlashInToken.js | import { union, isEven } from '../../../utils'
import { CLASS_OR_ID } from '../../../config'
// TODO HIGHLIGHT
export default function backlashInToken (h, backlashes, outerClass, start, token) {
const { highlights = [] } = token
const chunks = backlashes.split('')
const len = chunks.length
const result = []
let i
for (i = 0; i < len; i++) {
const chunk = chunks[i]
const light = highlights.filter(light => union({ start: start + i, end: start + i + 1 }, light))
let selector = 'span'
if (light.length) {
const className = this.getHighlightClassName(light[0].active)
selector += `.${className}`
}
if (isEven(i)) {
result.push(
h(`${selector}.${outerClass}`, chunk)
)
} else {
result.push(
h(`${selector}.${CLASS_OR_ID.AG_BACKLASH}`, chunk)
)
}
}
return result
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/autoLinkExtension.js | src/muya/lib/parser/render/renderInlines/autoLinkExtension.js | import { CLASS_OR_ID } from '../../../config'
import { sanitizeHyperlink } from '../../../utils/url'
// render auto_link to vdom
export default function autoLinkExtension (h, cursor, block, token, outerClass) {
const { linkType, www, url, email } = token
const { start, end } = token.range
const content = this.highlight(h, block, start, end, token)
const hyperlink = linkType === 'www' ? encodeURI(`http://${www}`) : (linkType === 'url' ? encodeURI(url) : `mailto:${email}`)
return [
h(`a.${CLASS_OR_ID.AG_INLINE_RULE}.${CLASS_OR_ID.AG_AUTO_LINK_EXTENSION}`, {
attrs: {
spellcheck: 'false'
},
props: {
href: sanitizeHyperlink(hyperlink),
target: '_blank'
}
}, content)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/delEmStringFactory.js | src/muya/lib/parser/render/renderInlines/delEmStringFactory.js | import { CLASS_OR_ID } from '../../../config'
import { snakeToCamel } from '../../../utils'
// render factory of `del`,`em`,`strong`
export default function delEmStrongFac (type, h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const COMMON_MARKER = `span.${className}.${CLASS_OR_ID.AG_REMOVE}`
const { marker } = token
const { start, end } = token.range
const backlashStart = end - marker.length - token.backlash.length
const content = [
...token.children.reduce((acc, to) => {
const chunk = this[snakeToCamel(to.type)](h, cursor, block, to, className)
return Array.isArray(chunk) ? [...acc, ...chunk] : [...acc, chunk]
}, []),
...this.backlashInToken(h, token.backlash, className, backlashStart, token)
]
const startMarker = this.highlight(h, block, start, start + marker.length, token)
const endMarker = this.highlight(h, block, end - marker.length, end, token)
return [
h(COMMON_MARKER, startMarker),
h(`${type}.${CLASS_OR_ID.AG_INLINE_RULE}`, content),
h(COMMON_MARKER, endMarker)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/del.js | src/muya/lib/parser/render/renderInlines/del.js | export default function del (h, cursor, block, token, outerClass) {
return this.delEmStrongFac('del', h, cursor, block, token, outerClass)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/referenceLink.js | src/muya/lib/parser/render/renderInlines/referenceLink.js | import { CLASS_OR_ID } from '../../../config'
import { snakeToCamel } from '../../../utils'
import { sanitizeHyperlink } from '../../../utils/url'
export default function referenceLink (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const labelClass = className === CLASS_OR_ID.AG_GRAY
? CLASS_OR_ID.AG_REFERENCE_LABEL
: className
const { start, end } = token.range
const {
anchor,
children,
backlash,
isFullLink,
label
} = token
const MARKER = '['
const key = (label + backlash.second).toLowerCase()
const backlashStart = start + MARKER.length + anchor.length
const content = [
...children.reduce((acc, to) => {
const chunk = this[snakeToCamel(to.type)](h, cursor, block, to, className)
return Array.isArray(chunk) ? [...acc, ...chunk] : [...acc, chunk]
}, []),
...this.backlashInToken(h, backlash.first, className, backlashStart, token)
]
const { href, title } = this.labels.get(key)
const startMarker = this.highlight(
h,
block,
start,
start + MARKER.length,
token
)
const endMarker = this.highlight(
h,
block,
start + MARKER.length + anchor.length + backlash.first.length,
end,
token
)
const anchorSelector = href ? `a.${CLASS_OR_ID.AG_INLINE_RULE}.${CLASS_OR_ID.AG_REFERENCE_LINK}` : `span.${CLASS_OR_ID.AG_REFERENCE_LINK}`
const data = {
attrs: {
spellcheck: 'false'
},
props: {
title
},
dataset: {
start,
end,
raw: token.raw
}
}
if (href) {
Object.assign(data.props, { href: sanitizeHyperlink(href) })
}
if (isFullLink) {
const labelContent = this.highlight(
h,
block,
start + 3 * MARKER.length + anchor.length + backlash.first.length,
end - MARKER.length - backlash.second.length,
token
)
const middleMarker = this.highlight(
h,
block,
start + MARKER.length + anchor.length + backlash.first.length,
start + 3 * MARKER.length + anchor.length + backlash.first.length,
token
)
const lastMarker = this.highlight(
h,
block,
end - MARKER.length,
end,
token
)
const secondBacklashStart = end - MARKER.length - backlash.second.length
return [
h(`span.${className}`, startMarker),
h(anchorSelector, data, content),
h(`span.${className}`, middleMarker),
h(`span.${labelClass}`, labelContent),
...this.backlashInToken(h, backlash.second, className, secondBacklashStart, token),
h(`span.${className}`, lastMarker)
]
} else {
return [
h(`span.${className}`, startMarker),
h(anchorSelector, data, content),
h(`span.${className}`, endMarker)
]
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/referenceDefinition.js | src/muya/lib/parser/render/renderInlines/referenceDefinition.js | import { CLASS_OR_ID } from '../../../config'
export default function referenceDefinition (h, cursor, block, token, outerClass) {
const className = CLASS_OR_ID.AG_REFERENCE_MARKER
const {
leftBracket,
label,
backlash,
// rightBracket,
// leftHrefMarker,
// href,
// rightHrefMarker,
titleMarker,
title,
rightTitleSpace
} = token
const { start, end } = token.range
const leftBracketContent = this.highlight(h, block, start, start + leftBracket.length, token)
const labelContent = this.highlight(h, block, start + leftBracket.length, start + leftBracket.length + label.length, token)
const middleContent = this.highlight(
h,
block,
start + leftBracket.length + label.length + backlash.length,
end - rightTitleSpace.length - titleMarker.length - title.length,
token
)
const titleContent = this.highlight(
h,
block,
end - rightTitleSpace.length - titleMarker.length - title.length,
end - titleMarker.length - rightTitleSpace.length,
token
)
const rightContent = this.highlight(
h,
block,
end - titleMarker.length - rightTitleSpace.length,
end,
token
)
const backlashStart = start + leftBracket.length + label.length
return [
h(`span.${className}`, leftBracketContent),
h(`span.${CLASS_OR_ID.AG_REFERENCE_LABEL}`, {
attrs: {
spellcheck: 'false'
}
}, labelContent),
...this.backlashInToken(h, backlash, CLASS_OR_ID.AG_GRAY, backlashStart, token),
h(`span.${className}`, {
attrs: {
spellcheck: 'false'
}
}, middleContent),
h(`span.${CLASS_OR_ID.AG_REFERENCE_TITLE}`, titleContent),
h(`span.${className}`, {
attrs: {
spellcheck: 'false'
}
}, rightContent)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/htmlEscape.js | src/muya/lib/parser/render/renderInlines/htmlEscape.js | import { CLASS_OR_ID } from '../../../config'
import escapeCharactersMap from '../../escapeCharacter'
export default function htmlEscape (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const { escapeCharacter } = token
const { start, end } = token.range
const content = this.highlight(h, block, start, end, token)
return [
h(`span.${className}.${CLASS_OR_ID.AG_HTML_ESCAPE}`, {
dataset: {
character: escapeCharactersMap[escapeCharacter]
}
}, content)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/index.js | src/muya/lib/parser/render/renderInlines/index.js | import backlashInToken from './backlashInToken'
import backlash from './backlash'
import highlight from './highlight'
import header from './header'
import link from './link'
import htmlTag from './htmlTag'
import hr from './hr'
import tailHeader from './tailHeader'
import hardLineBreak from './hardLineBreak'
import softLineBreak from './softLineBreak'
import codeFense from './codeFense'
import inlineMath from './inlineMath'
import autoLink from './autoLink'
import autoLinkExtension from './autoLinkExtension'
import loadImageAsync from './loadImageAsync'
import image from './image'
import delEmStrongFac from './delEmStringFactory'
import emoji from './emoji'
import inlineCode from './inlineCode'
import text from './text'
import del from './del'
import em from './em'
import strong from './strong'
import htmlEscape from './htmlEscape'
import multipleMath from './multipleMath'
import referenceDefinition from './referenceDefinition'
import htmlRuby from './htmlRuby'
import referenceLink from './referenceLink'
import referenceImage from './referenceImage'
import superSubScript from './superSubScript'
import footnoteIdentifier from './footnoteIdentifier'
export default {
backlashInToken,
backlash,
highlight,
header,
link,
htmlTag,
hr,
tailHeader,
hardLineBreak,
softLineBreak,
codeFense,
inlineMath,
autoLink,
autoLinkExtension,
loadImageAsync,
image,
delEmStrongFac,
emoji,
inlineCode,
text,
del,
em,
strong,
htmlEscape,
multipleMath,
referenceDefinition,
htmlRuby,
referenceLink,
referenceImage,
superSubScript,
footnoteIdentifier
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/inlineCode.js | src/muya/lib/parser/render/renderInlines/inlineCode.js | import { CLASS_OR_ID } from '../../../config'
export default function inlineCode (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const { marker } = token
const { start, end } = token.range
const startMarker = this.highlight(h, block, start, start + marker.length, token)
const endMarker = this.highlight(h, block, end - marker.length, end, token)
const content = this.highlight(h, block, start + marker.length, end - marker.length, token)
return [
h(`span.${className}.${CLASS_OR_ID.AG_REMOVE}`, startMarker),
h(`code.${CLASS_OR_ID.AG_INLINE_RULE}`, {
attrs: {
spellcheck: 'false'
}
}, content),
h(`span.${className}.${CLASS_OR_ID.AG_REMOVE}`, endMarker)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/footnoteIdentifier.js | src/muya/lib/parser/render/renderInlines/footnoteIdentifier.js | import { CLASS_OR_ID } from '../../../config'
export default function footnoteIdentifier (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const { marker } = token
const { start, end } = token.range
const startMarker = this.highlight(h, block, start, start + marker.length, token)
const endMarker = this.highlight(h, block, end - 1, end, token)
const content = this.highlight(h, block, start + marker.length, end - 1, token)
return [
h(`sup#noteref-${token.content}.${CLASS_OR_ID.AG_INLINE_FOOTNOTE_IDENTIFIER}.${CLASS_OR_ID.AG_INLINE_RULE}`, [
h(`span.${className}.${CLASS_OR_ID.AG_REMOVE}`, startMarker),
h('a', {
attrs: {
spellcheck: 'false'
}
}, content),
h(`span.${className}.${CLASS_OR_ID.AG_REMOVE}`, endMarker)
])
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/inlineMath.js | src/muya/lib/parser/render/renderInlines/inlineMath.js | import katex from 'katex'
import 'katex/dist/contrib/mhchem.min.js'
import { CLASS_OR_ID } from '../../../config'
import { htmlToVNode } from '../snabbdom'
import 'katex/dist/katex.min.css'
export default function displayMath (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const mathSelector = className === CLASS_OR_ID.AG_HIDE
? `span.${className}.${CLASS_OR_ID.AG_MATH}`
: `span.${CLASS_OR_ID.AG_MATH}`
const { start, end } = token.range
const { marker } = token
const startMarker = this.highlight(h, block, start, start + marker.length, token)
const endMarker = this.highlight(h, block, end - marker.length, end, token)
const content = this.highlight(h, block, start + marker.length, end - marker.length, token)
const { content: math, type } = token
const { loadMathMap } = this
const displayMode = false
const key = `${math}_${type}`
let mathVnode = null
let previewSelector = `span.${CLASS_OR_ID.AG_MATH_RENDER}`
if (loadMathMap.has(key)) {
mathVnode = loadMathMap.get(key)
} else {
try {
const html = katex.renderToString(math, {
displayMode
})
mathVnode = htmlToVNode(html)
loadMathMap.set(key, mathVnode)
} catch (err) {
mathVnode = '< Invalid Mathematical Formula >'
previewSelector += `.${CLASS_OR_ID.AG_MATH_ERROR}`
}
}
return [
h(`span.${className}.${CLASS_OR_ID.AG_MATH_MARKER}`, startMarker),
h(mathSelector, [
h(`span.${CLASS_OR_ID.AG_INLINE_RULE}.${CLASS_OR_ID.AG_MATH_TEXT}`, {
attrs: { spellcheck: 'false' }
}, content),
h(previewSelector, {
attrs: { contenteditable: 'false' }
}, mathVnode)
]),
h(`span.${className}.${CLASS_OR_ID.AG_MATH_MARKER}`, endMarker)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/link.js | src/muya/lib/parser/render/renderInlines/link.js | import { CLASS_OR_ID } from '../../../config'
import { isLengthEven, snakeToCamel } from '../../../utils'
import { sanitizeHyperlink } from '../../../utils/url'
// 'link': /^(\[)((?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*?)(\\*)\]\((.*?)(\\*)\)/, // can nest
export default function link (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const linkClassName = className === CLASS_OR_ID.AG_HIDE ? className : CLASS_OR_ID.AG_LINK_IN_BRACKET
const { start, end } = token.range
const firstMiddleBracket = this.highlight(h, block, start, start + 3, token)
const firstBracket = this.highlight(h, block, start, start + 1, token)
const middleBracket = this.highlight(
h, block,
start + 1 + token.anchor.length + token.backlash.first.length,
start + 1 + token.anchor.length + token.backlash.first.length + 2,
token
)
const hrefContent = this.highlight(
h, block,
start + 1 + token.anchor.length + token.backlash.first.length + 2,
start + 1 + token.anchor.length + token.backlash.first.length + 2 + token.hrefAndTitle.length,
token
)
const middleHref = this.highlight(
h, block, start + 1 + token.anchor.length + token.backlash.first.length,
block, start + 1 + token.anchor.length + token.backlash.first.length + 2 + token.hrefAndTitle.length,
token
)
const lastBracket = this.highlight(h, block, end - 1, end, token)
const firstBacklashStart = start + 1 + token.anchor.length
const secondBacklashStart = end - 1 - token.backlash.second.length
if (isLengthEven(token.backlash.first) && isLengthEven(token.backlash.second)) {
if (!token.children.length && !token.backlash.first) { // no-text-link
return [
h(`span.${CLASS_OR_ID.AG_GRAY}.${CLASS_OR_ID.AG_REMOVE}`, firstMiddleBracket),
h(`a.${CLASS_OR_ID.AG_NOTEXT_LINK}.${CLASS_OR_ID.AG_INLINE_RULE}`, {
props: {
href: sanitizeHyperlink(token.href + encodeURI(token.backlash.second)),
target: '_blank',
title: token.title
}
}, [
...hrefContent,
...this.backlashInToken(h, token.backlash.second, className, secondBacklashStart, token)
]),
h(`span.${CLASS_OR_ID.AG_GRAY}.${CLASS_OR_ID.AG_REMOVE}`, lastBracket)
]
} else { // has children
return [
h(`span.${className}.${CLASS_OR_ID.AG_REMOVE}`, firstBracket),
h(`a.${CLASS_OR_ID.AG_INLINE_RULE}`, {
props: {
href: sanitizeHyperlink(token.href + encodeURI(token.backlash.second)),
target: '_blank',
title: token.title
},
dataset: {
start,
end,
raw: token.raw
}
}, [
...token.children.reduce((acc, to) => {
const chunk = this[snakeToCamel(to.type)](h, cursor, block, to, className)
return Array.isArray(chunk) ? [...acc, ...chunk] : [...acc, chunk]
}, []),
...this.backlashInToken(h, token.backlash.first, className, firstBacklashStart, token)
]),
h(`span.${className}.${CLASS_OR_ID.AG_REMOVE}`, middleBracket),
h(`span.${linkClassName}.${CLASS_OR_ID.AG_REMOVE}`, {
attrs: { spellcheck: 'false' }
}, [
...hrefContent,
...this.backlashInToken(h, token.backlash.second, className, secondBacklashStart, token)
]),
h(`span.${className}.${CLASS_OR_ID.AG_REMOVE}`, lastBracket)
]
}
} else {
return [
...firstBracket,
...token.children.reduce((acc, to) => {
const chunk = this[snakeToCamel(to.type)](h, cursor, block, to, className)
return Array.isArray(chunk) ? [...acc, ...chunk] : [...acc, chunk]
}, []),
...this.backlashInToken(h, token.backlash.first, className, firstBacklashStart, token),
...middleHref,
...this.backlashInToken(h, token.backlash.second, className, secondBacklashStart, token),
...lastBracket
]
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/hr.js | src/muya/lib/parser/render/renderInlines/hr.js | import { CLASS_OR_ID } from '../../../config'
export default function hr (h, cursor, block, token, outerClass) {
const { start, end } = token.range
const content = this.highlight(h, block, start, end, token)
return [
h(`span.${CLASS_OR_ID.AG_GRAY}.${CLASS_OR_ID.AG_REMOVE}`, content)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/softLineBreak.js | src/muya/lib/parser/render/renderInlines/softLineBreak.js | import { CLASS_OR_ID } from '../../../config'
export default function hardLineBreak (h, cursor, block, token, outerClass) {
const { lineBreak, isAtEnd } = token
let selector = `span.${CLASS_OR_ID.AG_SOFT_LINE_BREAK}`
if (isAtEnd) {
selector += `.${CLASS_OR_ID.AG_LINE_END}`
}
return [
h(selector, lineBreak)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/tailHeader.js | src/muya/lib/parser/render/renderInlines/tailHeader.js | export default function tailHeader (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const { start, end } = token.range
const content = this.highlight(h, block, start, end, token)
if (/^h\d$/.test(block.type)) {
return [
h(`span.${className}`, content)
]
} else {
return content
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/multipleMath.js | src/muya/lib/parser/render/renderInlines/multipleMath.js | import { CLASS_OR_ID } from '../../../config'
export default function multipleMath (h, cursor, block, token, outerClass) {
const { start, end } = token.range
const content = this.highlight(h, block, start, end, token)
return [
h(`span.${CLASS_OR_ID.AG_GRAY}.${CLASS_OR_ID.AG_REMOVE}`, content)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/codeFense.js | src/muya/lib/parser/render/renderInlines/codeFense.js | import { CLASS_OR_ID } from '../../../config'
export default function codeFense (h, cursor, block, token, outerClass) {
const { start, end } = token.range
const { marker } = token
const markerContent = this.highlight(h, block, start, start + marker.length, token)
const content = this.highlight(h, block, start + marker.length, end, token)
return [
h(`span.${CLASS_OR_ID.AG_GRAY}`, markerContent),
h(`span.${CLASS_OR_ID.AG_LANGUAGE}`, {
attrs: {
spellcheck: 'false'
}
}, content)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/loadImageAsync.js | src/muya/lib/parser/render/renderInlines/loadImageAsync.js | import { getUniqueId, loadImage } from '../../../utils'
import { insertAfter, operateClassName } from '../../../utils/domManipulate'
import { CLASS_OR_ID } from '../../../config'
export default function loadImageAsync (imageInfo, attrs, className, imageClass) {
const { src, isUnknownType } = imageInfo
let id
let isSuccess
let w
let h
let domsrc
let reload = false
if (this.loadImageMap.has(src)) {
const imageInfo = this.loadImageMap.get(src)
if (imageInfo.dispMsec !== imageInfo.touchMsec) {
// We have a cached image, but force it to load.
reload = true
}
} else {
reload = true
}
if (reload) {
id = getUniqueId()
loadImage(src, isUnknownType)
.then(({ url, width, height }) => {
const imageText = document.querySelector(`#${id}`)
const img = document.createElement('img')
let dispMsec = Date.now()
let touchMsec = dispMsec
if (/^file:\/\//.test(src)) {
domsrc = url + '?msec=' + dispMsec
} else {
domsrc = url
}
img.src = domsrc
if (attrs.alt) img.alt = attrs.alt.replace(/[`*{}[\]()#+\-.!_>~:|<>$]/g, '')
if (attrs.title) img.setAttribute('title', attrs.title)
if (attrs.width && typeof attrs.width === 'number') {
img.setAttribute('width', attrs.width)
}
if (attrs.height && typeof attrs.height === 'number') {
img.setAttribute('height', attrs.height)
}
if (imageClass) {
img.classList.add(imageClass)
}
if (imageText) {
if (imageText.classList.contains('ag-inline-image')) {
const imageContainer = imageText.querySelector('.ag-image-container')
const oldImage = imageContainer.querySelector('img')
if (oldImage) {
oldImage.remove()
}
imageContainer.appendChild(img)
imageText.classList.remove('ag-image-loading')
imageText.classList.add('ag-image-success')
} else {
insertAfter(img, imageText)
operateClassName(imageText, 'add', className)
}
}
if (this.urlMap.has(src)) {
this.urlMap.delete(src)
}
this.loadImageMap.set(src, {
id,
isSuccess: true,
width,
height,
dispMsec,
touchMsec,
domsrc
})
})
.catch(() => {
const imageText = document.querySelector(`#${id}`)
if (imageText) {
operateClassName(imageText, 'remove', CLASS_OR_ID.AG_IMAGE_LOADING)
operateClassName(imageText, 'add', CLASS_OR_ID.AG_IMAGE_FAIL)
const image = imageText.querySelector('img')
if (image) {
image.remove()
}
}
if (this.urlMap.has(src)) {
this.urlMap.delete(src)
}
this.loadImageMap.set(src, {
id,
isSuccess: false
})
})
} else {
const imageInfo = this.loadImageMap.get(src)
id = imageInfo.id
isSuccess = imageInfo.isSuccess
w = imageInfo.width
h = imageInfo.height
domsrc = imageInfo.domsrc
}
return { id, isSuccess, domsrc, width: w, height: h }
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/highlight.js | src/muya/lib/parser/render/renderInlines/highlight.js | import { union } from '../../../utils'
// change text to highlight vdom
export default function highlight (h, block, rStart, rEnd, token) {
const { text } = block
const { highlights } = token
let result = []
const unions = []
let pos = rStart
if (highlights) {
for (const light of highlights) {
const un = union({ start: rStart, end: rEnd }, light)
if (un) unions.push(un)
}
}
if (unions.length) {
for (const u of unions) {
const { start, end, active } = u
const className = this.getHighlightClassName(active)
if (pos < start) {
result.push(text.substring(pos, start))
}
result.push(h(`span.${className}`, text.substring(start, end)))
pos = end
}
if (pos < rEnd) {
result.push(block.text.substring(pos, rEnd))
}
} else {
result = [text.substring(rStart, rEnd)]
}
return result
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/autoLink.js | src/muya/lib/parser/render/renderInlines/autoLink.js | import { CLASS_OR_ID } from '../../../config'
import { sanitizeHyperlink } from '../../../utils/url'
// render auto_link to vdom
export default function autoLink (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const { isLink, marker, href, email } = token
const { start, end } = token.range
const startMarker = this.highlight(h, block, start, start + marker.length, token)
const endMarker = this.highlight(h, block, end - marker.length, end, token)
const content = this.highlight(h, block, start + marker.length, end - marker.length, token)
const hyperlink = isLink ? encodeURI(href) : `mailto:${email}`
return [
h(`span.${className}`, startMarker),
h(`a.${CLASS_OR_ID.AG_INLINE_RULE}.${CLASS_OR_ID.AG_AUTO_LINK}`, {
attrs: {
spellcheck: 'false'
},
props: {
href: sanitizeHyperlink(hyperlink),
target: '_blank'
}
}, content),
h(`span.${className}`, endMarker)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/superSubScript.js | src/muya/lib/parser/render/renderInlines/superSubScript.js | import { CLASS_OR_ID } from '../../../config'
export default function superSubScript (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const { marker } = token
const { start, end } = token.range
const startMarker = this.highlight(h, block, start, start + marker.length, token)
const endMarker = this.highlight(h, block, end - marker.length, end, token)
const content = this.highlight(h, block, start + marker.length, end - marker.length, token)
const tagName = marker === '^' ? 'sup' : 'sub'
return [
h(`span.${className}.${CLASS_OR_ID.AG_REMOVE}`, startMarker),
h(`${tagName}.${CLASS_OR_ID.AG_INLINE_RULE}`, {
attrs: {
spellcheck: 'false'
}
}, content),
h(`span.${className}.${CLASS_OR_ID.AG_REMOVE}`, endMarker)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/backlash.js | src/muya/lib/parser/render/renderInlines/backlash.js | import { CLASS_OR_ID } from '../../../config'
export default function backlash (h, cursor, block, token, outerClass) {
const className = this.getClassName(outerClass, block, token, cursor)
const { start, end } = token.range
const content = this.highlight(h, block, start, end, token)
return [
h(`span.${className}.${CLASS_OR_ID.AG_REMOVE}`, content)
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/image.js | src/muya/lib/parser/render/renderInlines/image.js | import { CLASS_OR_ID } from '../../../config'
import { getImageInfo } from '../../../utils'
import ImageIcon from '../../../assets/pngicon/image/2.png'
import ImageFailIcon from '../../../assets/pngicon/image_fail/2.png'
import DeleteIcon from '../../../assets/pngicon/delete/2.png'
const renderIcon = (h, className, icon) => {
const selector = `a.${className}`
const iconVnode = h('i.icon', h('i.icon-inner', {
style: {
background: `url(${icon}) no-repeat`,
'background-size': '100%'
}
}, ''))
return h(selector, {
attrs: {
contenteditable: 'false'
}
}, iconVnode)
}
// I dont want operate dom directly, is there any better method? need help!
export default function image (h, cursor, block, token, outerClass) {
const imageInfo = getImageInfo(token.attrs.src)
const { selectedImage } = this.muya.contentState
const data = {
dataset: {
raw: token.raw
}
}
let id
let isSuccess
let domsrc
let { src } = imageInfo
const alt = token.attrs.alt
const title = token.attrs.title
const width = token.attrs.width
const height = token.attrs.height
if (src) {
({ id, isSuccess, domsrc } = this.loadImageAsync(imageInfo, token.attrs))
}
let wrapperSelector = id
? `span#${isSuccess ? block.key + '_' + id + '_' + token.range.start : id}.${CLASS_OR_ID.AG_INLINE_IMAGE}`
: `span.${CLASS_OR_ID.AG_INLINE_IMAGE}`
const imageIcons = [
renderIcon(h, 'ag-image-icon-success', ImageIcon),
renderIcon(h, 'ag-image-icon-fail', ImageFailIcon),
renderIcon(h, 'ag-image-icon-close', DeleteIcon)
]
const renderImageContainer = (...args) => {
const data = {}
if (title) {
Object.assign(data, {
dataset: { title }
})
}
return h(`span.${CLASS_OR_ID.AG_IMAGE_CONTAINER}`, data, args)
}
if (typeof token.attrs['data-align'] === 'string') {
wrapperSelector += `.${token.attrs['data-align']}`
}
// the src image is still loading, so use the url Map base64.
if (this.urlMap.has(src)) {
// fix: it will generate a new id if the image is not loaded.
const { selectedImage } = this.muya.contentState
if (selectedImage && selectedImage.token.attrs.src === src && selectedImage.imageId !== id) {
selectedImage.imageId = id
}
src = this.urlMap.get(src)
isSuccess = true
}
if (alt.startsWith('loading-')) {
wrapperSelector += `.${CLASS_OR_ID.AG_IMAGE_UPLOADING}`
Object.assign(data.dataset, {
id: alt
})
if (this.urlMap.has(alt)) {
src = this.urlMap.get(alt)
isSuccess = true
}
}
if (src) {
// image is loading...
if (typeof isSuccess === 'undefined') {
wrapperSelector += `.${CLASS_OR_ID.AG_IMAGE_LOADING}`
} else if (isSuccess === true) {
wrapperSelector += `.${CLASS_OR_ID.AG_IMAGE_SUCCESS}`
} else {
wrapperSelector += `.${CLASS_OR_ID.AG_IMAGE_FAIL}`
}
// Add image selected class name.
if (selectedImage) {
const { key, token: selectToken } = selectedImage
if (
key === block.key &&
selectToken.range.start === token.range.start &&
selectToken.range.end === token.range.end
) {
wrapperSelector += `.${CLASS_OR_ID.AG_INLINE_IMAGE_SELECTED}`
}
}
const renderImage = () => {
const data = {
props: { alt: alt.replace(/[`*{}[\]()#+\-.!_>~:|<>$]/g, ''), src: domsrc, title }
}
if (typeof width === 'number') {
Object.assign(data.props, { width })
}
if (typeof height === 'number') {
Object.assign(data.props, { height })
}
return h('img', data)
}
return isSuccess
? [
h(wrapperSelector, data, [
...imageIcons,
renderImageContainer(
// An image description has inline elements as its contents.
// When an image is rendered to HTML, this is standardly used as the image’s alt attribute.
renderImage()
)
])
]
: [
h(wrapperSelector, data, [
...imageIcons,
renderImageContainer()
])
]
} else {
wrapperSelector += `.${CLASS_OR_ID.AG_EMPTY_IMAGE}`
return [
h(wrapperSelector, data, [
...imageIcons,
renderImageContainer()
])
]
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/htmlTag.js | src/muya/lib/parser/render/renderInlines/htmlTag.js | import { CLASS_OR_ID, BLOCK_TYPE6 } from '../../../config'
import { snakeToCamel } from '../../../utils'
import sanitize, { isValidAttribute } from '../../../utils/dompurify'
export default function htmlTag (h, cursor, block, token, outerClass) {
const { tag, openTag, closeTag, children, attrs } = token
const className = children ? this.getClassName(outerClass, block, token, cursor) : CLASS_OR_ID.AG_GRAY
const tagClassName = className === CLASS_OR_ID.AG_HIDE ? className : CLASS_OR_ID.AG_HTML_TAG
const { start, end } = token.range
const openContent = this.highlight(h, block, start, start + openTag.length, token)
const closeContent = closeTag
? this.highlight(h, block, end - closeTag.length, end, token)
: ''
const anchor = Array.isArray(children) && tag !== 'ruby' // important
? children.reduce((acc, to) => {
const chunk = this[snakeToCamel(to.type)](h, cursor, block, to, className)
return Array.isArray(chunk) ? [...acc, ...chunk] : [...acc, chunk]
}, [])
: ''
switch (tag) {
// Handle html img.
case 'img': {
return this.image(h, cursor, block, token, outerClass)
}
case 'br': {
return [h(`span.${CLASS_OR_ID.AG_HTML_TAG}`, [...openContent, h(tag)])]
}
default:
// handle void html tag
if (!closeTag) {
return [h(`span.${CLASS_OR_ID.AG_HTML_TAG}`, openContent)]
} else if (tag === 'ruby') {
return this.htmlRuby(h, cursor, block, token, outerClass)
} else {
// if tag is a block level element, use a inline element `span` to instead.
// Because we can not nest a block level element in span element(line is span element)
// we also recommand user not use block level element in paragraph. use block element in html block.
// Use code !sanitize(`<${tag}>`) to filter some malicious tags. for example: <embed>.
let selector = BLOCK_TYPE6.includes(tag) || !sanitize(`<${tag}>`) ? 'span' : tag
selector += `.${CLASS_OR_ID.AG_INLINE_RULE}.${CLASS_OR_ID.AG_RAW_HTML}`
const data = {
attrs: {},
dataset: {
start,
end,
raw: token.raw
}
}
// Disable spell checking for these tags
if (tag === 'code' || tag === 'kbd') {
Object.assign(data.attrs, { spellcheck: 'false' })
}
if (attrs.id) {
selector += `#${attrs.id}`
}
if (attrs.class && /\S/.test(attrs.class)) {
const classNames = attrs.class.split(/\s+/)
for (const className of classNames) {
selector += `.${className}`
}
}
for (const attr of Object.keys(attrs)) {
if (attr !== 'id' && attr !== 'class') {
const attrData = attrs[attr]
if (isValidAttribute(tag, attr, attrData)) {
data.attrs[attr] = attrData
}
}
}
return [
h(`span.${tagClassName}.${CLASS_OR_ID.AG_OUTPUT_REMOVE}`, {
attrs: {
spellcheck: 'false'
}
}, openContent),
h(`${selector}`, data, anchor),
h(`span.${tagClassName}.${CLASS_OR_ID.AG_OUTPUT_REMOVE}`, {
attrs: {
spellcheck: 'false'
}
}, closeContent)
]
}
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/strong.js | src/muya/lib/parser/render/renderInlines/strong.js | export default function strong (h, cursor, block, token, outerClass) {
return this.delEmStrongFac('strong', h, cursor, block, token, outerClass)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderInlines/text.js | src/muya/lib/parser/render/renderInlines/text.js | // render token of text type to vdom.
export default function text (h, cursor, block, token) {
const { start, end } = token.range
return [
h('span.ag-plain-text', this.highlight(h, block, start, end, token))
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderBlock/renderLineNumber.js | src/muya/lib/parser/render/renderBlock/renderLineNumber.js | import { h } from '../snabbdom'
const NEW_LINE_EXP = /\n(?!$)/g
const renderLineNumberRows = codeContent => {
const { text } = codeContent
const match = text.match(NEW_LINE_EXP)
let linesNum = match ? match.length + 1 : 1
if (text.endsWith('\n')) {
linesNum++
}
const data = {
attrs: {
'aria-hidden': true
}
}
const children = [...new Array(linesNum)].map(() => h('span'))
return h('span.line-numbers-rows', data, children)
}
export default renderLineNumberRows
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderBlock/renderCopyButton.js | src/muya/lib/parser/render/renderBlock/renderCopyButton.js | import { h } from '../snabbdom'
import copyIcon from '../../../assets/pngicon/copy/2.png'
const renderCopyButton = () => {
const selector = 'a.ag-code-copy'
const iconVnode = h('i.icon', h('i.icon-inner', {
style: {
background: `url(${copyIcon}) no-repeat`,
'background-size': '100%'
}
}, ''))
return h(selector, {
attrs: {
title: 'Copy content',
contenteditable: 'false'
}
}, iconVnode)
}
export default renderCopyButton
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderBlock/index.js | src/muya/lib/parser/render/renderBlock/index.js | import renderBlock from './renderBlock'
import renderLeafBlock from './renderLeafBlock'
import renderContainerBlock from './renderContainerBlock'
import renderIcon from './renderIcon'
export default {
renderBlock,
renderLeafBlock,
renderContainerBlock,
renderIcon
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderBlock/renderContainerBlock.js | src/muya/lib/parser/render/renderBlock/renderContainerBlock.js | import { CLASS_OR_ID } from '../../../config'
import { renderTableTools } from './renderToolBar'
import { footnoteJumpIcon } from './renderFootnoteJump'
import { renderEditIcon } from './renderContainerEditIcon'
// import renderLineNumberRows from './renderLineNumber'
import renderCopyButton from './renderCopyButton'
import { renderLeftBar, renderBottomBar } from './renderTableDargBar'
import { h } from '../snabbdom'
const PRE_BLOCK_HASH = {
fencecode: `.${CLASS_OR_ID.AG_FENCE_CODE}`,
indentcode: `.${CLASS_OR_ID.AG_INDENT_CODE}`,
html: `.${CLASS_OR_ID.AG_HTML_BLOCK}`,
frontmatter: `.${CLASS_OR_ID.AG_FRONT_MATTER}`,
multiplemath: `.${CLASS_OR_ID.AG_MULTIPLE_MATH}`,
flowchart: `.${CLASS_OR_ID.AG_FLOWCHART}`,
sequence: `.${CLASS_OR_ID.AG_SEQUENCE}`,
plantuml: `.${CLASS_OR_ID.AG_PLANTUML}`,
mermaid: `.${CLASS_OR_ID.AG_MERMAID}`,
'vega-lite': `.${CLASS_OR_ID.AG_VEGA_LITE}`
}
export default function renderContainerBlock (parent, block, activeBlocks, matches, useCache = false) {
let selector = this.getSelector(block, activeBlocks)
const {
key,
align,
type,
headingStyle,
editable,
functionType,
listType,
listItemType,
bulletMarkerOrDelimiter,
isLooseListItem,
lang,
column
} = block
if (type === 'table') {
this.renderingTable = block
} else if (/thead|tbody/.test(type)) {
this.renderingRowContainer = block
}
const children = block.children.map(child => this.renderBlock(block, child, activeBlocks, matches, useCache))
const data = {
attrs: {},
dataset: {}
}
if (editable === false) {
Object.assign(data.attrs, {
contenteditable: 'false',
spellcheck: 'false'
})
}
if (/code|pre/.test(type)) {
if (typeof lang === 'string' && !!lang) {
selector += `.language-${lang.replace(/[#.]{1}/g, '')}`
}
if (type === 'pre') {
children.unshift(renderCopyButton())
}
// FIXME: Disabled due to #1648 - be consistent.
// if (this.muya.options.codeBlockLineNumbers) {
// if (type === 'pre') {
// selector += '.line-numbers'
// } else {
// children.unshift(renderLineNumberRows(block.children[0]))
// }
// }
Object.assign(data.attrs, { spellcheck: 'false' })
}
if (/^(?:th|td)$/.test(type)) {
const { cells } = this.muya.contentState.selectedTableCells || {}
if (align) {
Object.assign(data.attrs, {
style: `text-align:${align}`
})
}
if (typeof column === 'number') {
Object.assign(data.dataset, {
column
})
}
if (cells && cells.length) {
const cell = cells.find(c => c.key === key)
if (cell) {
const { top, right, bottom, left } = cell
selector += '.ag-cell-selected'
if (top) {
selector += '.ag-cell-border-top'
}
if (right) {
selector += '.ag-cell-border-right'
}
if (bottom) {
selector += '.ag-cell-border-bottom'
}
if (left) {
selector += '.ag-cell-border-left'
}
}
} else {
// Judge whether to render the table drag bar.
const { renderingTable, renderingRowContainer } = this
const findTable = renderingTable ? activeBlocks.find(b => b.key === renderingTable.key) : null
if (findTable && renderingRowContainer) {
const { row: tableRow, column: tableColumn } = findTable
const isLastRow = () => {
if (renderingRowContainer.type === 'thead') {
return tableRow === 0
} else {
return !parent.nextSibling
}
}
if (block.parent === activeBlocks[1].parent && !block.preSibling && tableRow > 0) {
children.unshift(renderLeftBar())
}
if (column === activeBlocks[1].column && isLastRow() && tableColumn > 0) {
children.push(renderBottomBar())
}
}
}
} else if (/^h/.test(type)) {
if (/^h\d$/.test(type)) {
// TODO: This should be the best place to create and update the TOC.
// Cache `block.key` and title and update only if necessary.
Object.assign(data.dataset, {
head: type
})
selector += `.${headingStyle}`
}
Object.assign(data.dataset, {
role: type
})
} else if (type === 'figure') {
if (functionType) {
Object.assign(data.dataset, { role: functionType.toUpperCase() })
if (functionType === 'table' && activeBlocks[0] && activeBlocks[0].functionType === 'cellContent') {
children.unshift(renderTableTools(activeBlocks))
} else if (functionType !== 'footnote') {
children.unshift(renderEditIcon())
} else {
children.push(footnoteJumpIcon())
}
}
if (
/html|multiplemath|flowchart|mermaid|sequence|plantuml|vega-lite/.test(functionType)
) {
selector += `.${CLASS_OR_ID.AG_CONTAINER_BLOCK}`
Object.assign(data.attrs, { spellcheck: 'false' })
}
} else if (/ul|ol/.test(type) && listType) {
selector += `.ag-${listType}-list`
if (type === 'ol') {
Object.assign(data.attrs, { start: block.start })
}
} else if (type === 'li' && listItemType) {
Object.assign(data.dataset, { marker: bulletMarkerOrDelimiter })
selector += `.${CLASS_OR_ID.AG_LIST_ITEM}`
selector += `.ag-${listItemType}-list-item`
selector += isLooseListItem ? `.${CLASS_OR_ID.AG_LOOSE_LIST_ITEM}` : `.${CLASS_OR_ID.AG_TIGHT_LIST_ITEM}`
} else if (type === 'pre') {
Object.assign(data.attrs, { spellcheck: 'false' })
Object.assign(data.dataset, { role: functionType })
selector += PRE_BLOCK_HASH[block.functionType]
if (/html|multiplemath|mermaid|flowchart|vega-lite|sequence|plantuml/.test(functionType)) {
const codeBlock = block.children[0]
const code = codeBlock.children.map(line => line.text).join('\n')
this.codeCache.set(block.key, code)
}
}
if (!block.parent) {
children.unshift(this.renderIcon(block))
}
return h(selector, data, children)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderBlock/renderContainerEditIcon.js | src/muya/lib/parser/render/renderBlock/renderContainerEditIcon.js | import { h } from '../snabbdom'
import { CLASS_OR_ID } from '../../../config'
import htmlIcon from '../../../assets/pngicon/html/2.png'
export const renderEditIcon = () => {
const selector = `a.${CLASS_OR_ID.AG_CONTAINER_ICON}`
const iconVnode = h('i.icon', h('i.icon-inner', {
style: {
background: `url(${htmlIcon}) no-repeat`,
'background-size': '100%'
}
}, ''))
return h(selector, {
attrs: {
contenteditable: 'false'
}
}, iconVnode)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderBlock/renderFootnoteJump.js | src/muya/lib/parser/render/renderBlock/renderFootnoteJump.js | import { h } from '../snabbdom'
export const footnoteJumpIcon = () => {
return h('i.ag-footnote-backlink', '↩︎')
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderBlock/renderIcon.js | src/muya/lib/parser/render/renderBlock/renderIcon.js | import { h } from '../snabbdom'
import { CLASS_OR_ID } from '../../../config'
import paragraphIcon from '../../../assets/pngicon/paragraph/2.png'
import htmlIcon from '../../../assets/pngicon/html/2.png'
import hrIcon from '../../../assets/pngicon/horizontal_line/2.png'
import frontMatterIcon from '../../../assets/pngicon/front_matter/2.png'
import header1Icon from '../../../assets/pngicon/heading_1/2.png'
import header2Icon from '../../../assets/pngicon/heading_2/2.png'
import header3Icon from '../../../assets/pngicon/heading_3/2.png'
import header4Icon from '../../../assets/pngicon/heading_4/2.png'
import header5Icon from '../../../assets/pngicon/heading_5/2.png'
import header6Icon from '../../../assets/pngicon/heading_6/2.png'
import newTableIcon from '../../../assets/pngicon/new_table/2.png'
import bulletListIcon from '../../../assets/pngicon/bullet_list/2.png'
import codeIcon from '../../../assets/pngicon/code/2.png'
import quoteIcon from '../../../assets/pngicon/quote_block/2.png'
import todoListIcon from '../../../assets/pngicon/todolist/2.png'
import mathblockIcon from '../../../assets/pngicon/math/2.png'
import orderListIcon from '../../../assets/pngicon/order_list/2.png'
import flowchartIcon from '../../../assets/pngicon/flowchart/2.png'
import sequenceIcon from '../../../assets/pngicon/sequence/2.png'
import plantumlIcon from '../../../assets/pngicon/plantuml/2.png'
import mermaidIcon from '../../../assets/pngicon/mermaid/2.png'
import vegaIcon from '../../../assets/pngicon/chart/2.png'
import footnoteIcon from '../../../assets/pngicon/footnote/2.png'
const FUNCTION_TYPE_HASH = {
mermaid: mermaidIcon,
flowchart: flowchartIcon,
sequence: sequenceIcon,
plantuml: plantumlIcon,
'vega-lite': vegaIcon,
table: newTableIcon,
html: htmlIcon,
multiplemath: mathblockIcon,
fencecode: codeIcon,
indentcode: codeIcon,
frontmatter: frontMatterIcon,
footnote: footnoteIcon
}
export default function renderIcon (block) {
if (block.parent) {
console.error('Only top most block can render front icon button.')
}
const { type, functionType, listType } = block
const selector = `a.${CLASS_OR_ID.AG_FRONT_ICON}`
let icon = null
switch (type) {
case 'p': {
icon = paragraphIcon
break
}
case 'figure':
case 'pre': {
icon = FUNCTION_TYPE_HASH[functionType]
if (!icon) {
console.warn(`Unhandled functionType ${functionType}`)
icon = paragraphIcon
}
break
}
case 'ul': {
if (listType === 'task') {
icon = todoListIcon
} else {
icon = bulletListIcon
}
break
}
case 'ol': {
icon = orderListIcon
break
}
case 'blockquote': {
icon = quoteIcon
break
}
case 'h1': {
icon = header1Icon
break
}
case 'h2': {
icon = header2Icon
break
}
case 'h3': {
icon = header3Icon
break
}
case 'h4': {
icon = header4Icon
break
}
case 'h5': {
icon = header5Icon
break
}
case 'h6': {
icon = header6Icon
break
}
case 'hr': {
icon = hrIcon
break
}
default:
icon = paragraphIcon
break
}
const iconVnode = h('i.icon', h('i.icon-inner', {
style: {
background: `url(${icon}) no-repeat`,
'background-size': '100%'
}
}, ''))
return h(selector, {
attrs: {
contenteditable: 'false'
}
}, iconVnode)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderBlock/renderLeafBlock.js | src/muya/lib/parser/render/renderBlock/renderLeafBlock.js | import katex from 'katex'
import prism, { loadedLanguages, transformAliasToOrigin } from '../../../prism/'
import 'katex/dist/contrib/mhchem.min.js'
import { CLASS_OR_ID, DEVICE_MEMORY, PREVIEW_DOMPURIFY_CONFIG, HAS_TEXT_BLOCK_REG } from '../../../config'
import { tokenizer } from '../../'
import { snakeToCamel, sanitize, escapeHTML, getLongUniqueId, getImageInfo } from '../../../utils'
import { h, htmlToVNode } from '../snabbdom'
// todo@jocs any better solutions?
const MARKER_HASK = {
'<': `%${getLongUniqueId()}%`,
'>': `%${getLongUniqueId()}%`,
'"': `%${getLongUniqueId()}%`,
"'": `%${getLongUniqueId()}%`
}
const getHighlightHtml = (text, highlights, escape = false, handleLineEnding = false) => {
let code = ''
let pos = 0
const getEscapeHTML = (className, content) => {
return `${MARKER_HASK['<']}span class=${MARKER_HASK['"']}${className}${MARKER_HASK['"']}${MARKER_HASK['>']}${content}${MARKER_HASK['<']}/span${MARKER_HASK['>']}`
}
for (const highlight of highlights) {
const { start, end, active } = highlight
code += text.substring(pos, start)
const className = active ? 'ag-highlight' : 'ag-selection'
let highlightContent = text.substring(start, end)
if (handleLineEnding && text.endsWith('\n') && end === text.length) {
highlightContent = highlightContent.substring(start, end - 1) +
(escape
? getEscapeHTML('ag-line-end', '\n')
: '<span class="ag-line-end">\n</span>')
}
code += escape
? getEscapeHTML(className, highlightContent)
: `<span class="${className}">${highlightContent}</span>`
pos = end
}
if (pos !== text.length) {
if (handleLineEnding && text.endsWith('\n')) {
code += text.substring(pos, text.length - 1) +
(escape
? getEscapeHTML('ag-line-end', '\n')
: '<span class="ag-line-end">\n</span>')
} else {
code += text.substring(pos)
}
}
return escapeHTML(code)
}
const hasReferenceToken = tokens => {
let result = false
const travel = tokens => {
for (const token of tokens) {
if (/reference_image|reference_link/.test(token.type)) {
result = true
break
}
if (Array.isArray(token.children) && token.children.length) {
travel(token.children)
}
}
}
travel(tokens)
return result
}
export default function renderLeafBlock (parent, block, activeBlocks, matches, useCache = false) {
const { loadMathMap } = this
const { cursor } = this.muya.contentState
let selector = this.getSelector(block, activeBlocks)
// highlight search key in block
const highlights = matches.filter(m => m.key === block.key)
const {
text,
type,
checked,
key,
lang,
functionType,
editable
} = block
const data = {
props: {},
attrs: {},
dataset: {},
style: {}
}
let children = ''
if (text) {
let tokens = []
if (highlights.length === 0 && this.tokenCache.has(text)) {
tokens = this.tokenCache.get(text)
} else if (
HAS_TEXT_BLOCK_REG.test(type) &&
functionType !== 'codeContent' &&
functionType !== 'languageInput'
) {
const hasBeginRules = /paragraphContent|atxLine/.test(functionType)
tokens = tokenizer(text, {
highlights,
hasBeginRules,
labels: this.labels,
options: this.muya.options
})
const hasReferenceTokens = hasReferenceToken(tokens)
if (highlights.length === 0 && useCache && DEVICE_MEMORY >= 4 && !hasReferenceTokens) {
this.tokenCache.set(text, tokens)
}
}
children = tokens.reduce((acc, token) => [...acc, ...this[snakeToCamel(token.type)](h, cursor, block, token)], [])
}
if (editable === false) {
Object.assign(data.attrs, {
spellcheck: 'false',
contenteditable: 'false'
})
}
if (type === 'div') {
const code = this.codeCache.get(block.preSibling)
switch (functionType) {
case 'html': {
selector += `.${CLASS_OR_ID.AG_HTML_PREVIEW}`
Object.assign(data.attrs, { spellcheck: 'false' })
const { disableHtml } = this.muya.options
const htmlContent = sanitize(code, PREVIEW_DOMPURIFY_CONFIG, disableHtml)
// handle empty html bock
if (/^<([a-z][a-z\d]*)[^>]*?>(\s*)<\/\1>$/.test(htmlContent.trim())) {
children = htmlToVNode('<div class="ag-empty"><Empty HTML Block></div>')
} else {
const parser = new DOMParser()
const doc = parser.parseFromString(htmlContent, 'text/html')
const imgs = doc.documentElement.querySelectorAll('img')
for (const img of imgs) {
const src = img.getAttribute('src')
const imageInfo = getImageInfo(src)
img.setAttribute('src', imageInfo.src)
}
children = htmlToVNode(doc.documentElement.querySelector('body').innerHTML)
}
break
}
case 'multiplemath': {
const key = `${code}_display_math`
selector += `.${CLASS_OR_ID.AG_CONTAINER_PREVIEW}`
Object.assign(data.attrs, { spellcheck: 'false' })
if (code === '') {
children = '< Empty Mathematical Formula >'
selector += `.${CLASS_OR_ID.AG_EMPTY}`
} else if (loadMathMap.has(key)) {
children = loadMathMap.get(key)
} else {
try {
const html = katex.renderToString(code, {
displayMode: true
})
children = htmlToVNode(html)
loadMathMap.set(key, children)
} catch (err) {
children = '< Invalid Mathematical Formula >'
selector += `.${CLASS_OR_ID.AG_MATH_ERROR}`
}
}
break
}
case 'mermaid': {
selector += `.${CLASS_OR_ID.AG_CONTAINER_PREVIEW}`
Object.assign(data.attrs, { spellcheck: 'false' })
if (code === '') {
children = '< Empty Mermaid Block >'
selector += `.${CLASS_OR_ID.AG_EMPTY}`
} else {
children = 'Loading...'
this.mermaidCache.set(`#${block.key}`, {
code,
functionType
})
}
break
}
case 'flowchart':
case 'sequence':
case 'plantuml':
case 'vega-lite': {
selector += `.${CLASS_OR_ID.AG_CONTAINER_PREVIEW}`
Object.assign(data.attrs, { spellcheck: 'false' })
if (code === '') {
children = '< Empty Diagram Block >'
selector += `.${CLASS_OR_ID.AG_EMPTY}`
} else {
children = 'Loading...'
this.diagramCache.set(`#${block.key}`, {
code,
functionType
})
}
break
}
}
} else if (type === 'input') {
const { fontSize, lineHeight } = this.muya.options
Object.assign(data.attrs, {
type: 'checkbox',
style: `top: ${(fontSize * lineHeight / 2 - 8).toFixed(2)}px`
})
selector = `${type}#${key}.${CLASS_OR_ID.AG_TASK_LIST_ITEM_CHECKBOX}`
if (checked) {
Object.assign(data.attrs, {
checked: true
})
selector += `.${CLASS_OR_ID.AG_CHECKBOX_CHECKED}`
}
children = ''
} else if (type === 'span' && functionType === 'codeContent') {
const code = getHighlightHtml(text, highlights, true, true)
.replace(new RegExp(MARKER_HASK['<'], 'g'), '<')
.replace(new RegExp(MARKER_HASK['>'], 'g'), '>')
.replace(new RegExp(MARKER_HASK['"'], 'g'), '"')
.replace(new RegExp(MARKER_HASK["'"], 'g'), "'")
// transform alias to original language
const transformedLang = transformAliasToOrigin([lang])[0]
if (transformedLang && /\S/.test(code) && loadedLanguages.has(transformedLang)) {
const wrapper = document.createElement('div')
wrapper.classList.add(`language-${transformedLang}`)
wrapper.innerHTML = code
prism.highlightElement(wrapper, false, function () {
const highlightedCode = this.innerHTML
selector += `.language-${transformedLang}`
children = htmlToVNode(highlightedCode)
})
} else {
children = htmlToVNode(code)
}
} else if (type === 'span' && functionType === 'languageInput') {
const escapedText = sanitize(text, PREVIEW_DOMPURIFY_CONFIG, true)
const html = getHighlightHtml(escapedText, highlights, true)
children = htmlToVNode(html)
} else if (type === 'span' && functionType === 'footnoteInput') {
Object.assign(data.attrs, { spellcheck: 'false' })
}
if (!block.parent) {
return h(selector, data, [this.renderIcon(block), ...children])
} else {
return h(selector, data, children)
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderBlock/renderTableDargBar.js | src/muya/lib/parser/render/renderBlock/renderTableDargBar.js | import { h } from '../snabbdom'
export const renderLeftBar = () => {
return h('span.ag-drag-handler.left', {
attrs: { contenteditable: 'false' }
})
}
export const renderBottomBar = () => {
return h('span.ag-drag-handler.bottom', {
attrs: { contenteditable: 'false' }
})
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderBlock/renderToolBar.js | src/muya/lib/parser/render/renderBlock/renderToolBar.js | // used for render table tookbar or others.
import { h } from '../snabbdom'
import { CLASS_OR_ID } from '../../../config'
import TableIcon from '../../../assets/pngicon/table/[email protected]'
import AlignLeftIcon from '../../../assets/pngicon/algin_left/2.png'
import AlignRightIcon from '../../../assets/pngicon/algin_right/2.png'
import AlignCenterIcon from '../../../assets/pngicon/algin_center/2.png'
import DeleteIcon from '../../../assets/pngicon/table_delete/2.png'
export const TABLE_TOOLS = Object.freeze([{
label: 'table',
title: 'Resize Table',
icon: TableIcon
}, {
label: 'left',
title: 'Align Left',
icon: AlignLeftIcon
}, {
label: 'center',
title: 'Align Center',
icon: AlignCenterIcon
}, {
label: 'right',
title: 'Align Right',
icon: AlignRightIcon
}, {
label: 'delete',
title: 'Delete Table',
icon: DeleteIcon
}])
const renderToolBar = (type, tools, activeBlocks) => {
const children = tools.map(tool => {
const { label, title, icon } = tool
const { align } = activeBlocks[1] // activeBlocks[0] is span block. cell content.
let selector = 'li'
if (align && label === align) {
selector += '.active'
}
const iconVnode = h('i.icon', h(`i.icon-${label}`, {
style: {
background: `url(${icon}) no-repeat`,
'background-size': '100%'
}
}, ''))
return h(selector, {
dataset: {
label,
tooltip: title
}
}, iconVnode)
})
const selector = `div.ag-tool-${type}.${CLASS_OR_ID.AG_TOOL_BAR}`
return h(selector, {
attrs: {
contenteditable: false
}
}, h('ul', children))
}
export const renderTableTools = (activeBlocks) => {
return renderToolBar('table', TABLE_TOOLS, activeBlocks)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/parser/render/renderBlock/renderBlock.js | src/muya/lib/parser/render/renderBlock/renderBlock.js | /**
* [renderBlock render one block, no matter it is a container block or text block]
*/
export default function renderBlock (parent, block, activeBlocks, matches, useCache = false) {
const method = Array.isArray(block.children) && block.children.length > 0
? 'renderContainerBlock'
: 'renderLeafBlock'
return this[method](parent, block, activeBlocks, matches, useCache)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/common/envPaths.js | src/common/envPaths.js | import path from 'path'
class EnvPaths {
/**
* @param {string} userDataPath The user data path.
* @returns
*/
constructor (userDataPath) {
const currentDate = new Date()
if (!userDataPath) {
throw new Error('"userDataPath" is not set.')
}
this._electronUserDataPath = userDataPath // path.join(userDataPath, 'electronUserData')
this._userDataPath = userDataPath
this._logPath = path.join(this._userDataPath, 'logs', `${currentDate.getFullYear()}${currentDate.getMonth() + 1}`)
this._preferencesPath = userDataPath // path.join(this._userDataPath, 'preferences')
this._dataCenterPath = userDataPath
this._preferencesFilePath = path.join(this._preferencesPath, 'preference.json')
// TODO(sessions): enable this...
// this._globalStorage = path.join(this._userDataPath, 'globalStorage')
// this._preferencesPath = path.join(this._userDataPath, 'preferences')
// this._sessionsPath = path.join(this._userDataPath, 'sessions')
}
get electronUserDataPath () {
// This path is identical to app.getPath('userData') but userDataPath must not necessarily be the same path.
return this._electronUserDataPath
}
get userDataPath () {
return this._userDataPath
}
get logPath () {
return this._logPath
}
get preferencesPath () {
return this._preferencesPath
}
get dataCenterPath () {
return this._dataCenterPath
}
get preferencesFilePath () {
return this._preferencesFilePath
}
}
export default EnvPaths
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/common/encoding.js | src/common/encoding.js | export const ENCODING_NAME_MAP = Object.freeze({
utf8: 'UTF-8',
utf16be: 'UTF-16 BE',
utf16le: 'UTF-16 LE',
utf32be: 'UTF-32 BE',
utf32le: 'UTF-32 LE',
ascii: 'Western (ISO 8859-1)',
latin3: 'Western (ISO 8859-3)',
iso885915: 'Western (ISO 8859-15)',
cp1252: 'Western (Windows 1252)',
arabic: 'Arabic (ISO 8859-6)',
cp1256: 'Arabic (Windows 1256)',
latin4: 'Baltic (ISO 8859-4)',
cp1257: 'Baltic (Windows 1257)',
iso88592: 'Central European (ISO 8859-2)',
windows1250: 'Central European (Windows 1250)',
cp866: 'Cyrillic (CP 866)',
iso88595: 'Cyrillic (ISO 8859-5)',
koi8r: 'Cyrillic (KOI8-R)',
koi8u: 'Cyrillic (KOI8-U)',
cp1251: 'Cyrillic (Windows 1251)',
iso885913: 'Estonian (ISO 8859-13)',
greek: 'Greek (ISO 8859-7)',
cp1253: 'Greek (Windows 1253)',
hebrew: 'Hebrew (ISO 8859-8)',
cp1255: 'Hebrew (Windows 1255)',
latin5: 'Turkish (ISO 8859-9)',
cp1254: 'Turkish (Windows 1254)',
gb2312: 'Simplified Chinese (GB2312)',
gb18030: 'Simplified Chinese (GB18030)',
gbk: 'Simplified Chinese (GBK)',
big5: 'Traditional Chinese (Big5)',
big5hkscs: 'Traditional Chinese (Big5-HKSCS)',
shiftjis: 'Japanese (Shift JIS)',
eucjp: 'Japanese (EUC-JP)',
euckr: 'Korean (EUC-KR)',
latin6: 'Nordic (ISO 8859-10)'
})
/**
* Try to translate the encoding.
*
* @param {Encoding} enc The encoding object.
*/
export const getEncodingName = enc => {
const { encoding, isBom } = enc
let str = ENCODING_NAME_MAP[encoding] || encoding
if (isBom) {
str += ' with BOM'
}
return str
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/common/commands/constants.js | src/common/commands/constants.js | const COMMANDS = Object.freeze({
EDIT_COPY: 'edit.copy',
EDIT_COPY_AS_HTML: 'edit.copy-as-html',
EDIT_COPY_AS_MARKDOWN: 'edit.copy-as-markdown',
EDIT_CREATE_PARAGRAPH: 'edit.create-paragraph',
EDIT_CUT: 'edit.cut',
EDIT_DELETE_PARAGRAPH: 'edit.delete-paragraph',
EDIT_DUPLICATE: 'edit.duplicate',
EDIT_FIND: 'edit.find',
EDIT_FIND_IN_FOLDER: 'edit.find-in-folder',
EDIT_FIND_NEXT: 'edit.find-next',
EDIT_FIND_PREVIOUS: 'edit.find-previous',
EDIT_PASTE: 'edit.paste',
EDIT_PASTE_AS_PLAINTEXT: 'edit.paste-as-plaintext',
EDIT_REDO: 'edit.redo',
EDIT_REPLACE: 'edit.replace',
EDIT_SCREENSHOT: 'edit.screenshot',
EDIT_SELECT_ALL: 'edit.select-all',
EDIT_UNDO: 'edit.undo',
FILE_CHECK_UPDATE: 'file.check-update',
FILE_CLOSE_TAB: 'file.close-tab',
FILE_CLOSE_WINDOW: 'file.close-window',
FILE_EXPORT_FILE: 'file.export-file',
FILE_IMPORT_FILE: 'file.import-file',
FILE_MOVE_FILE: 'file.move-file',
FILE_NEW_FILE: 'file.new-window',
FILE_NEW_TAB: 'file.new-tab',
FILE_OPEN_FILE: 'file.open-file',
FILE_OPEN_FOLDER: 'file.open-folder',
FILE_PREFERENCES: 'file.preferences',
FILE_PRINT: 'file.print',
FILE_QUICK_OPEN: 'file.quick-open',
FILE_QUIT: 'file.quit',
FILE_RENAME_FILE: 'file.rename-file',
FILE_SAVE: 'file.save',
FILE_SAVE_AS: 'file.save-as',
// FILE_TOGGLE_AUTO_SAVE: 'file.toggle-auto-save',
FORMAT_CLEAR_FORMAT: 'format.clear-format',
FORMAT_EMPHASIS: 'format.emphasis',
FORMAT_HIGHLIGHT: 'format.highlight',
FORMAT_HYPERLINK: 'format.hyperlink',
FORMAT_IMAGE: 'format.image',
FORMAT_INLINE_CODE: 'format.inline-code',
FORMAT_INLINE_MATH: 'format.inline-math',
FORMAT_STRIKE: 'format.strike',
FORMAT_STRONG: 'format.strong',
FORMAT_SUBSCRIPT: 'format.subscript',
FORMAT_SUPERSCRIPT: 'format.superscript',
FORMAT_UNDERLINE: 'format.underline',
MT_HIDE: 'mt.hide',
MT_HIDE_OTHERS: 'mt.hide-others',
PARAGRAPH_BULLET_LIST: 'paragraph.bullet-list',
PARAGRAPH_CODE_FENCE: 'paragraph.code-fence',
PARAGRAPH_DEGRADE_HEADING: 'paragraph.degrade-heading',
PARAGRAPH_FRONT_MATTER: 'paragraph.front-matter',
PARAGRAPH_HEADING_1: 'paragraph.heading-1',
PARAGRAPH_HEADING_2: 'paragraph.heading-2',
PARAGRAPH_HEADING_3: 'paragraph.heading-3',
PARAGRAPH_HEADING_4: 'paragraph.heading-4',
PARAGRAPH_HEADING_5: 'paragraph.heading-5',
PARAGRAPH_HEADING_6: 'paragraph.heading-6',
PARAGRAPH_HORIZONTAL_LINE: 'paragraph.horizontal-line',
PARAGRAPH_HTML_BLOCK: 'paragraph.html-block',
PARAGRAPH_LOOSE_LIST_ITEM: 'paragraph.loose-list-item',
PARAGRAPH_MATH_FORMULA: 'paragraph.math-formula',
PARAGRAPH_ORDERED_LIST: 'paragraph.order-list',
PARAGRAPH_PARAGRAPH: 'paragraph.paragraph',
PARAGRAPH_QUOTE_BLOCK: 'paragraph.quote-block',
PARAGRAPH_TABLE: 'paragraph.table',
PARAGRAPH_TASK_LIST: 'paragraph.task-list',
PARAGRAPH_INCREASE_HEADING: 'paragraph.upgrade-heading',
TABS_CYCLE_BACKWARD: 'tabs.cycle-backward',
TABS_CYCLE_FORWARD: 'tabs.cycle-forward',
TABS_SWITCH_TO_EIGHTH: 'tabs.switch-to-eighth',
TABS_SWITCH_TO_FIFTH: 'tabs.switch-to-fifth',
TABS_SWITCH_TO_FIRST: 'tabs.switch-to-first',
TABS_SWITCH_TO_FOURTH: 'tabs.switch-to-fourth',
TABS_SWITCH_TO_LEFT: 'tabs.switch-to-left',
TABS_SWITCH_TO_NINTH: 'tabs.switch-to-ninth',
TABS_SWITCH_TO_RIGHT: 'tabs.switch-to-right',
TABS_SWITCH_TO_SECOND: 'tabs.switch-to-second',
TABS_SWITCH_TO_SEVENTH: 'tabs.switch-to-seventh',
TABS_SWITCH_TO_SIXTH: 'tabs.switch-to-sixth',
TABS_SWITCH_TO_TENTH: 'tabs.switch-to-tenth',
TABS_SWITCH_TO_THIRD: 'tabs.switch-to-third',
VIEW_COMMAND_PALETTE: 'view.command-palette',
VIEW_DEV_RELOAD: 'view.dev-reload',
VIEW_FOCUS_MODE: 'view.focus-mode',
VIEW_FORCE_RELOAD_IMAGES: 'view.reload-images',
VIEW_SOURCE_CODE_MODE: 'view.source-code-mode',
VIEW_TOGGLE_DEV_TOOLS: 'view.toggle-dev-tools',
VIEW_TOGGLE_SIDEBAR: 'view.toggle-sidebar',
VIEW_TOGGLE_TABBAR: 'view.toggle-tabbar',
VIEW_TOGGLE_TOC: 'view.toggle-toc',
VIEW_TYPEWRITER_MODE: 'view.typewriter-mode',
WINDOW_MINIMIZE: 'window.minimize',
WINDOW_TOGGLE_ALWAYS_ON_TOP: 'window.toggle-always-on-top',
WINDOW_TOGGLE_FULL_SCREEN: 'window.toggle-full-screen',
WINDOW_ZOOM_IN: 'window.zoom-in',
WINDOW_ZOOM_OUT: 'window.zoom-out'
})
export default COMMANDS
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/common/filesystem/index.js | src/common/filesystem/index.js | import fs from 'fs-extra'
import fsPromises from 'fs/promises'
import path from 'path'
/**
* Test whether or not the given path exists.
*
* @param {string} p The path to the file or directory.
* @returns {boolean}
*/
export const exists = async p => {
try {
await fsPromises.access(p)
return true
} catch (_) {
return false
}
}
/**
* Ensure that a directory exist.
*
* @param {string} dirPath The directory path.
*/
export const ensureDirSync = dirPath => {
try {
fs.ensureDirSync(dirPath)
} catch (e) {
if (e.code !== 'EEXIST') {
throw e
}
}
}
/**
* Returns true if the path is a directory with read access.
*
* @param {string} dirPath The directory path.
*/
export const isDirectory = dirPath => {
try {
return fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory()
} catch (_) {
return false
}
}
/**
* Returns true if the path is a directory or a symbolic link to a directory with read access.
*
* @param {string} dirPath The directory path.
*/
export const isDirectory2 = dirPath => {
try {
if (!fs.existsSync(dirPath)) {
return false
}
const fi = fs.lstatSync(dirPath)
if (fi.isDirectory()) {
return true
} else if (fi.isSymbolicLink()) {
const targetPath = path.resolve(path.dirname(dirPath), fs.readlinkSync(dirPath))
return isDirectory(targetPath)
}
return false
} catch (_) {
return false
}
}
/**
* Returns true if the path is a file with read access.
*
* @param {string} filepath The file path.
*/
export const isFile = filepath => {
try {
return fs.existsSync(filepath) && fs.lstatSync(filepath).isFile()
} catch (_) {
return false
}
}
/**
* Returns true if the path is a file or a symbolic link to a file with read access.
*
* @param {string} filepath The file path.
*/
export const isFile2 = filepath => {
try {
if (!fs.existsSync(filepath)) {
return false
}
const fi = fs.lstatSync(filepath)
if (fi.isFile()) {
return true
} else if (fi.isSymbolicLink()) {
const targetPath = path.resolve(path.dirname(filepath), fs.readlinkSync(filepath))
return isFile(targetPath)
}
return false
} catch (_) {
return false
}
}
/**
* Returns true if the path is a symbolic link with read access.
*
* @param {string} filepath The link path.
*/
export const isSymbolicLink = filepath => {
try {
return fs.existsSync(filepath) && fs.lstatSync(filepath).isSymbolicLink()
} catch (_) {
return false
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/common/filesystem/paths.js | src/common/filesystem/paths.js | import fs from 'fs'
import path from 'path'
import { isFile, isFile2, isSymbolicLink } from './index'
const isOsx = process.platform === 'darwin'
export const MARKDOWN_EXTENSIONS = Object.freeze([
'markdown',
'mdown',
'mkdn',
'md',
'mkd',
'mdwn',
'mdtxt',
'mdtext',
'mdx',
'text',
'txt'
])
export const MARKDOWN_INCLUSIONS = Object.freeze(MARKDOWN_EXTENSIONS.map(x => '*.' + x))
export const IMAGE_EXTENSIONS = Object.freeze([
'jpeg',
'jpg',
'png',
'gif',
'svg',
'webp'
])
/**
* Returns true if the filename matches one of the markdown extensions.
*
* @param {string} filename Path or filename
*/
export const hasMarkdownExtension = filename => {
if (!filename || typeof filename !== 'string') return false
return MARKDOWN_EXTENSIONS.some(ext => filename.toLowerCase().endsWith(`.${ext}`))
}
/**
* Returns true if the path is an image file.
*
* @param {string} filepath The path
*/
export const isImageFile = filepath => {
const extname = path.extname(filepath)
return isFile(filepath) && IMAGE_EXTENSIONS.some(ext => {
const EXT_REG = new RegExp(ext, 'i')
return EXT_REG.test(extname)
})
}
/**
* Returns true if the path is a markdown file or symbolic link to a markdown file.
*
* @param {string} filepath The path or link path.
*/
export const isMarkdownFile = filepath => {
if (!isFile2(filepath)) return false
// Check symbolic link.
if (isSymbolicLink(filepath)) {
const targetPath = path.resolve(path.dirname(filepath), fs.readlinkSync(filepath))
return isFile(targetPath) && hasMarkdownExtension(targetPath)
}
return hasMarkdownExtension(filepath)
}
/**
* Check if the both paths point to the same file.
*
* @param {string} pathA The first path.
* @param {string} pathB The second path.
* @param {boolean} [isNormalized] Are both paths already normalized.
*/
export const isSamePathSync = (pathA, pathB, isNormalized = false) => {
if (!pathA || !pathB) return false
const a = isNormalized ? pathA : path.normalize(pathA)
const b = isNormalized ? pathB : path.normalize(pathB)
if (a.length !== b.length) {
return false
} else if (a === b) {
return true
} else if (a.toLowerCase() === b.toLowerCase()) {
try {
const fiA = fs.statSync(a)
const fiB = fs.statSync(b)
return fiA.ino === fiB.ino
} catch (_) {
// Ignore error
}
}
return false
}
/**
* Check whether a file or directory is a child of the given directory.
*
* @param {string} dir The parent directory.
* @param {string} child The file or directory path to check.
*/
export const isChildOfDirectory = (dir, child) => {
if (!dir || !child) return false
const relative = path.relative(dir, child)
return relative && !relative.startsWith('..') && !path.isAbsolute(relative)
}
export const getResourcesPath = () => {
let resPath = process.resourcesPath
if (process.env.NODE_ENV === 'development') {
// Default locations:
// Linux/Windows: node_modules/electron/dist/resources/
// macOS: node_modules/electron/dist/Electron.app/Contents/Resources
if (isOsx) {
resPath = path.join(resPath, '../..')
}
resPath = path.join(resPath, '../../../../resources')
}
return resPath
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/common/keybinding/index.js | src/common/keybinding/index.js | const isOsx = process.platform === 'darwin'
const _normalizeAccelerator = accelerator => {
return accelerator.toLowerCase()
.replace('commandorcontrol', isOsx ? 'cmd' : 'ctrl')
.replace('cmdorctrl', isOsx ? 'cmd' : 'ctrl')
.replace('control', 'ctrl')
.replace('meta', 'cmd') // meta := cmd (macOS only) or super
.replace('command', 'cmd')
.replace('option', 'alt')
}
export const isEqualAccelerator = (a, b) => {
a = _normalizeAccelerator(a)
b = _normalizeAccelerator(b)
const i1 = a.indexOf('+')
const i2 = b.indexOf('+')
if (i1 === -1 && i2 === -1) {
return a === b
} else if (i1 === -1 || i2 === -1) {
return false
}
const partsA = a.split('+')
const partsB = b.split('+')
if (partsA.length !== partsB.length) {
return false
}
const intersection = new Set([...partsA, ...partsB])
return intersection.size === partsB.length
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/index.js | src/main/index.js | import './globalSetting'
import path from 'path'
import { app, dialog } from 'electron'
import { initialize as remoteInitializeServer } from '@electron/remote/main'
import cli from './cli'
import setupExceptionHandler, { initExceptionLogger } from './exceptionHandler'
import log from 'electron-log'
import App from './app'
import Accessor from './app/accessor'
import setupEnvironment from './app/env'
import { getLogLevel } from './utils'
const initializeLogger = appEnvironment => {
log.transports.console.level = process.env.NODE_ENV === 'development' ? 'info' : 'error'
log.transports.rendererConsole = null
log.transports.file.resolvePath = () => path.join(appEnvironment.paths.logPath, 'main.log')
log.transports.file.level = getLogLevel()
log.transports.file.sync = true
initExceptionLogger()
}
// -----------------------------------------------
// NOTE: We only support Linux, macOS and Windows but not BSD nor SunOS.
if (!/^(darwin|win32|linux)$/i.test(process.platform)) {
process.stdout.write(`Operating system "${process.platform}" is not supported! Please open an issue at "https://github.com/marktext/marktext".\n`)
process.exit(1)
}
setupExceptionHandler()
const args = cli()
const appEnvironment = setupEnvironment(args)
initializeLogger(appEnvironment)
if (args['--disable-gpu']) {
app.disableHardwareAcceleration()
}
// Make MarkText a single instance application.
if (!process.mas && process.env.NODE_ENV !== 'development') {
const gotSingleInstanceLock = app.requestSingleInstanceLock()
if (!gotSingleInstanceLock) {
process.stdout.write('Other MarkText instance detected: exiting...\n')
app.exit()
}
}
// MarkText environment is configured successfully. You can now access paths, use the logger etc.
// Create other instances that need access to the modules from above.
let accessor = null
try {
accessor = new Accessor(appEnvironment)
} catch (err) {
// Catch errors that may come from invalid configuration files like settings.
const msgHint = err.message.includes('Config schema violation')
? 'This seems to be an issue with your configuration file(s). '
: ''
log.error(`Loading MarkText failed during initialization! ${msgHint}`, err)
const EXIT_ON_ERROR = !!process.env.MARKTEXT_EXIT_ON_ERROR
const SHOW_ERROR_DIALOG = !process.env.MARKTEXT_ERROR_INTERACTION
if (!EXIT_ON_ERROR && SHOW_ERROR_DIALOG) {
dialog.showErrorBox(
'There was an error during loading',
`${msgHint}${err.message}\n\n${err.stack}`
)
}
process.exit(1)
}
// Use synchronous only to report errors in early stage of startup.
log.transports.file.sync = false
// -----------------------------------------------
// Be careful when changing code before this line!
// NOTE: Do not create classes or other code before this line!
// TODO: We should switch to another async API like https://nornagon.medium.com/electrons-remote-module-considered-harmful-70d69500f31.
// Enable remote module
remoteInitializeServer()
const marktext = new App(accessor, args)
marktext.init()
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/config.js | src/main/config.js | export const isOsx = process.platform === 'darwin'
export const isWindows = process.platform === 'win32'
export const isLinux = process.platform === 'linux'
export const editorWinOptions = Object.freeze({
minWidth: 550,
minHeight: 350,
webPreferences: {
contextIsolation: false,
// WORKAROUND: We cannot enable spellcheck if it was disabled during
// renderer startup due to a bug in Electron (Electron#32755). We'll
// enable it always and set the HTML spelling attribute to false.
spellcheck: true,
nodeIntegration: true,
webSecurity: false
},
useContentSize: true,
show: true,
frame: false,
titleBarStyle: 'hiddenInset',
zoomFactor: 1.0
})
export const preferencesWinOptions = Object.freeze({
minWidth: 450,
minHeight: 350,
width: 950,
height: 650,
webPreferences: {
contextIsolation: false,
// Always true to access native spellchecker.
spellcheck: true,
nodeIntegration: true,
webSecurity: false
},
fullscreenable: false,
fullscreen: false,
minimizable: false,
useContentSize: true,
show: true,
frame: false,
thickFrame: !isOsx,
titleBarStyle: 'hiddenInset',
zoomFactor: 1.0
})
export const PANDOC_EXTENSIONS = Object.freeze([
'html',
'docx',
'odt',
'latex',
'tex',
'ltx',
'rst',
'rest',
'org',
'wiki',
'dokuwiki',
'textile',
'opml',
'epub'
])
export const BLACK_LIST = Object.freeze([
'$RECYCLE.BIN'
])
export const EXTENSION_HASN = Object.freeze({
styledHtml: '.html',
pdf: '.pdf'
})
export const TITLE_BAR_HEIGHT = isOsx ? 21 : 32
export const LINE_ENDING_REG = /(?:\r\n|\n)/g
export const LF_LINE_ENDING_REG = /(?:[^\r]\n)|(?:^\n$)/
export const CRLF_LINE_ENDING_REG = /\r\n/
export const GITHUB_REPO_URL = 'https://github.com/marktext/marktext'
// copy from muya
export const URL_REG = /^http(s)?:\/\/([a-z0-9\-._~]+\.[a-z]{2,}|[0-9.]+|localhost|\[[a-f0-9.:]+\])(:[0-9]{1,5})?(\/[\S]+)?/i
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/index.dev.js | src/main/index.dev.js | /**
* This file is used specifically and only for development. It installs
* `vue-devtools`. There shouldn't be any need to modify this file,
* but it can be used to extend your development environment.
*/
/* eslint-disable */
require('dotenv').config()
// Install `vue-devtools`
require('electron').app.on('ready', () => {
const { default: installExtension, VUEJS_DEVTOOLS } = require('electron-devtools-installer')
installExtension(VUEJS_DEVTOOLS)
.then(() => {})
.catch(err => {
console.log('Unable to install `vue-devtools`: \n', err)
})
})
/* eslint-enable */
// Require `main` process to boot app
require('./index')
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/globalSetting.js | src/main/globalSetting.js | import path from 'path'
// Set `__static` path to static files in production.
if (process.env.NODE_ENV !== 'development') {
global.__static = path.join(__dirname, '/static').replace(/\\/g, '\\\\')
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/exceptionHandler.js | src/main/exceptionHandler.js | // Based on electron-unhandled by sindresorhus:
//
// MIT License
// Copyright (c) Sindre Sorhus <[email protected]> (sindresorhus.com)
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import { app, clipboard, crashReporter, dialog, ipcMain } from 'electron'
import os from 'os'
import log from 'electron-log'
import { createAndOpenGitHubIssueUrl } from './utils/createGitHubIssue'
const EXIT_ON_ERROR = !!process.env.MARKTEXT_EXIT_ON_ERROR
const SHOW_ERROR_DIALOG = !process.env.MARKTEXT_ERROR_INTERACTION
const ERROR_MSG_MAIN = 'An unexpected error occurred in the main process'
const ERROR_MSG_RENDERER = 'An unexpected error occurred in the renderer process'
let logger = s => console.error(s)
const getOSInformation = () => {
return `${os.type()} ${os.arch()} ${os.release()} (${os.platform()})`
}
const exceptionToString = (error, type) => {
const { message, stack } = error
return `Version: ${global.MARKTEXT_VERSION_STRING || app.getVersion()}\n` +
`OS: ${getOSInformation()}\n` +
`Type: ${type}\n` +
`Date: ${new Date().toUTCString()}\n` +
`Message: ${message}\n` +
`Stack: ${stack}\n`
}
const handleError = async (title, error, type) => {
const { message, stack } = error
// Write error into file
if (type === 'main') {
logger(exceptionToString(error, type))
}
if (EXIT_ON_ERROR) {
console.log('MarkText was terminated due to an unexpected error (MARKTEXT_EXIT_ON_ERROR variable was set)!')
process.exit(1)
// eslint, don't lie to me, the return statement is important!
return // eslint-disable-line no-unreachable
} else if (!SHOW_ERROR_DIALOG || (global.MARKTEXT_IS_STABLE && type === 'renderer')) {
return
}
// show error dialog
if (app.isReady()) {
// Blocking message box
const { response } = await dialog.showMessageBox({
type: 'error',
buttons: [
'OK',
'Copy Error',
'Report...'
],
defaultId: 0,
noLink: true,
message: title,
detail: stack
})
switch (response) {
case 1: {
clipboard.writeText(`${title}\n${stack}`)
break
}
case 2: {
const issueTitle = message ? `Unexpected error: ${message}` : title
createAndOpenGitHubIssueUrl(
issueTitle,
`### Description
${title}.
<!-- Please describe, how the bug occurred -->
### Stack Trace
\`\`\`\n${stack}\n\`\`\`
### Version
MarkText: ${global.MARKTEXT_VERSION_STRING}
Operating system: ${getOSInformation()}`)
break
}
}
} else {
// error during Electron initialization
dialog.showErrorBox(title, stack)
process.exit(1)
}
}
const setupExceptionHandler = () => {
// main process error handler
process.on('uncaughtException', error => {
handleError(ERROR_MSG_MAIN, error, 'main')
})
// renderer process error handler
ipcMain.on('mt::handle-renderer-error', (e, error) => {
handleError(ERROR_MSG_RENDERER, error, 'renderer')
})
// start crashReporter to save core dumps to temporary folder
crashReporter.start({
companyName: 'marktext',
productName: 'marktext',
submitURL: 'http://0.0.0.0/',
uploadToServer: false,
compress: true
})
}
export const initExceptionLogger = () => {
// replace placeholder logger
logger = log.error
}
export default setupExceptionHandler
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/dataCenter/index.js | src/main/dataCenter/index.js | import fs from 'fs'
import path from 'path'
import EventEmitter from 'events'
import { BrowserWindow, ipcMain, dialog } from 'electron'
import keytar from 'keytar'
import schema from './schema'
import Store from 'electron-store'
import log from 'electron-log'
import { ensureDirSync } from 'common/filesystem'
import { IMAGE_EXTENSIONS } from 'common/filesystem/paths'
const DATA_CENTER_NAME = 'dataCenter'
class DataCenter extends EventEmitter {
constructor (paths) {
super()
const { dataCenterPath, userDataPath } = paths
this.dataCenterPath = dataCenterPath
this.userDataPath = userDataPath
this.serviceName = 'marktext'
this.encryptKeys = ['githubToken']
this.hasDataCenterFile = fs.existsSync(path.join(this.dataCenterPath, `./${DATA_CENTER_NAME}.json`))
this.store = new Store({
schema,
name: DATA_CENTER_NAME
})
this.init()
}
init () {
const defaultData = {
imageFolderPath: path.join(this.userDataPath, 'images'),
screenshotFolderPath: path.join(this.userDataPath, 'screenshot'),
webImages: [],
cloudImages: [],
currentUploader: 'none',
imageBed: {
github: {
owner: '',
repo: '',
branch: ''
}
}
}
if (!this.hasDataCenterFile) {
this.store.set(defaultData)
ensureDirSync(this.store.get('screenshotFolderPath'))
}
this._listenForIpcMain()
}
async getAll () {
const { serviceName, encryptKeys } = this
const data = this.store.store
try {
const encryptData = await Promise.all(encryptKeys.map(key => {
return keytar.getPassword(serviceName, key)
}))
const encryptObj = encryptKeys.reduce((acc, k, i) => {
return {
...acc,
[k]: encryptData[i]
}
}, {})
return Object.assign(data, encryptObj)
} catch (err) {
log.error('Failed to decrypt secure keys:', err)
return data
}
}
addImage (key, url) {
const items = this.store.get(key)
const alreadyHas = items.some(item => item.url === url)
let item
if (alreadyHas) {
item = items.find(item => item.url === url)
item.timeStamp = +new Date()
} else {
item = {
url,
timeStamp: +new Date()
}
items.push(item)
}
ipcMain.emit('broadcast-web-image-added', { type: key, item })
return this.store.set(key, items)
}
removeImage (type, url) {
const items = this.store.get(type)
const index = items.indexOf(url)
const item = items[index]
if (index === -1) return
items.splice(index, 1)
ipcMain.emit('broadcast-web-image-removed', { type, item })
return this.store.set(type, items)
}
/**
*
* @param {string} key
* return a promise
*/
getItem (key) {
const { encryptKeys, serviceName } = this
if (encryptKeys.includes(key)) {
return keytar.getPassword(serviceName, key)
} else {
const value = this.store.get(key)
return Promise.resolve(value)
}
}
async setItem (key, value) {
const { encryptKeys, serviceName } = this
if (key === 'screenshotFolderPath') {
ensureDirSync(value)
}
ipcMain.emit('broadcast-user-data-changed', { [key]: value })
if (encryptKeys.includes(key)) {
try {
return await keytar.setPassword(serviceName, key, value)
} catch (err) {
log.error('Keytar error:', err)
}
} else {
return this.store.set(key, value)
}
}
/**
* Change multiple setting entries.
*
* @param {Object.<string, *>} settings A settings object or subset object with key/value entries.
*/
setItems (settings) {
if (!settings) {
log.error('Cannot change settings without entires: object is undefined or null.')
return
}
Object.keys(settings).forEach(key => {
this.setItem(key, settings[key])
})
}
_listenForIpcMain () {
// local main events
ipcMain.on('set-image-folder-path', newPath => {
this.setItem('imageFolderPath', newPath)
})
// events from renderer process
ipcMain.on('mt::ask-for-user-data', async e => {
const win = BrowserWindow.fromWebContents(e.sender)
const userData = await this.getAll()
win.webContents.send('mt::user-preference', userData)
})
ipcMain.on('mt::ask-for-modify-image-folder-path', async (e, imagePath) => {
if (!imagePath) {
const win = BrowserWindow.fromWebContents(e.sender)
const { filePaths } = await dialog.showOpenDialog(win, {
properties: ['openDirectory', 'createDirectory']
})
if (filePaths && filePaths[0]) {
imagePath = filePaths[0]
}
}
if (imagePath) {
this.setItem('imageFolderPath', imagePath)
}
})
ipcMain.on('mt::set-user-data', (e, userData) => {
this.setItems(userData)
})
// TODO: Replace sync. call.
ipcMain.on('mt::ask-for-image-path', async e => {
const win = BrowserWindow.fromWebContents(e.sender)
const { filePaths } = await dialog.showOpenDialog(win, {
properties: ['openFile'],
filters: [{
name: 'Images',
extensions: IMAGE_EXTENSIONS
}]
})
if (filePaths && filePaths[0]) {
e.returnValue = filePaths[0]
} else {
e.returnValue = ''
}
})
}
}
export default DataCenter
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/app/accessor.js | src/main/app/accessor.js | import WindowManager from '../app/windowManager'
import Preference from '../preferences'
import DataCenter from '../dataCenter'
import Keybindings from '../keyboard/shortcutHandler'
import AppMenu from '../menu'
import { loadMenuCommands } from '../menu/actions'
import { CommandManager, loadDefaultCommands } from '../commands'
class Accessor {
/**
* @param {AppEnvironment} appEnvironment The application environment instance.
*/
constructor (appEnvironment) {
const userDataPath = appEnvironment.paths.userDataPath
this.env = appEnvironment
this.paths = appEnvironment.paths // export paths to make it better accessible
this.preferences = new Preference(this.paths)
this.dataCenter = new DataCenter(this.paths)
this.commandManager = CommandManager
this._loadCommands()
this.keybindings = new Keybindings(this.commandManager, appEnvironment)
this.menu = new AppMenu(this.preferences, this.keybindings, userDataPath)
this.windowManager = new WindowManager(this.menu, this.preferences)
}
_loadCommands () {
const { commandManager } = this
loadDefaultCommands(commandManager)
loadMenuCommands(commandManager)
if (this.env.isDevMode) {
commandManager.__verifyDefaultCommands()
}
}
}
export default Accessor
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/app/env.js | src/main/app/env.js | import path from 'path'
import AppPaths, { ensureAppDirectoriesSync } from './paths'
let envId = 0
const patchEnvPath = () => {
if (process.platform === 'darwin') {
process.env.PATH += (process.env.PATH.endsWith(path.delimiter) ? '' : path.delimiter) + '/Library/TeX/texbin'
}
}
export class AppEnvironment {
constructor (options) {
this._id = envId++
this._appPaths = new AppPaths(options.userDataPath)
this._debug = !!options.debug
this._isDevMode = !!options.isDevMode
this._verbose = !!options.verbose
this._safeMode = !!options.safeMode
this._disableSpellcheck = !!options.disableSpellcheck
}
/**
* Returns an unique identifier that can be used with IPC to identify messages from this environment.
*
* @returns {number} Returns an unique identifier.
*/
get id () {
return this._id
}
/**
* @returns {AppPaths}
*/
get paths () {
return this._appPaths
}
/**
* @returns {boolean}
*/
get debug () {
return this._debug
}
/**
* @returns {boolean}
*/
get isDevMode () {
return this._isDevMode
}
/**
* @returns {boolean}
*/
get verbose () {
return this._verbose
}
/**
* @returns {boolean}
*/
get safeMode () {
return this._safeMode
}
/**
* @returns {boolean}
*/
get disableSpellcheck () {
return this._disableSpellcheck
}
}
/**
* Create a (global) application environment instance and bootstraps the application.
*
* @param {arg.Result} args The parsed application arguments.
* @returns {AppEnvironment} The current (global) environment.
*/
const setupEnvironment = args => {
patchEnvPath()
const isDevMode = process.env.NODE_ENV !== 'production'
const debug = args['--debug'] || !!process.env.MARKTEXT_DEBUG || process.env.NODE_ENV !== 'production'
const verbose = args['--verbose'] || 0
const safeMode = args['--safe']
const userDataPath = args['--user-data-dir'] // or null (= default user data path)
const disableSpellcheck = args['--disable-spellcheck']
const appEnvironment = new AppEnvironment({
debug,
isDevMode,
verbose,
safeMode,
userDataPath,
disableSpellcheck
})
ensureAppDirectoriesSync(appEnvironment.paths)
// Keep this for easier access.
global.MARKTEXT_DEBUG = debug
global.MARKTEXT_DEBUG_VERBOSE = verbose
global.MARKTEXT_SAFE_MODE = safeMode
return appEnvironment
}
export default setupEnvironment
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/app/index.js | src/main/app/index.js | import path from 'path'
import fsPromises from 'fs/promises'
import { exec } from 'child_process'
import dayjs from 'dayjs'
import log from 'electron-log'
import { app, BrowserWindow, clipboard, dialog, ipcMain, nativeTheme, shell } from 'electron'
import { isChildOfDirectory } from 'common/filesystem/paths'
import { isLinux, isOsx, isWindows } from '../config'
import parseArgs from '../cli/parser'
import { normalizeAndResolvePath } from '../filesystem'
import { normalizeMarkdownPath } from '../filesystem/markdown'
import { registerKeyboardListeners } from '../keyboard'
import { selectTheme } from '../menu/actions/theme'
import { dockMenu } from '../menu/templates'
import registerSpellcheckerListeners from '../spellchecker'
import { watchers } from '../utils/imagePathAutoComplement'
import { WindowType } from '../windows/base'
import EditorWindow from '../windows/editor'
import SettingWindow from '../windows/setting'
class App {
/**
* @param {Accessor} accessor The application accessor for application instances.
* @param {arg.Result} args Parsed application arguments.
*/
constructor (accessor, args) {
this._accessor = accessor
this._args = args || { _: [] }
this._openFilesCache = []
this._openFilesTimer = null
this._windowManager = this._accessor.windowManager
// this.launchScreenshotWin = null // The window which call the screenshot.
// this.shortcutCapture = null
this._listenForIpcMain()
}
/**
* The entry point into the application.
*/
init () {
// Enable these features to use `backdrop-filter` css rules!
if (isOsx) {
app.commandLine.appendSwitch('enable-experimental-web-platform-features', 'true')
}
app.on('second-instance', (event, argv, workingDirectory) => {
const { _openFilesCache, _windowManager } = this
const args = parseArgs(argv.slice(1))
const buf = []
for (const pathname of args._) {
// Ignore all unknown flags
if (pathname.startsWith('--')) {
continue
}
const info = normalizeMarkdownPath(path.resolve(workingDirectory, pathname))
if (info) {
buf.push(info)
}
}
if (args['--new-window']) {
this._openPathList(buf, true)
return
}
_openFilesCache.push(...buf)
if (_openFilesCache.length) {
this._openFilesToOpen()
} else {
const activeWindow = _windowManager.getActiveWindow()
if (activeWindow) {
activeWindow.bringToFront()
}
}
})
app.on('open-file', this.openFile) // macOS only
app.on('ready', this.ready)
app.on('window-all-closed', () => {
// Close all the image path watcher
for (const watcher of watchers.values()) {
watcher.close()
}
this._windowManager.closeWatcher()
if (!isOsx) {
app.quit()
}
})
app.on('activate', () => { // macOS only
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (this._windowManager.windowCount === 0) {
this.ready()
}
})
// Prevent to load webview and opening links or new windows via HTML/JS.
app.on('web-contents-created', (event, contents) => {
contents.on('will-attach-webview', event => {
event.preventDefault()
})
contents.on('will-navigate', event => {
event.preventDefault()
})
contents.setWindowOpenHandler(details => {
return { action: 'deny' }
})
})
}
async getScreenshotFileName () {
const screenshotFolderPath = await this._accessor.dataCenter.getItem('screenshotFolderPath')
const fileName = `${dayjs().format('YYYY-MM-DD-HH-mm-ss')}-screenshot.png`
return path.join(screenshotFolderPath, fileName)
}
ready = () => {
const { _args: args, _openFilesCache } = this
const { preferences } = this._accessor
if (args._.length) {
for (const pathname of args._) {
// Ignore all unknown flags
if (pathname.startsWith('--')) {
continue
}
const info = normalizeMarkdownPath(pathname)
if (info) {
_openFilesCache.push(info)
}
}
}
const {
startUpAction,
defaultDirectoryToOpen,
autoSwitchTheme,
theme
} = preferences.getAll()
if (startUpAction === 'folder' && defaultDirectoryToOpen) {
const info = normalizeMarkdownPath(defaultDirectoryToOpen)
if (info) {
_openFilesCache.unshift(info)
}
}
// Set initial native theme for theme in preferences.
const isDarkTheme = /dark/i.test(theme)
if (autoSwitchTheme === 0 && isDarkTheme !== nativeTheme.shouldUseDarkColors) {
selectTheme(nativeTheme.shouldUseDarkColors ? 'dark' : 'light')
nativeTheme.themeSource = nativeTheme.shouldUseDarkColors ? 'dark' : 'light'
} else {
nativeTheme.themeSource = isDarkTheme ? 'dark' : 'light'
}
let isDarkMode = nativeTheme.shouldUseDarkColors
ipcMain.on('broadcast-preferences-changed', change => {
// Set Chromium's color for native elements after theme change.
if (change.theme) {
const isDarkTheme = /dark/i.test(change.theme)
if (isDarkMode !== isDarkTheme) {
isDarkMode = isDarkTheme
nativeTheme.themeSource = isDarkTheme ? 'dark' : 'light'
} else if (nativeTheme.themeSource === 'system') {
// Need to set dark or light theme because we set `system` to get the current system theme.
nativeTheme.themeSource = isDarkMode ? 'dark' : 'light'
}
}
})
if (isOsx) {
app.dock.setMenu(dockMenu)
} else if (isWindows) {
app.setJumpList([{
type: 'recent'
}, {
type: 'tasks',
items: [{
type: 'task',
title: 'New Window',
description: 'Opens a new window',
program: process.execPath,
args: '--new-window',
iconPath: process.execPath,
iconIndex: 0
}]
}])
}
if (_openFilesCache.length) {
this._openFilesToOpen()
} else {
this._createEditorWindow()
}
// this.shortcutCapture = new ShortcutCapture()
// if (process.env.NODE_ENV === 'development') {
// this.shortcutCapture.dirname = path.resolve(path.join(__dirname, '../../../node_modules/shortcut-capture'))
// }
// this.shortcutCapture.on('capture', async ({ dataURL }) => {
// const { screenshotFileName } = this
// const image = nativeImage.createFromDataURL(dataURL)
// const bufferImage = image.toPNG()
// if (this.launchScreenshotWin) {
// this.launchScreenshotWin.webContents.send('mt::screenshot-captured')
// this.launchScreenshotWin = null
// }
// try {
// // write screenshot image into screenshot folder.
// await fse.writeFile(screenshotFileName, bufferImage)
// } catch (err) {
// log.error(err)
// }
// })
}
openFile = (event, pathname) => {
event.preventDefault()
const info = normalizeMarkdownPath(pathname)
if (info) {
this._openFilesCache.push(info)
if (app.isReady()) {
// It might come more files
if (this._openFilesTimer) {
clearTimeout(this._openFilesTimer)
}
this._openFilesTimer = setTimeout(() => {
this._openFilesTimer = null
this._openFilesToOpen()
}, 100)
}
}
}
// --- private --------------------------------
/**
* Creates a new editor window.
*
* @param {string} [rootDirectory] The root directory to open.
* @param {string[]} [fileList] A list of markdown files to open.
* @param {string[]} [markdownList] Array of markdown data to open.
* @param {*} [options] The BrowserWindow options.
* @returns {EditorWindow} The created editor window.
*/
_createEditorWindow (rootDirectory = null, fileList = [], markdownList = [], options = {}) {
const editor = new EditorWindow(this._accessor)
editor.createWindow(rootDirectory, fileList, markdownList, options)
this._windowManager.add(editor)
if (this._windowManager.windowCount === 1) {
this._accessor.menu.setActiveWindow(editor.id)
}
return editor
}
/**
* Create a new setting window.
*/
_createSettingWindow (category) {
const setting = new SettingWindow(this._accessor)
setting.createWindow(category)
this._windowManager.add(setting)
if (this._windowManager.windowCount === 1) {
this._accessor.menu.setActiveWindow(setting.id)
}
}
_openFilesToOpen () {
this._openPathList(this._openFilesCache, false)
}
/**
* Open the path list in the best window(s).
*
* @param {string[]} pathsToOpen The path list to open.
* @param {boolean} openFilesInSameWindow Open all files in the same window with
* the first directory and discard other directories.
*/
_openPathList (pathsToOpen, openFilesInSameWindow = false) {
const { _windowManager } = this
const openFilesInNewWindow = this._accessor.preferences.getItem('openFilesInNewWindow')
const fileSet = new Set()
const directorySet = new Set()
for (const { isDir, path } of pathsToOpen) {
if (isDir) {
directorySet.add(path)
} else {
fileSet.add(path)
}
}
// Filter out directories that are already opened.
for (const window of _windowManager.windows.values()) {
if (window.type === WindowType.EDITOR) {
const { openedRootDirectory } = window
if (directorySet.has(openedRootDirectory)) {
window.bringToFront()
directorySet.delete(openedRootDirectory)
}
}
}
const directoriesToOpen = Array.from(directorySet).map(dir => ({ rootDirectory: dir, fileList: [] }))
const filesToOpen = Array.from(fileSet)
// Discard all directories except first one and add files.
if (openFilesInSameWindow) {
if (directoriesToOpen.length) {
directoriesToOpen[0].fileList.push(...filesToOpen)
directoriesToOpen.length = 1
} else {
directoriesToOpen.push({ rootDirectory: null, fileList: [...filesToOpen] })
}
filesToOpen.length = 0
}
// Find the best window(s) to open the files in.
if (!openFilesInSameWindow && !openFilesInNewWindow) {
const isFirstWindow = _windowManager.getActiveEditorId() === null
// Prefer new directories
for (let i = 0; i < directoriesToOpen.length; ++i) {
const { fileList, rootDirectory } = directoriesToOpen[i]
let breakOuterLoop = false
for (let j = 0; j < filesToOpen.length; ++j) {
const pathname = filesToOpen[j]
if (isChildOfDirectory(rootDirectory, pathname)) {
if (isFirstWindow) {
fileList.push(...filesToOpen)
filesToOpen.length = 0
breakOuterLoop = true
break
}
fileList.push(pathname)
filesToOpen.splice(j, 1)
--j
}
}
if (breakOuterLoop) {
break
}
}
// Find for the remaining files the best window to open the files in.
if (isFirstWindow && directoriesToOpen.length && filesToOpen.length) {
const { fileList } = directoriesToOpen[0]
fileList.push(...filesToOpen)
filesToOpen.length = 0
} else {
const windowList = _windowManager.findBestWindowToOpenIn(filesToOpen)
for (const item of windowList) {
const { windowId, fileList } = item
// File list is empty when all files are already opened.
if (fileList.length === 0) {
continue
}
if (windowId !== null) {
const window = _windowManager.get(windowId)
if (window) {
window.openTabsFromPaths(fileList)
window.bringToFront()
continue
}
// else: fallthrough
}
this._createEditorWindow(null, fileList)
}
}
// Directores are always opened in a new window if not already opened.
for (const item of directoriesToOpen) {
const { rootDirectory, fileList } = item
this._createEditorWindow(rootDirectory, fileList)
}
} else {
// Open each file and directory in a new window.
for (const pathname of filesToOpen) {
this._createEditorWindow(null, [pathname])
}
for (const item of directoriesToOpen) {
const { rootDirectory, fileList } = item
this._createEditorWindow(rootDirectory, fileList)
}
}
// Empty the file list
pathsToOpen.length = 0
}
_openSettingsWindow (category) {
const settingWins = this._windowManager.getWindowsByType(WindowType.SETTINGS)
if (settingWins.length >= 1) {
// A setting window is already created
const browserSettingWindow = settingWins[0].win.browserWindow
browserSettingWindow.webContents.send('settings::change-tab', category)
if (isLinux) {
browserSettingWindow.focus()
} else {
browserSettingWindow.moveTop()
}
return
}
this._createSettingWindow(category)
}
_listenForIpcMain () {
registerKeyboardListeners()
registerSpellcheckerListeners()
ipcMain.on('app-create-editor-window', () => {
this._createEditorWindow()
})
ipcMain.on('screen-capture', async win => {
if (isOsx) {
// Use macOs `screencapture` command line when in macOs system.
const screenshotFileName = await this.getScreenshotFileName()
exec('screencapture -i -c', async (err) => {
if (err) {
log.error(err)
return
}
try {
// Write screenshot image into screenshot folder.
const image = clipboard.readImage()
const bufferImage = image.toPNG()
await fsPromises.writeFile(screenshotFileName, bufferImage)
} catch (err) {
log.error(err)
}
win.webContents.send('mt::screenshot-captured')
})
} else {
// TODO: Do nothing, maybe we'll add screenCapture later on Linux and Windows.
// if (this.shortcutCapture) {
// this.launchScreenshotWin = win
// this.shortcutCapture.shortcutCapture()
// }
}
})
ipcMain.on('app-create-settings-window', category => {
this._openSettingsWindow(category)
})
ipcMain.on('app-open-file-by-id', (windowId, filePath) => {
const openFilesInNewWindow = this._accessor.preferences.getItem('openFilesInNewWindow')
if (openFilesInNewWindow) {
this._createEditorWindow(null, [filePath])
} else {
const editor = this._windowManager.get(windowId)
if (editor) {
editor.openTab(filePath, {}, true)
}
}
})
ipcMain.on('app-open-files-by-id', (windowId, fileList) => {
const openFilesInNewWindow = this._accessor.preferences.getItem('openFilesInNewWindow')
if (openFilesInNewWindow) {
this._createEditorWindow(null, fileList)
} else {
const editor = this._windowManager.get(windowId)
if (editor) {
editor.openTabsFromPaths(
fileList.map(p => normalizeMarkdownPath(p))
.filter(i => i && !i.isDir)
.map(i => i.path))
}
}
})
ipcMain.on('app-open-markdown-by-id', (windowId, data) => {
const openFilesInNewWindow = this._accessor.preferences.getItem('openFilesInNewWindow')
if (openFilesInNewWindow) {
this._createEditorWindow(null, [], [data])
} else {
const editor = this._windowManager.get(windowId)
if (editor) {
editor.openUntitledTab(true, data)
}
}
})
ipcMain.on('app-open-directory-by-id', (windowId, pathname, openInSameWindow) => {
const { openFolderInNewWindow } = this._accessor.preferences.getAll()
if (openInSameWindow || !openFolderInNewWindow) {
const editor = this._windowManager.get(windowId)
if (editor) {
editor.openFolder(pathname)
return
}
}
this._createEditorWindow(pathname)
})
// --- renderer -------------------
ipcMain.on('mt::app-try-quit', () => {
app.quit()
})
ipcMain.on('mt::open-file-by-window-id', (e, windowId, filePath) => {
const resolvedPath = normalizeAndResolvePath(filePath)
const openFilesInNewWindow = this._accessor.preferences.getItem('openFilesInNewWindow')
if (openFilesInNewWindow) {
this._createEditorWindow(null, [resolvedPath])
} else {
const editor = this._windowManager.get(windowId)
if (editor) {
editor.openTab(resolvedPath, {}, true)
}
}
})
ipcMain.on('mt::select-default-directory-to-open', async e => {
const { preferences } = this._accessor
const { defaultDirectoryToOpen } = preferences.getAll()
const win = BrowserWindow.fromWebContents(e.sender)
const { filePaths } = await dialog.showOpenDialog(win, {
defaultPath: defaultDirectoryToOpen,
properties: ['openDirectory', 'createDirectory']
})
if (filePaths && filePaths[0]) {
preferences.setItems({ defaultDirectoryToOpen: filePaths[0] })
}
})
ipcMain.on('mt::open-setting-window', () => {
this._openSettingsWindow()
})
ipcMain.on('mt::make-screenshot', e => {
const win = BrowserWindow.fromWebContents(e.sender)
ipcMain.emit('screen-capture', win)
})
ipcMain.on('mt::request-keybindings', e => {
const win = BrowserWindow.fromWebContents(e.sender)
const { keybindings } = this._accessor
// Convert map to object
win.webContents.send('mt::keybindings-response', Object.fromEntries(keybindings.keys))
})
ipcMain.on('mt::open-keybindings-config', () => {
const { keybindings } = this._accessor
keybindings.openConfigInFileManager()
})
ipcMain.handle('mt::keybinding-get-pref-keybindings', () => {
const { keybindings } = this._accessor
const defaultKeybindings = keybindings.getDefaultKeybindings()
const userKeybindings = keybindings.getUserKeybindings()
return { defaultKeybindings, userKeybindings }
})
ipcMain.handle('mt::keybinding-save-user-keybindings', async (event, userKeybindings) => {
const { keybindings } = this._accessor
return keybindings.setUserKeybindings(userKeybindings)
})
ipcMain.handle('mt::fs-trash-item', async (event, fullPath) => {
return shell.trashItem(fullPath)
})
}
}
export default App
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/app/windowManager.js | src/main/app/windowManager.js | import { app, BrowserWindow, ipcMain } from 'electron'
import EventEmitter from 'events'
import log from 'electron-log'
import Watcher, { WATCHER_STABILITY_THRESHOLD, WATCHER_STABILITY_POLL_INTERVAL } from '../filesystem/watcher'
import { WindowType } from '../windows/base'
class WindowActivityList {
constructor () {
// Oldest Newest
// <number>, ... , <number>
this._buf = []
}
getNewest () {
const { _buf } = this
if (_buf.length) {
return _buf[_buf.length - 1]
}
return null
}
getSecondNewest () {
const { _buf } = this
if (_buf.length >= 2) {
return _buf[_buf.length - 2]
}
return null
}
setNewest (id) {
// I think we do not need a linked list for only a few windows.
const { _buf } = this
const index = _buf.indexOf(id)
if (index !== -1) {
const lastIndex = _buf.length - 1
if (index === lastIndex) {
return
}
_buf.splice(index, 1)
}
_buf.push(id)
}
delete (id) {
const { _buf } = this
const index = _buf.indexOf(id)
if (index !== -1) {
_buf.splice(index, 1)
}
}
}
class WindowManager extends EventEmitter {
/**
*
* @param {AppMenu} appMenu The application menu instance.
* @param {Preference} preferences The preference instance.
*/
constructor (appMenu, preferences) {
super()
this._appMenu = appMenu
this._activeWindowId = null
this._windows = new Map()
this._windowActivity = new WindowActivityList()
// TODO(need::refactor): Please see #1035.
this._watcher = new Watcher(preferences)
this._listenForIpcMain()
}
/**
* Add the given window to the window list.
*
* @param {IApplicationWindow} window The application window. We take ownership!
*/
add (window) {
const { id: windowId } = window
this._windows.set(windowId, window)
if (!this._appMenu.has(windowId)) {
this._appMenu.addDefaultMenu(windowId)
}
if (this.windowCount === 1) {
this.setActiveWindow(windowId)
}
window.on('window-focus', () => {
this.setActiveWindow(windowId)
})
window.on('window-closed', () => {
this.remove(windowId)
this._watcher.unwatchByWindowId(windowId)
})
}
/**
* Return the application window by id.
*
* @param {string} windowId The window id.
* @returns {BaseWindow} The application window or undefined.
*/
get (windowId) {
return this._windows.get(windowId)
}
/**
* Return the BrowserWindow by id.
*
* @param {string} windowId The window id.
* @returns {Electron.BrowserWindow} The window or undefined.
*/
getBrowserWindow (windowId) {
const window = this.get(windowId)
if (window) {
return window.browserWindow
}
return undefined
}
/**
* Remove the given window by id.
*
* NOTE: All window "window-focus" events listeners are removed!
*
* @param {string} windowId The window id.
* @returns {IApplicationWindow} Returns the application window. We no longer take ownership.
*/
remove (windowId) {
const { _windows } = this
const window = this.get(windowId)
if (window) {
window.removeAllListeners('window-focus')
this._windowActivity.delete(windowId)
const nextWindowId = this._windowActivity.getNewest()
this.setActiveWindow(nextWindowId)
_windows.delete(windowId)
}
return window
}
setActiveWindow (windowId) {
if (this._activeWindowId !== windowId) {
this._activeWindowId = windowId
this._windowActivity.setNewest(windowId)
if (windowId != null) {
// windowId is null when all windows are closed (e.g. when gracefully closed).
this._appMenu.setActiveWindow(windowId)
}
this.emit('activeWindowChanged', windowId)
}
}
/**
* Returns the active window or null if no window is registered.
* @returns {BaseWindow|undefined}
*/
getActiveWindow () {
return this._windows.get(this._activeWindowId)
}
/**
* Returns the active window id or null if no window is registered.
* @returns {number|null}
*/
getActiveWindowId () {
return this._activeWindowId
}
/**
* Returns the (last) active editor window or null if no editor is registered.
* @returns {EditorWindow|undefined}
*/
getActiveEditor () {
let win = this.getActiveWindow()
if (win && win.type !== WindowType.EDITOR) {
win = this._windows.get(this._windowActivity.getSecondNewest())
if (win && win.type === WindowType.EDITOR) {
return win
}
return undefined
}
return win
}
/**
* Returns the (last) active editor window id or null if no editor is registered.
* @returns {number|null}
*/
getActiveEditorId () {
const win = this.getActiveEditor()
return win ? win.id : null
}
/**
*
* @param {WindowType} type the WindowType one of ['base', 'editor', 'settings']
* @returns {{id: number, win: BaseWindow}[]} Return the windows of the given {type}
*/
getWindowsByType (type) {
if (!WindowType[type.toUpperCase()]) {
console.error(`"${type}" is not a valid window type.`)
}
const { windows } = this
const result = []
for (const [key, value] of windows) {
if (value.type === type) {
result.push({
id: key,
win: value
})
}
}
return result
}
/**
* Find the best window to open the files in.
*
* @param {string[]} fileList File full paths.
* @returns {{windowId: string, fileList: string[]}[]} An array of files mapped to a window id or null to open in a new window.
*/
findBestWindowToOpenIn (fileList) {
if (!fileList || !Array.isArray(fileList) || !fileList.length) return []
const { windows } = this
const lastActiveEditorId = this.getActiveEditorId() // editor id or null
if (this.windowCount <= 1) {
return [{ windowId: lastActiveEditorId, fileList }]
}
// Array of scores, same order like fileList.
let filePathScores = null
for (const window of windows.values()) {
if (window.type === WindowType.EDITOR) {
const scores = window.getCandidateScores(fileList)
if (!filePathScores) {
filePathScores = scores
} else {
const len = filePathScores.length
for (let i = 0; i < len; ++i) {
// Update score only if the file is not already opened.
if (filePathScores[i].score !== -1 && filePathScores[i].score < scores[i].score) {
filePathScores[i] = scores[i]
}
}
}
}
}
const buf = []
const len = filePathScores.length
for (let i = 0; i < len; ++i) {
let { id: windowId, score } = filePathScores[i]
if (score === -1) {
// Skip files that already opened.
continue
} else if (score === 0) {
// There is no best window to open the file(s) in.
windowId = lastActiveEditorId
}
let item = buf.find(w => w.windowId === windowId)
if (!item) {
item = { windowId, fileList: [] }
buf.push(item)
}
item.fileList.push(fileList[i])
}
return buf
}
get windows () {
return this._windows
}
get windowCount () {
return this._windows.size
}
// --- helper ---------------------------------
closeWatcher () {
this._watcher.close()
}
/**
* Closes the browser window and associated application window without asking to save documents.
*
* @param {Electron.BrowserWindow} browserWindow The browser window.
*/
forceClose (browserWindow) {
if (!browserWindow) {
return false
}
const { id: windowId } = browserWindow
const { _appMenu, _windows } = this
// Free watchers used by this window
this._watcher.unwatchByWindowId(windowId)
// Application clearup and remove listeners
_appMenu.removeWindowMenu(windowId)
const window = this.remove(windowId)
// Destroy window wrapper and browser window
if (window) {
window.destroy()
} else {
log.error('Something went wrong: Cannot find associated application window!')
browserWindow.destroy()
}
// Quit application on macOS if not windows are opened.
if (_windows.size === 0) {
app.quit()
}
return true
}
/**
* Closes the application window and associated browser window without asking to save documents.
*
* @param {number} windowId The application window or browser window id.
*/
forceCloseById (windowId) {
const browserWindow = this.getBrowserWindow(windowId)
if (browserWindow) {
return this.forceClose(browserWindow)
}
return false
}
// --- private --------------------------------
_listenForIpcMain () {
// HACK: Don't use this event! Please see #1034 and #1035
ipcMain.on('mt::window-add-file-path', (e, filePath) => {
const win = BrowserWindow.fromWebContents(e.sender)
const editor = this.get(win.id)
if (!editor) {
log.error(`Cannot find window id "${win.id}" to add opened file.`)
return
}
editor.addToOpenedFiles(filePath)
})
// Force close a BrowserWindow
ipcMain.on('mt::close-window', e => {
const win = BrowserWindow.fromWebContents(e.sender)
this.forceClose(win)
})
ipcMain.on('mt::open-file', (e, filePath, options) => {
const win = BrowserWindow.fromWebContents(e.sender)
const editor = this.get(win.id)
if (!editor) {
log.error(`Cannot find window id "${win.id}" to open file.`)
return
}
editor.openTab(filePath, options, true)
})
ipcMain.on('mt::window-tab-closed', (e, pathname) => {
const win = BrowserWindow.fromWebContents(e.sender)
const editor = this.get(win.id)
if (editor) {
editor.removeFromOpenedFiles(pathname)
}
})
ipcMain.on('mt::window-toggle-always-on-top', e => {
const win = BrowserWindow.fromWebContents(e.sender)
const flag = !win.isAlwaysOnTop()
win.setAlwaysOnTop(flag)
this._appMenu.updateAlwaysOnTopMenu(win.id, flag)
})
// --- local events ---------------
ipcMain.on('watcher-unwatch-all-by-id', windowId => {
this._watcher.unwatchByWindowId(windowId)
})
ipcMain.on('watcher-watch-file', (win, filePath) => {
this._watcher.watch(win, filePath, 'file')
})
ipcMain.on('watcher-watch-directory', (win, pathname) => {
this._watcher.watch(win, pathname, 'dir')
})
ipcMain.on('watcher-unwatch-file', (win, filePath) => {
this._watcher.unwatch(win, filePath, 'file')
})
ipcMain.on('watcher-unwatch-directory', (win, pathname) => {
this._watcher.unwatch(win, pathname, 'dir')
})
ipcMain.on('window-add-file-path', (windowId, filePath) => {
const editor = this.get(windowId)
if (!editor) {
log.error(`Cannot find window id "${windowId}" to add opened file.`)
return
}
editor.addToOpenedFiles(filePath)
})
ipcMain.on('window-change-file-path', (windowId, pathname, oldPathname) => {
const editor = this.get(windowId)
if (!editor) {
log.error(`Cannot find window id "${windowId}" to change file path.`)
return
}
editor.changeOpenedFilePath(pathname, oldPathname)
})
ipcMain.on('window-file-saved', (windowId, pathname) => {
// A changed event is emitted earliest after the stability threshold.
const duration = WATCHER_STABILITY_THRESHOLD + (WATCHER_STABILITY_POLL_INTERVAL * 2)
this._watcher.ignoreChangedEvent(windowId, pathname, duration)
})
ipcMain.on('window-close-by-id', id => {
this.forceCloseById(id)
})
ipcMain.on('window-reload-by-id', id => {
const window = this.get(id)
if (window) {
window.reload()
}
})
ipcMain.on('window-toggle-always-on-top', win => {
const flag = !win.isAlwaysOnTop()
win.setAlwaysOnTop(flag)
this._appMenu.updateAlwaysOnTopMenu(win.id, flag)
})
ipcMain.on('broadcast-preferences-changed', prefs => {
// We can not dynamic change the title bar style, so do not need to send it to renderer.
if (typeof prefs.titleBarStyle !== 'undefined') {
delete prefs.titleBarStyle
}
if (Object.keys(prefs).length > 0) {
for (const { browserWindow } of this._windows.values()) {
browserWindow.webContents.send('mt::user-preference', prefs)
}
}
})
ipcMain.on('broadcast-user-data-changed', userData => {
for (const { browserWindow } of this._windows.values()) {
browserWindow.webContents.send('mt::user-preference', userData)
}
})
}
}
export default WindowManager
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/app/paths.js | src/main/app/paths.js | import { app } from 'electron'
import EnvPaths from 'common/envPaths'
import { ensureDirSync } from 'common/filesystem'
class AppPaths extends EnvPaths {
/**
* Configure and sets all application paths.
*
* @param {[string]} userDataPath The user data path or null.
*/
constructor (userDataPath = '') {
if (!userDataPath) {
// Use default user data path.
userDataPath = app.getPath('userData')
}
// Initialize environment paths
super(userDataPath)
// Changing the user data directory is only allowed during application bootstrap.
app.setPath('userData', this._electronUserDataPath)
}
}
export const ensureAppDirectoriesSync = paths => {
ensureDirSync(paths.userDataPath)
ensureDirSync(paths.logPath)
// TODO(sessions): enable this...
// ensureDirSync(paths.electronUserDataPath)
// ensureDirSync(paths.globalStorage)
// ensureDirSync(paths.preferencesPath)
// ensureDirSync(paths.sessionsPath)
}
export default AppPaths
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/contextMenu/editor/spellcheck.js | src/main/contextMenu/editor/spellcheck.js | import { ipcMain, MenuItem } from 'electron'
import log from 'electron-log'
import { isOsx } from '../../config'
import { addToDictionary } from '../../spellchecker'
import { SEPARATOR } from './menuItems'
/**
* Build the spell checker menu depending on input.
*
* @param {boolean} isMisspelled Whether a the selected word is misspelled.
* @param {[string]} misspelledWord The selected word.
* @param {[string[]]} wordSuggestions Suggestions for `selectedWord`.
* @returns {MenuItem[]}
*/
export default (isMisspelled, misspelledWord, wordSuggestions) => {
const spellingSubmenu = []
spellingSubmenu.push(new MenuItem({
label: 'Change Language...',
// NB: On macOS the OS spell checker is used and will detect the language automatically.
visible: !isOsx,
click (menuItem, targetWindow) {
targetWindow.webContents.send('mt::spelling-show-switch-language')
}
}))
// Handle misspelled word if wordSuggestions is set, otherwise word is correct.
if (isMisspelled && misspelledWord && wordSuggestions) {
spellingSubmenu.push({
label: 'Add to Dictionary',
click (menuItem, targetWindow) {
if (!addToDictionary(targetWindow, misspelledWord)) {
log.error(`Error while adding "${misspelledWord}" to dictionary.`)
return
}
// Need to notify Chromium to invalidate the spelling underline.
targetWindow.webContents.replaceMisspelling(misspelledWord)
}
})
if (wordSuggestions.length > 0) {
spellingSubmenu.push(SEPARATOR)
for (const word of wordSuggestions) {
spellingSubmenu.push({
label: word,
click (menuItem, targetWindow) {
targetWindow.webContents.send('mt::spelling-replace-misspelling', {
word: misspelledWord,
replacement: word
})
}
})
}
}
} else {
spellingSubmenu.push({
label: 'Edit Dictionary...',
click (menuItem, targetWindow) {
ipcMain.emit('app-create-settings-window', 'spelling')
}
})
}
return spellingSubmenu
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/contextMenu/editor/index.js | src/main/contextMenu/editor/index.js | import { Menu, MenuItem } from 'electron'
import {
CUT,
COPY,
PASTE,
COPY_AS_MARKDOWN,
COPY_AS_HTML,
PASTE_AS_PLAIN_TEXT,
SEPARATOR,
INSERT_BEFORE,
INSERT_AFTER
} from './menuItems'
import spellcheckMenuBuilder from './spellcheck'
const CONTEXT_ITEMS = [INSERT_BEFORE, INSERT_AFTER, SEPARATOR, CUT, COPY, PASTE, SEPARATOR, COPY_AS_MARKDOWN, COPY_AS_HTML, PASTE_AS_PLAIN_TEXT]
const isInsideEditor = params => {
const { isEditable, editFlags, inputFieldType } = params
// WORKAROUND for Electron#32102: `params.spellcheckEnabled` is always false. Try to detect the editor container via other information.
return isEditable && inputFieldType === 'none' && !!editFlags.canEditRichly
}
export const showEditorContextMenu = (win, event, params, isSpellcheckerEnabled) => {
const { isEditable, hasImageContents, selectionText, editFlags, misspelledWord, dictionarySuggestions } = params
// NOTE: We have to get the word suggestions from this event because `webFrame.getWordSuggestions` and
// `webFrame.isWordMisspelled` doesn't work on Windows (Electron#28684).
// Make sure that the request comes from a contenteditable inside the editor container.
if (isInsideEditor(params) && !hasImageContents) {
const hasText = selectionText.trim().length > 0
const canCopy = hasText && editFlags.canCut && editFlags.canCopy
// const canPaste = hasText && editFlags.canPaste
const isMisspelled = isEditable && !!selectionText && !!misspelledWord
const menu = new Menu()
if (isSpellcheckerEnabled) {
const spellingSubmenu = spellcheckMenuBuilder(isMisspelled, misspelledWord, dictionarySuggestions)
menu.append(new MenuItem({
label: 'Spelling...',
submenu: spellingSubmenu
}))
menu.append(new MenuItem(SEPARATOR))
}
[CUT, COPY, COPY_AS_HTML, COPY_AS_MARKDOWN].forEach(item => {
item.enabled = canCopy
})
CONTEXT_ITEMS.forEach(item => {
menu.append(new MenuItem(item))
})
menu.popup([{ window: win, x: event.clientX, y: event.clientY }])
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/contextMenu/editor/menuItems.js | src/main/contextMenu/editor/menuItems.js | // NOTE: This are mutable fields that may change at runtime.
export const CUT = {
label: 'Cut',
id: 'cutMenuItem',
role: 'cut'
}
export const COPY = {
label: 'Copy',
id: 'copyMenuItem',
role: 'copy'
}
export const PASTE = {
label: 'Paste',
id: 'pasteMenuItem',
role: 'paste'
}
export const COPY_AS_MARKDOWN = {
label: 'Copy As Markdown',
id: 'copyAsMarkdownMenuItem',
click (menuItem, targetWindow) {
targetWindow.webContents.send('mt::cm-copy-as-markdown')
}
}
export const COPY_AS_HTML = {
label: 'Copy As Html',
id: 'copyAsHtmlMenuItem',
click (menuItem, targetWindow) {
targetWindow.webContents.send('mt::cm-copy-as-html')
}
}
export const PASTE_AS_PLAIN_TEXT = {
label: 'Paste as Plain Text',
id: 'pasteAsPlainTextMenuItem',
click (menuItem, targetWindow) {
targetWindow.webContents.send('mt::cm-paste-as-plain-text')
}
}
export const INSERT_BEFORE = {
label: 'Insert Paragraph Before',
id: 'insertParagraphBeforeMenuItem',
click (menuItem, targetWindow) {
targetWindow.webContents.send('mt::cm-insert-paragraph', 'before')
}
}
export const INSERT_AFTER = {
label: 'Insert Paragraph After',
id: 'insertParagraphAfterMenuItem',
click (menuItem, targetWindow) {
targetWindow.webContents.send('mt::cm-insert-paragraph', 'after')
}
}
export const SEPARATOR = {
type: 'separator'
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/commands/tab.js | src/main/commands/tab.js | import { COMMANDS } from './index'
const switchToLeftTab = win => {
if (win && win.webContents) {
win.webContents.send('mt::tabs-cycle-left')
}
}
const switchToRightTab = win => {
if (win && win.webContents) {
win.webContents.send('mt::tabs-cycle-right')
}
}
const switchTabByIndex = (win, index) => {
if (win && win.webContents) {
win.webContents.send('mt::switch-tab-by-index', index)
}
}
export const loadTabCommands = commandManager => {
commandManager.add(COMMANDS.TABS_CYCLE_BACKWARD, switchToLeftTab)
commandManager.add(COMMANDS.TABS_CYCLE_FORWARD, switchToRightTab)
commandManager.add(COMMANDS.TABS_SWITCH_TO_LEFT, switchToLeftTab)
commandManager.add(COMMANDS.TABS_SWITCH_TO_RIGHT, switchToRightTab)
commandManager.add(COMMANDS.TABS_SWITCH_TO_FIRST, win => switchTabByIndex(win, 0))
commandManager.add(COMMANDS.TABS_SWITCH_TO_SECOND, win => switchTabByIndex(win, 1))
commandManager.add(COMMANDS.TABS_SWITCH_TO_THIRD, win => switchTabByIndex(win, 2))
commandManager.add(COMMANDS.TABS_SWITCH_TO_FOURTH, win => switchTabByIndex(win, 3))
commandManager.add(COMMANDS.TABS_SWITCH_TO_FIFTH, win => switchTabByIndex(win, 4))
commandManager.add(COMMANDS.TABS_SWITCH_TO_SIXTH, win => switchTabByIndex(win, 5))
commandManager.add(COMMANDS.TABS_SWITCH_TO_SEVENTH, win => switchTabByIndex(win, 6))
commandManager.add(COMMANDS.TABS_SWITCH_TO_EIGHTH, win => switchTabByIndex(win, 7))
commandManager.add(COMMANDS.TABS_SWITCH_TO_NINTH, win => switchTabByIndex(win, 8))
commandManager.add(COMMANDS.TABS_SWITCH_TO_TENTH, win => switchTabByIndex(win, 9))
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/commands/index.js | src/main/commands/index.js | import COMMAND_CONSTANTS from 'common/commands/constants'
import { loadFileCommands } from './file'
import { loadTabCommands } from './tab'
export const COMMANDS = COMMAND_CONSTANTS
export const loadDefaultCommands = commandManager => {
loadFileCommands(commandManager)
loadTabCommands(commandManager)
}
class CommandManager {
constructor () {
this._commands = new Map()
}
add (id, callback) {
const { _commands } = this
if (_commands.has(id)) {
throw new Error(`Command with id="${id}" already exists.`)
}
_commands.set(id, callback)
}
remove (id) {
return this._commands.delete(id)
}
has (id) {
return this._commands.has(id)
}
execute (id, ...args) {
const command = this._commands.get(id)
if (!command) {
throw new Error(`No command found with id="${id}".`)
}
return command(...args)
}
__verifyDefaultCommands () {
const { _commands } = this
Object.keys(COMMANDS).forEach(propertyName => {
const id = COMMANDS[propertyName]
if (!_commands.has(id)) {
console.error(`[DEBUG] Default command with id="${id}" isn't available!`)
}
})
}
}
const commandManagerInstance = new CommandManager()
export { commandManagerInstance as CommandManager }
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/commands/file.js | src/main/commands/file.js | import { COMMANDS } from './index'
const openQuickOpenDialog = win => {
if (win && win.webContents) {
win.webContents.send('mt::execute-command-by-id', 'file.quick-open')
}
}
export const loadFileCommands = commandManager => {
commandManager.add(COMMANDS.FILE_QUICK_OPEN, openQuickOpenDialog)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/utils/createGitHubIssue.js | src/main/utils/createGitHubIssue.js | import { shell } from 'electron'
import { GITHUB_REPO_URL } from '../config'
export const createGitHubIssueUrl = (title, msg) => {
const issueUrl = new URL(`${GITHUB_REPO_URL}/issues/new`)
if (title) {
issueUrl.searchParams.set('title', title)
}
if (msg) {
issueUrl.searchParams.set('body', msg)
}
return issueUrl.toString()
}
export const createAndOpenGitHubIssueUrl = (title, msg) => {
shell.openExternal(createGitHubIssueUrl(title, msg))
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/utils/imagePathAutoComplement.js | src/main/utils/imagePathAutoComplement.js | import fs from 'fs'
import path from 'path'
import { filter } from 'fuzzaldrin'
import log from 'electron-log'
import { isDirectory, isFile } from 'common/filesystem'
import { IMAGE_EXTENSIONS } from 'common/filesystem/paths'
import { BLACK_LIST } from '../config'
// TODO(need::refactor): Refactor this file. Just return an array of directories and files without caching and watching?
// TODO: rebuild cache @jocs
const IMAGE_PATH = new Map()
export const watchers = new Map()
const filesHandler = (files, directory, key) => {
const IMAGE_REG = new RegExp('(' + IMAGE_EXTENSIONS.join('|') + ')$', 'i')
const onlyDirAndImage = files
.map(file => {
const fullPath = path.join(directory, file)
let type = ''
if (isDirectory(fullPath)) {
type = 'directory'
} else if (isFile(fullPath) && IMAGE_REG.test(file)) {
type = 'image'
}
return {
file,
type
}
})
.filter(({
file,
type
}) => {
if (BLACK_LIST.includes(file)) return false
return type === 'directory' || type === 'image'
})
IMAGE_PATH.set(directory, onlyDirAndImage)
if (key !== undefined) {
return filter(onlyDirAndImage, key, {
key: 'file'
})
}
}
const rebuild = (directory) => {
fs.readdir(directory, (err, files) => {
if (err) {
log.error('imagePathAutoComplement::rebuild:', err)
} else {
filesHandler(files, directory)
}
})
}
const watchDirectory = directory => {
if (watchers.has(directory)) return // Do not duplicate watch the same directory
const watcher = fs.watch(directory, (eventType, filename) => {
if (eventType === 'rename') {
rebuild(directory)
}
})
watchers.set(directory, watcher)
}
export const searchFilesAndDir = (directory, key) => {
let result = []
if (IMAGE_PATH.has(directory)) {
result = filter(IMAGE_PATH.get(directory), key, { key: 'file' })
return Promise.resolve(result)
} else {
return new Promise((resolve, reject) => {
fs.readdir(directory, (err, files) => {
if (err) {
reject(err)
} else {
result = filesHandler(files, directory, key)
watchDirectory(directory)
resolve(result)
}
})
})
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/utils/index.js | src/main/utils/index.js | import { app } from 'electron'
const ID_PREFIX = 'mt-'
let id = 0
export const getUniqueId = () => {
return `${ID_PREFIX}${id++}`
}
// TODO: Remove this function and load the recommend title from the editor (renderer) when
// requesting the document to save/export.
export const getRecommendTitleFromMarkdownString = markdown => {
// NOTE: We should read the title from the renderer cache because this regex matches in
// code blocks too.
const tokens = markdown.match(/#{1,6} {1,}(.*\S.*)(?:\n|$)/g)
if (!tokens) return ''
const headers = tokens.map(t => {
const matches = t.trim().match(/(#{1,6}) {1,}(.+)/)
return {
level: matches[1].length,
content: matches[2].trim()
}
})
return headers.sort((a, b) => a.level - b.level)[0].content
}
/**
* Returns a special directory path for the requested name.
*
* NOTE: Do not use "userData" to get the user data path, instead use AppPaths!
*
* @param {string} name The special directory name.
* @returns {string} The resolved special directory path.
*/
export const getPath = name => {
if (name === 'userData') {
throw new Error('Do not use "getPath" for user data path!')
}
return app.getPath(name)
}
export const hasSameKeys = (a, b) => {
const aKeys = Object.keys(a).sort()
const bKeys = Object.keys(b).sort()
return JSON.stringify(aKeys) === JSON.stringify(bKeys)
}
export const getLogLevel = () => {
if (!global.MARKTEXT_DEBUG_VERBOSE || typeof global.MARKTEXT_DEBUG_VERBOSE !== 'number' ||
global.MARKTEXT_DEBUG_VERBOSE <= 0) {
return process.env.NODE_ENV === 'development' ? 'debug' : 'info'
} else if (global.MARKTEXT_DEBUG_VERBOSE === 1) {
return 'verbose'
} else if (global.MARKTEXT_DEBUG_VERBOSE === 2) {
return 'debug'
}
return 'silly' // >= 3
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/utils/pandoc.js | src/main/utils/pandoc.js | // Copy from https://github.com/utatti/simple-pandoc/blob/master/index.js
import { spawn } from 'child_process'
import commandExists from 'command-exists'
import { isFile2 } from 'common/filesystem'
const pandocCommand = 'pandoc'
const getCommand = () => {
if (envPathExists()) {
return process.env.MARKTEXT_PANDOC
}
return pandocCommand
}
const pandoc = (from, to, ...args) => {
const command = getCommand()
const option = ['-s', from, '-t', to].concat(args)
const converter = () => new Promise((resolve, reject) => {
const proc = spawn(command, option)
proc.on('error', reject)
let data = ''
proc.stdout.on('data', chunk => {
data += chunk.toString()
})
proc.stdout.on('end', () => resolve(data))
proc.stdout.on('error', reject)
proc.stdin.end()
})
converter.stream = srcStream => {
const proc = spawn(command, option)
srcStream.pipe(proc.stdin)
return proc.stdout
}
return converter
}
pandoc.exists = () => {
if (envPathExists()) {
return true
}
return commandExists.sync(pandocCommand)
}
const envPathExists = () => {
return !!process.env.MARKTEXT_PANDOC && isFile2(process.env.MARKTEXT_PANDOC)
}
export default pandoc
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/filesystem/index.js | src/main/filesystem/index.js | import fs from 'fs-extra'
import path from 'path'
import { isDirectory, isFile, isSymbolicLink } from 'common/filesystem'
/**
* Normalize the path into an absolute path and resolves the link target if needed.
*
* @param {string} pathname The path or link path.
* @returns {string} Returns the absolute path and resolved link. If the link target
* cannot be resolved, an empty string is returned.
*/
export const normalizeAndResolvePath = pathname => {
if (isSymbolicLink(pathname)) {
const absPath = path.dirname(pathname)
const targetPath = path.resolve(absPath, fs.readlinkSync(pathname))
if (isFile(targetPath) || isDirectory(targetPath)) {
return path.resolve(targetPath)
}
console.error(`Cannot resolve link target "${pathname}" (${targetPath}).`)
return ''
}
return path.resolve(pathname)
}
export const writeFile = (pathname, content, extension, options = 'utf-8') => {
if (!pathname) {
return Promise.reject(new Error('[ERROR] Cannot save file without path.'))
}
pathname = !extension || pathname.endsWith(extension) ? pathname : `${pathname}${extension}`
return fs.outputFile(pathname, content, options)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/filesystem/markdown.js | src/main/filesystem/markdown.js | import fsPromises from 'fs/promises'
import path from 'path'
import log from 'electron-log'
import iconv from 'iconv-lite'
import { LINE_ENDING_REG, LF_LINE_ENDING_REG, CRLF_LINE_ENDING_REG } from '../config'
import { isDirectory2 } from 'common/filesystem'
import { isMarkdownFile } from 'common/filesystem/paths'
import { normalizeAndResolvePath, writeFile } from '../filesystem'
import { guessEncoding } from './encoding'
const getLineEnding = lineEnding => {
if (lineEnding === 'lf') {
return '\n'
} else if (lineEnding === 'crlf') {
return '\r\n'
}
// This should not happend but use fallback value.
log.error(`Invalid end of line character: expected "lf" or "crlf" but got "${lineEnding}".`)
return '\n'
}
const convertLineEndings = (text, lineEnding) => {
return text.replace(LINE_ENDING_REG, getLineEnding(lineEnding))
}
/**
* Special function to normalize directory and markdown file paths.
*
* @param {string} pathname The path to the file or directory.
* @returns {{isDir: boolean, path: string}?} Returns the normalize path and a
* directory hint or null if it's not a directory or markdown file.
*/
export const normalizeMarkdownPath = pathname => {
const isDir = isDirectory2(pathname)
if (isDir || isMarkdownFile(pathname)) {
// Normalize and resolve the path or link target.
const resolved = normalizeAndResolvePath(pathname)
if (resolved) {
return { isDir, path: resolved }
} else {
console.error(`[ERROR] Cannot resolve "${pathname}".`)
}
}
return null
}
/**
* Write the content into a file.
*
* @param {string} pathname The path to the file.
* @param {string} content The buffer to save.
* @param {IMarkdownDocumentOptions} options The markdown document options
*/
export const writeMarkdownFile = (pathname, content, options) => {
const { adjustLineEndingOnSave, lineEnding } = options
const { encoding, isBom } = options.encoding
const extension = path.extname(pathname) || '.md'
if (adjustLineEndingOnSave) {
content = convertLineEndings(content, lineEnding)
}
const buffer = iconv.encode(content, encoding, { addBOM: isBom })
// TODO(@fxha): "safeSaveDocuments" using temporary file and rename syscall.
return writeFile(pathname, buffer, extension, undefined)
}
/**
* Reads the contents of a markdown file.
*
* @param {string} pathname The path to the markdown file.
* @param {string} preferredEol The preferred EOL.
* @param {boolean} autoGuessEncoding Whether we should try to auto guess encoding.
* @param {*} trimTrailingNewline The trim trailing newline option.
* @returns {IMarkdownDocumentRaw} Returns a raw markdown document.
*/
export const loadMarkdownFile = async (pathname, preferredEol, autoGuessEncoding = true, trimTrailingNewline = 2) => {
// TODO: Use streams to not buffer the file multiple times and only guess
// encoding on the first 256/512 bytes.
let buffer = await fsPromises.readFile(path.resolve(pathname))
const encoding = guessEncoding(buffer, autoGuessEncoding)
const supported = iconv.encodingExists(encoding.encoding)
if (!supported) {
throw new Error(`"${encoding.encoding}" encoding is not supported.`)
}
let markdown = iconv.decode(buffer, encoding.encoding)
// Detect line ending
const isLf = LF_LINE_ENDING_REG.test(markdown)
const isCrlf = CRLF_LINE_ENDING_REG.test(markdown)
const isMixedLineEndings = isLf && isCrlf
const isUnknownEnding = !isLf && !isCrlf
let lineEnding = preferredEol
if (isLf && !isCrlf) {
lineEnding = 'lf'
} else if (isCrlf && !isLf) {
lineEnding = 'crlf'
}
let adjustLineEndingOnSave = false
if (isMixedLineEndings || isUnknownEnding || lineEnding !== 'lf') {
adjustLineEndingOnSave = lineEnding !== 'lf'
// Convert to LF for internal use.
markdown = convertLineEndings(markdown, 'lf')
}
// Detect final newline
if (trimTrailingNewline === 2) {
if (!markdown) {
// Use default value
trimTrailingNewline = 3
} else {
const lastIndex = markdown.length - 1
if (lastIndex >= 1 && markdown[lastIndex] === '\n' && markdown[lastIndex - 1] === '\n') {
// Disabled
trimTrailingNewline = 2
} else if (markdown[lastIndex] === '\n') {
// Ensure single trailing newline
trimTrailingNewline = 1
} else {
// Trim trailing newlines
trimTrailingNewline = 0
}
}
}
const filename = path.basename(pathname)
return {
// document information
markdown,
filename,
pathname,
// options
encoding,
lineEnding,
adjustLineEndingOnSave,
trimTrailingNewline,
// raw file information
isMixedLineEndings
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/filesystem/watcher.js | src/main/filesystem/watcher.js | import path from 'path'
import fsPromises from 'fs/promises'
import log from 'electron-log'
import chokidar from 'chokidar'
import { exists } from 'common/filesystem'
import { hasMarkdownExtension } from 'common/filesystem/paths'
import { getUniqueId } from '../utils'
import { loadMarkdownFile } from '../filesystem/markdown'
import { isLinux, isOsx } from '../config'
// TODO(refactor): Please see GH#1035.
export const WATCHER_STABILITY_THRESHOLD = 1000
export const WATCHER_STABILITY_POLL_INTERVAL = 150
const EVENT_NAME = {
dir: 'mt::update-object-tree',
file: 'mt::update-file'
}
const add = async (win, pathname, type, endOfLine, autoGuessEncoding, trimTrailingNewline) => {
const stats = await fsPromises.stat(pathname)
const birthTime = stats.birthtime
const isMarkdown = hasMarkdownExtension(pathname)
const file = {
pathname,
name: path.basename(pathname),
isFile: true,
isDirectory: false,
birthTime,
isMarkdown
}
if (isMarkdown) {
// HACK: But this should be removed completely in #1034/#1035.
try {
const data = await loadMarkdownFile(
pathname,
endOfLine,
autoGuessEncoding,
trimTrailingNewline
)
file.data = data
} catch (err) {
// Only notify user about opened files.
if (type === 'file') {
win.webContents.send('mt::show-notification', {
title: 'Watcher I/O error',
type: 'error',
message: err.message
})
return
}
}
win.webContents.send(EVENT_NAME[type], {
type: 'add',
change: file
})
}
}
const unlink = (win, pathname, type) => {
const file = { pathname }
win.webContents.send(EVENT_NAME[type], {
type: 'unlink',
change: file
})
}
const change = async (win, pathname, type, endOfLine, autoGuessEncoding, trimTrailingNewline) => {
// No need to update the tree view if the file content has changed.
if (type === 'dir') return
const isMarkdown = hasMarkdownExtension(pathname)
if (isMarkdown) {
// HACK: Markdown data should be removed completely in #1034/#1035 and
// should be only loaded after user interaction.
try {
const data = await loadMarkdownFile(
pathname,
endOfLine,
autoGuessEncoding,
trimTrailingNewline
)
const file = {
pathname,
data
}
win.webContents.send('mt::update-file', {
type: 'change',
change: file
})
} catch (err) {
// Only notify user about opened files.
if (type === 'file') {
win.webContents.send('mt::show-notification', {
title: 'Watcher I/O error',
type: 'error',
message: err.message
})
}
}
}
}
const addDir = (win, pathname, type) => {
if (type === 'file') return
const directory = {
pathname,
name: path.basename(pathname),
isCollapsed: true,
isDirectory: true,
isFile: false,
isMarkdown: false,
folders: [],
files: []
}
win.webContents.send('mt::update-object-tree', {
type: 'addDir',
change: directory
})
}
const unlinkDir = (win, pathname, type) => {
if (type === 'file') return
const directory = { pathname }
win.webContents.send('mt::update-object-tree', {
type: 'unlinkDir',
change: directory
})
}
class Watcher {
/**
* @param {Preference} preferences The preference instance.
*/
constructor (preferences) {
this._preferences = preferences
this._ignoreChangeEvents = []
this.watchers = {}
}
// Watch a file or directory and return a unwatch function.
watch (win, watchPath, type = 'dir'/* file or dir */) {
// TODO: Is it needed to set `watcherUsePolling` ? because macOS need to set to true.
const usePolling = isOsx ? true : this._preferences.getItem('watcherUsePolling')
const id = getUniqueId()
const watcher = chokidar.watch(watchPath, {
ignored: (pathname, fileInfo) => {
// This function is called twice, once with a single argument (the path),
// second time with two arguments (the path and the "fs.Stats" object of that path).
if (!fileInfo) {
return /(?:^|[/\\])(?:\..|node_modules|(?:.+\.asar))/.test(pathname)
}
if (/(?:^|[/\\])(?:\..|node_modules|(?:.+\.asar))/.test(pathname)) {
return true
}
if (fileInfo.isDirectory()) {
return false
}
return !hasMarkdownExtension(pathname)
},
ignoreInitial: type === 'file',
persistent: true,
ignorePermissionErrors: true,
// Just to be sure when a file is replaced with a directory don't watch recursively.
depth: type === 'file' ? (isOsx ? 1 : 0) : undefined,
// Please see GH#1043
awaitWriteFinish: {
stabilityThreshold: WATCHER_STABILITY_THRESHOLD,
pollInterval: WATCHER_STABILITY_POLL_INTERVAL
},
// Settings options
usePolling
})
let disposed = false
let enospcReached = false
let renameTimer = null
watcher
.on('add', async pathname => {
if (!await this._shouldIgnoreEvent(win.id, pathname, type, usePolling)) {
const { _preferences } = this
const eol = _preferences.getPreferredEol()
const { autoGuessEncoding, trimTrailingNewline } = _preferences.getAll()
add(win, pathname, type, eol, autoGuessEncoding, trimTrailingNewline)
}
})
.on('change', async pathname => {
if (!await this._shouldIgnoreEvent(win.id, pathname, type, usePolling)) {
const { _preferences } = this
const eol = _preferences.getPreferredEol()
const { autoGuessEncoding, trimTrailingNewline } = _preferences.getAll()
change(win, pathname, type, eol, autoGuessEncoding, trimTrailingNewline)
}
})
.on('unlink', pathname => unlink(win, pathname, type))
.on('addDir', pathname => addDir(win, pathname, type))
.on('unlinkDir', pathname => unlinkDir(win, pathname, type))
.on('raw', (event, subpath, details) => {
if (global.MARKTEXT_DEBUG_VERBOSE >= 3) {
console.log('watcher: ', event, subpath, details)
}
// Fix atomic rename on Linux (chokidar#591).
// TODO: This should also apply to macOS.
// TODO: Do we need to rewatch when the watched directory was renamed?
if (isLinux && type === 'file' && event === 'rename') {
if (renameTimer) {
clearTimeout(renameTimer)
}
renameTimer = setTimeout(async () => {
renameTimer = null
if (disposed) {
return
}
const fileExists = await exists(watchPath)
if (fileExists) {
// File still exists but we need to rewatch the file because the inode has changed.
watcher.unwatch(watchPath)
watcher.add(watchPath)
}
}, 150)
}
})
.on('error', error => {
// Check if too many file descriptors are opened and notify the user about this issue.
if (error.code === 'ENOSPC') {
if (!enospcReached) {
enospcReached = true
log.warn('inotify limit reached: Too many file descriptors are opened.')
win.webContents.send('mt::show-notification', {
title: 'inotify limit reached',
type: 'warning',
message: 'Cannot watch all files and file changes because too many file descriptors are opened.'
})
}
} else {
log.error('Error while watching files:', error)
}
})
const closeFn = () => {
disposed = true
if (this.watchers[id]) {
delete this.watchers[id]
}
if (renameTimer) {
clearTimeout(renameTimer)
renameTimer = null
}
watcher.close()
}
this.watchers[id] = {
win,
watcher,
pathname: watchPath,
type,
close: closeFn
}
// unwatcher function
return closeFn
}
// Remove a single watcher.
unwatch (win, watchPath, type = 'dir') {
for (const id of Object.keys(this.watchers)) {
const w = this.watchers[id]
if (
w.win === win &&
w.pathname === watchPath &&
w.type === type
) {
w.watcher.close()
delete this.watchers[id]
break
}
}
}
// Remove all watchers from the given window id.
unwatchByWindowId (windowId) {
const watchers = []
const watchIds = []
for (const id of Object.keys(this.watchers)) {
const w = this.watchers[id]
if (w.win.id === windowId) {
watchers.push(w.watcher)
watchIds.push(id)
}
}
if (watchers.length) {
watchIds.forEach(id => delete this.watchers[id])
watchers.forEach(watcher => watcher.close())
}
}
close () {
Object.keys(this.watchers).forEach(id => this.watchers[id].close())
this.watchers = {}
this._ignoreChangeEvents = []
}
/**
* Ignore the next changed event within a certain time for the current file and window.
*
* NOTE: Only valid for files and "add"/"change" event!
*
* @param {number} windowId The window id.
* @param {string} pathname The path to ignore.
* @param {number} [duration] The duration in ms to ignore the changed event.
*/
ignoreChangedEvent (windowId, pathname, duration = WATCHER_STABILITY_THRESHOLD + (WATCHER_STABILITY_POLL_INTERVAL * 2)) {
this._ignoreChangeEvents.push({ windowId, pathname, duration, start: new Date() })
}
/**
* Check whether we should ignore the current event because the file may be changed from MarkText itself.
*
* @param {number} winId
* @param {string} pathname
* @param {string} type
* @param {boolean} usePolling
*/
async _shouldIgnoreEvent (winId, pathname, type, usePolling) {
if (type === 'file') {
const { _ignoreChangeEvents } = this
const currentTime = new Date()
for (let i = 0; i < _ignoreChangeEvents.length; ++i) {
const { windowId, pathname: pathToIgnore, start, duration } = _ignoreChangeEvents[i]
if (windowId === winId && pathToIgnore === pathname) {
_ignoreChangeEvents.splice(i, 1)
--i
// Modification origin is the editor and we should ignore the event.
if (currentTime - start < duration) {
return true
}
// Try to catch cloud drives that emit the change event not immediately or re-sync the change (GH#3044).
if (!usePolling) {
try {
const fileInfo = await fsPromises.stat(pathname)
if (fileInfo.mtime - start < duration) {
if (global.MARKTEXT_DEBUG_VERBOSE >= 3) {
console.log(`Ignoring file event after "stat": current="${currentTime}", start="${start}", file="${fileInfo.mtime}".`)
}
return true
}
} catch (error) {
console.error('Failed to "stat" file to determine modification time:', error)
}
}
}
}
}
return false
}
}
export default Watcher
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/filesystem/encoding.js | src/main/filesystem/encoding.js | import ced from 'ced'
const CED_ICONV_ENCODINGS = {
'BIG5-CP950': 'big5',
KSC: 'euckr',
'ISO-2022-KR': 'euckr',
GB: 'gb2312',
ISO_2022_CN: 'gb2312',
JIS: 'shiftjis',
SJS: 'shiftjis',
Unicode: 'utf8',
// Map ASCII to UTF-8
'ASCII-7-bit': 'utf8',
ASCII: 'utf8',
MACINTOSH: 'utf8'
}
// Byte Order Mark's to detect endianness and encoding.
const BOM_ENCODINGS = {
utf8: [0xEF, 0xBB, 0xBF],
utf16be: [0xFE, 0xFF],
utf16le: [0xFF, 0xFE]
}
const checkSequence = (buffer, sequence) => {
if (buffer.length < sequence.length) {
return false
}
return sequence.every((v, i) => v === buffer[i])
}
/**
* Guess the encoding from the buffer.
*
* @param {Buffer} buffer
* @param {boolean} autoGuessEncoding
* @returns {Encoding}
*/
export const guessEncoding = (buffer, autoGuessEncoding) => {
let isBom = false
let encoding = 'utf8'
// Detect UTF8- and UTF16-BOM encodings.
for (const [key, value] of Object.entries(BOM_ENCODINGS)) {
if (checkSequence(buffer, value)) {
return { encoding: key, isBom: true }
}
}
// // Try to detect binary files. Text files should not containt four 0x00 characters.
// let zeroSeenCounter = 0
// for (let i = 0; i < Math.min(buffer.byteLength, 256); ++i) {
// if (buffer[i] === 0x00) {
// if (zeroSeenCounter >= 3) {
// return { encoding: 'binary', isBom: false }
// }
// zeroSeenCounter++
// } else {
// zeroSeenCounter = 0
// }
// }
// Auto guess encoding, otherwise use UTF8.
if (autoGuessEncoding) {
encoding = ced(buffer)
if (CED_ICONV_ENCODINGS[encoding]) {
encoding = CED_ICONV_ENCODINGS[encoding]
} else {
encoding = encoding.toLowerCase().replace(/-_/g, '')
}
}
return { encoding, isBom }
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.