paste-html.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. import { EditorView } from '@codemirror/view'
  2. import { Prec } from '@codemirror/state'
  3. import {
  4. insertPastedContent,
  5. pastedContent,
  6. storePastedContent,
  7. } from './pasted-content'
  8. import { debugConsole } from '@/utils/debugging'
  9. import {
  10. isBlockContainingElement,
  11. isBlockElement,
  12. isElementNode,
  13. isInlineElement,
  14. isTextNode,
  15. shouldRemoveEmptyBlockElement,
  16. } from './html-elements'
  17. export const pasteHtml = [
  18. Prec.highest(
  19. EditorView.domEventHandlers({
  20. paste(event, view) {
  21. const { clipboardData } = event
  22. if (!clipboardData) {
  23. return false
  24. }
  25. // only handle pasted HTML
  26. if (!clipboardData.types.includes('text/html')) {
  27. return false
  28. }
  29. // ignore text/html from VS Code
  30. if (
  31. clipboardData.types.includes('application/vnd.code.copymetadata') ||
  32. clipboardData.types.includes('vscode-editor-data')
  33. ) {
  34. return false
  35. }
  36. const html = clipboardData.getData('text/html').trim()
  37. const text = clipboardData.getData('text/plain').trim()
  38. if (html.length === 0) {
  39. return false
  40. }
  41. // convert the HTML to LaTeX
  42. try {
  43. const parser = new DOMParser()
  44. const { documentElement } = parser.parseFromString(html, 'text/html')
  45. // fall back to creating a figure when there's an image on the clipoard,
  46. // unless the HTML indicates that it came from an Office application
  47. // (which also puts an image on the clipboard)
  48. if (clipboardData.files.length > 0 && !hasProgId(documentElement)) {
  49. return false
  50. }
  51. const bodyElement = documentElement.querySelector('body')
  52. // DOMParser should always create a body element, so this is mostly for TypeScript
  53. if (!bodyElement) {
  54. return false
  55. }
  56. // if the only content is in a code block, use the plain text version
  57. if (onlyCode(bodyElement)) {
  58. return false
  59. }
  60. const latex = htmlToLaTeX(bodyElement)
  61. // if there's no formatting, use the plain text version
  62. if (latex === text && clipboardData.files.length === 0) {
  63. return false
  64. }
  65. view.dispatch(insertPastedContent(view, { latex, text }))
  66. view.dispatch(storePastedContent({ latex, text }, true))
  67. return true
  68. } catch (error) {
  69. debugConsole.error(error)
  70. // fall back to the default paste handler
  71. return false
  72. }
  73. },
  74. })
  75. ),
  76. pastedContent,
  77. ]
  78. const removeUnwantedElements = (
  79. documentElement: HTMLElement,
  80. selector: string
  81. ) => {
  82. for (const element of documentElement.querySelectorAll(selector)) {
  83. element.remove()
  84. }
  85. }
  86. const findCodeContainingElement = (documentElement: HTMLElement) => {
  87. let result: HTMLElement | null
  88. // a code element
  89. result = documentElement.querySelector<HTMLElement>('code')
  90. if (result) {
  91. return result
  92. }
  93. // a pre element with "monospace" somewhere in the font family
  94. result = documentElement.querySelector<HTMLPreElement>('pre')
  95. if (result?.style.fontFamily.includes('monospace')) {
  96. return result
  97. }
  98. return null
  99. }
  100. // return true if the text content of the first <code> element
  101. // is the same as the text content of the whole document element
  102. const onlyCode = (documentElement: HTMLElement) => {
  103. const codeElement = findCodeContainingElement(documentElement)
  104. return (
  105. codeElement?.textContent?.trim() === documentElement.textContent?.trim()
  106. )
  107. }
  108. const hasProgId = (documentElement: HTMLElement) => {
  109. const meta = documentElement.querySelector<HTMLMetaElement>(
  110. 'meta[name="ProgId"]'
  111. )
  112. return meta && meta.content.trim().length > 0
  113. }
  114. const htmlToLaTeX = (bodyElement: HTMLElement) => {
  115. // remove style elements
  116. removeUnwantedElements(bodyElement, 'style')
  117. let before: string | null = null
  118. let after: string | null = null
  119. // repeat until the content stabilises
  120. do {
  121. before = bodyElement.textContent
  122. // normalise whitespace in text
  123. normaliseWhitespace(bodyElement)
  124. // replace unwanted whitespace in blocks
  125. processWhitespaceInBlocks(bodyElement)
  126. after = bodyElement.textContent
  127. } while (before !== after)
  128. // pre-process table elements
  129. processTables(bodyElement)
  130. // pre-process lists
  131. processLists(bodyElement)
  132. // protect special characters in non-LaTeX text nodes
  133. protectSpecialCharacters(bodyElement)
  134. processMatchedElements(bodyElement)
  135. const text = bodyElement.textContent
  136. if (!text) {
  137. return ''
  138. }
  139. return (
  140. text
  141. // remove zero-width spaces (e.g. those added by Powerpoint)
  142. .replaceAll('​', '')
  143. // normalise multiple newlines
  144. .replaceAll(/\n{2,}/g, '\n\n')
  145. // only allow a single newline at the start and end
  146. .replaceAll(/(^\n+|\n+$)/g, '\n')
  147. // replace tab with 4 spaces (hard-coded indent unit)
  148. .replaceAll('\t', ' ')
  149. )
  150. }
  151. const trimInlineElements = (
  152. element: HTMLElement,
  153. precedingSpace = true
  154. ): boolean => {
  155. for (const node of element.childNodes) {
  156. if (isTextNode(node)) {
  157. let text = node.textContent!
  158. if (precedingSpace) {
  159. text = text.replace(/^\s+/, '')
  160. }
  161. if (text === '') {
  162. node.remove()
  163. } else {
  164. node.textContent = text
  165. precedingSpace = /\s$/.test(text)
  166. }
  167. } else if (isInlineElement(node)) {
  168. precedingSpace = trimInlineElements(node, precedingSpace)
  169. } else if (isBlockElement(node)) {
  170. precedingSpace = true // TODO
  171. } else {
  172. precedingSpace = false // TODO
  173. }
  174. }
  175. // TODO: trim whitespace at the end
  176. return precedingSpace
  177. }
  178. const processWhitespaceInBlocks = (documentElement: HTMLElement) => {
  179. trimInlineElements(documentElement)
  180. const walker = document.createTreeWalker(
  181. documentElement,
  182. NodeFilter.SHOW_ELEMENT,
  183. node =>
  184. isElementNode(node) && isElementContainingCode(node)
  185. ? NodeFilter.FILTER_REJECT
  186. : NodeFilter.FILTER_ACCEPT
  187. )
  188. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  189. // TODO: remove leading newline from pre, code and textarea?
  190. if (isBlockContainingElement(node)) {
  191. // remove all text nodes directly inside elements that should only contain blocks
  192. for (const childNode of node.childNodes) {
  193. if (isTextNode(childNode)) {
  194. childNode.remove()
  195. }
  196. }
  197. }
  198. if (isBlockElement(node)) {
  199. trimInlineElements(node)
  200. if (shouldRemoveEmptyBlockElement(node)) {
  201. node.remove()
  202. // TODO: and parents?
  203. }
  204. }
  205. }
  206. }
  207. const normaliseWhitespace = (documentElement: HTMLElement) => {
  208. const walker = document.createTreeWalker(
  209. documentElement,
  210. NodeFilter.SHOW_TEXT,
  211. node =>
  212. isElementNode(node) && isElementContainingCode(node)
  213. ? NodeFilter.FILTER_REJECT
  214. : NodeFilter.FILTER_ACCEPT
  215. )
  216. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  217. const text = node.textContent
  218. if (text !== null) {
  219. if (/^\s+$/.test(text)) {
  220. // replace nodes containing only whitespace (including non-breaking space) with a single space
  221. node.textContent = ' '
  222. } else {
  223. // collapse contiguous whitespace (except for non-breaking space) to a single space
  224. node.textContent = text.replaceAll(/[\n\r\f\t \u2028\u2029]+/g, ' ')
  225. }
  226. }
  227. }
  228. }
  229. // TODO: negative lookbehind once Safari supports it
  230. const specialCharacterRegExp = /(^|[^\\])([#$%&~_^\\{}])/g
  231. const specialCharacterReplacer = (
  232. _match: string,
  233. prefix: string,
  234. char: string
  235. ) => {
  236. if (char === '\\') {
  237. // convert `\` to `\textbackslash{}`, preserving subsequent whitespace
  238. char = 'textbackslash{}'
  239. }
  240. return `${prefix}\\${char}`
  241. }
  242. const isElementContainingCode = (element: HTMLElement) =>
  243. element.nodeName === 'CODE' ||
  244. (element.nodeName === 'PRE' && element.style.fontFamily.includes('monospace'))
  245. const protectSpecialCharacters = (documentElement: HTMLElement) => {
  246. const walker = document.createTreeWalker(
  247. documentElement,
  248. NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
  249. node =>
  250. isElementNode(node) && isElementContainingCode(node)
  251. ? NodeFilter.FILTER_REJECT
  252. : NodeFilter.FILTER_ACCEPT
  253. )
  254. for (let node = walker.nextNode(); node; node = walker.nextNode()) {
  255. if (isTextNode(node)) {
  256. const text = node.textContent
  257. if (text) {
  258. // replace non-backslash-prefixed characters
  259. node.textContent = text.replaceAll(
  260. specialCharacterRegExp,
  261. specialCharacterReplacer
  262. )
  263. }
  264. }
  265. }
  266. }
  267. const processMatchedElements = (documentElement: HTMLElement) => {
  268. for (const item of selectors) {
  269. for (const element of documentElement.querySelectorAll<any>(
  270. item.selector
  271. )) {
  272. if (!item.match || item.match(element)) {
  273. // start the markup
  274. if (item.start) {
  275. const start = document.createTextNode(item.start(element))
  276. if (item.inside) {
  277. element.prepend(start)
  278. } else {
  279. element.before(start)
  280. }
  281. }
  282. // end the markup
  283. if (item.end) {
  284. const end = document.createTextNode(item.end(element))
  285. if (item.inside) {
  286. element.append(end)
  287. } else {
  288. element.after(end)
  289. }
  290. }
  291. }
  292. }
  293. }
  294. }
  295. const matchingParents = (element: HTMLElement, selector: string) => {
  296. const matches = []
  297. for (
  298. let ancestor = element.parentElement?.closest(selector);
  299. ancestor;
  300. ancestor = ancestor.parentElement?.closest(selector)
  301. ) {
  302. matches.push(ancestor)
  303. }
  304. return matches
  305. }
  306. const urlCharacterReplacements = new Map<string, string>([
  307. ['\\', '\\\\'],
  308. ['#', '\\#'],
  309. ['%', '\\%'],
  310. ['{', '%7B'],
  311. ['}', '%7D'],
  312. ])
  313. const protectUrlCharacters = (url: string) => {
  314. // NOTE: add new characters to both this regex and urlCharacterReplacements
  315. return url.replaceAll(/[\\#%{}]/g, match => {
  316. const replacement = urlCharacterReplacements.get(match)
  317. if (!replacement) {
  318. throw new Error(`No replacement found for ${match}`)
  319. }
  320. return replacement
  321. })
  322. }
  323. const processLists = (element: HTMLElement) => {
  324. for (const list of element.querySelectorAll('ol,ul')) {
  325. // if the list has only one item, replace the list with an element containing the contents of the item
  326. if (list.childElementCount === 1) {
  327. const div = document.createElement('div')
  328. div.append(...list.firstElementChild!.childNodes)
  329. list.before('\n', div, '\n')
  330. list.remove()
  331. }
  332. }
  333. }
  334. const processTables = (element: HTMLElement) => {
  335. for (const table of element.querySelectorAll('table')) {
  336. // create a wrapper element for the table and the caption
  337. const container = document.createElement('div')
  338. container.className = 'ol-table-wrap'
  339. table.after(container)
  340. // move the caption (if it exists) into the container before the table
  341. const caption = table.querySelector('caption')
  342. if (caption) {
  343. container.append(caption)
  344. }
  345. // move the table into the container
  346. container.append(table)
  347. // add empty cells to account for rowspan
  348. for (const cell of table.querySelectorAll<HTMLTableCellElement>(
  349. 'th[rowspan],td[rowspan]'
  350. )) {
  351. const rowspan = Number(cell.getAttribute('rowspan') || '1')
  352. const colspan = Number(cell.getAttribute('colspan') || '1')
  353. let row: HTMLTableRowElement | null = cell.closest('tr')
  354. if (row) {
  355. let position = 0
  356. for (const child of row.cells) {
  357. if (child === cell) {
  358. break
  359. }
  360. position += Number(child.getAttribute('colspan') || '1')
  361. }
  362. for (let i = 1; i < rowspan; i++) {
  363. const nextElement: Element | null = row?.nextElementSibling
  364. if (!isTableRow(nextElement)) {
  365. break
  366. }
  367. row = nextElement
  368. let targetCell: HTMLTableCellElement | undefined
  369. let targetPosition = 0
  370. for (const child of row.cells) {
  371. if (targetPosition === position) {
  372. targetCell = child
  373. break
  374. }
  375. targetPosition += Number(child.getAttribute('colspan') || '1')
  376. }
  377. const fillerCells = Array.from({ length: colspan }, () =>
  378. document.createElement('td')
  379. )
  380. if (targetCell) {
  381. targetCell.before(...fillerCells)
  382. } else {
  383. row.append(...fillerCells)
  384. }
  385. }
  386. }
  387. }
  388. }
  389. }
  390. const isTableRow = (element: Element | null): element is HTMLTableRowElement =>
  391. element?.nodeName === 'TR'
  392. const cellAlignment = new Map([
  393. ['left', 'l'],
  394. ['center', 'c'],
  395. ['right', 'r'],
  396. ])
  397. const tabular = (element: HTMLTableElement) => {
  398. const definitions: Array<{
  399. alignment: string
  400. borderLeft: boolean
  401. borderRight: boolean
  402. }> = []
  403. const rows = element.querySelectorAll('tr')
  404. for (const row of rows) {
  405. const cells = [...row.childNodes].filter(
  406. element => element.nodeName === 'TD' || element.nodeName === 'TH'
  407. ) as Array<HTMLTableCellElement>
  408. let index = 0
  409. for (const cell of cells) {
  410. // NOTE: reading the alignment and borders from the first cell definition in each column
  411. if (definitions[index] === undefined) {
  412. const { textAlign, borderLeftStyle, borderRightStyle } = cell.style
  413. definitions[index] = {
  414. alignment: textAlign,
  415. borderLeft: visibleBorderStyle(borderLeftStyle),
  416. borderRight: visibleBorderStyle(borderRightStyle),
  417. }
  418. }
  419. index += Number(cell.getAttribute('colspan') ?? 1)
  420. }
  421. }
  422. for (let index = 0; index <= definitions.length; index++) {
  423. // fill in missing definitions
  424. const item = definitions[index] || {
  425. alignment: 'left',
  426. borderLeft: false,
  427. borderRight: false,
  428. }
  429. // remove left border if previous column had a right border
  430. if (item.borderLeft && index > 0 && definitions[index - 1]?.borderRight) {
  431. item.borderLeft = false
  432. }
  433. }
  434. return definitions
  435. .flatMap(definition => [
  436. definition.borderLeft ? '|' : '',
  437. cellAlignment.get(definition.alignment) ?? 'l',
  438. definition.borderRight ? '|' : '',
  439. ])
  440. .filter(Boolean)
  441. .join(' ')
  442. }
  443. const listDepth = (
  444. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  445. ): number => Math.max(0, matchingParents(element, 'ul,ol').length - 1)
  446. const listIndent = (
  447. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  448. ): string => '\t'.repeat(listDepth(element))
  449. type ElementSelector<T extends string, E extends HTMLElement = HTMLElement> = {
  450. selector: T
  451. match?: (element: E) => boolean
  452. start?: (element: E) => string
  453. end?: (element: E) => string
  454. inside?: boolean
  455. }
  456. const createSelector = <
  457. T extends string,
  458. E extends HTMLElement = T extends keyof HTMLElementTagNameMap
  459. ? HTMLElementTagNameMap[T]
  460. : HTMLElement
  461. >({
  462. selector,
  463. ...elementSelector
  464. }: ElementSelector<T, E>) => ({
  465. selector,
  466. ...elementSelector,
  467. })
  468. const headings = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']
  469. const isHeading = (element: HTMLElement | null) => {
  470. return element && headings.includes(element.nodeName)
  471. }
  472. const hasContent = (element: HTMLElement): boolean => {
  473. return Boolean(element.textContent && element.textContent.trim().length > 0)
  474. }
  475. type BorderStyle =
  476. | 'borderTopStyle'
  477. | 'borderRightStyle'
  478. | 'borderBottomStyle'
  479. | 'borderLeftStyle'
  480. const visibleBorderStyle = (style: CSSStyleDeclaration[BorderStyle]): boolean =>
  481. !!style && style !== 'none' && style !== 'hidden'
  482. const rowHasBorderStyle = (
  483. element: HTMLTableRowElement,
  484. style: BorderStyle
  485. ): boolean => {
  486. if (visibleBorderStyle(element.style[style])) {
  487. return true
  488. }
  489. const cells = element.querySelectorAll<HTMLTableCellElement>('th,td')
  490. return [...cells].every(cell => visibleBorderStyle(cell.style[style]))
  491. }
  492. const isTableRowElement = (
  493. element: Element | null
  494. ): element is HTMLTableRowElement => element?.nodeName === 'TR'
  495. const nextRowHasBorderStyle = (
  496. element: HTMLTableRowElement,
  497. style: BorderStyle
  498. ) => {
  499. const { nextElementSibling } = element
  500. return (
  501. isTableRowElement(nextElementSibling) &&
  502. rowHasBorderStyle(nextElementSibling, style)
  503. )
  504. }
  505. const startMulticolumn = (element: HTMLTableCellElement): string => {
  506. const colspan = Number(element.getAttribute('colspan') || 1)
  507. const alignment = cellAlignment.get(element.style.textAlign) ?? 'l'
  508. return `\\multicolumn{${colspan}}{${alignment}}{`
  509. }
  510. const startMultirow = (element: HTMLTableCellElement): string => {
  511. const rowspan = Number(element.getAttribute('rowspan') || 1)
  512. // NOTE: it would be useful to read cell width if specified, using `*` as a starting point
  513. return `\\multirow{${rowspan}}{*}{`
  514. }
  515. const selectors = [
  516. createSelector({
  517. selector: 'b',
  518. match: element =>
  519. !element.style.fontWeight &&
  520. !isHeading(element.parentElement) &&
  521. hasContent(element),
  522. start: () => '\\textbf{',
  523. end: () => '}',
  524. }),
  525. createSelector({
  526. selector: '*',
  527. match: element =>
  528. (element.style.fontWeight === 'bold' ||
  529. parseInt(element.style.fontWeight) >= 700) &&
  530. hasContent(element),
  531. start: () => '\\textbf{',
  532. end: () => '}',
  533. inside: true,
  534. }),
  535. createSelector({
  536. selector: 'strong',
  537. match: element => !element.style.fontWeight && hasContent(element),
  538. start: () => '\\textbf{',
  539. end: () => '}',
  540. }),
  541. createSelector({
  542. selector: 'i',
  543. match: element => !element.style.fontStyle && hasContent(element),
  544. start: () => '\\textit{',
  545. end: () => '}',
  546. }),
  547. createSelector({
  548. selector: '*',
  549. match: element =>
  550. element.style.fontStyle === 'italic' && hasContent(element),
  551. start: () => '\\textit{',
  552. end: () => '}',
  553. inside: true,
  554. }),
  555. createSelector({
  556. selector: 'em',
  557. match: element => !element.style.fontStyle && hasContent(element),
  558. start: () => '\\textit{',
  559. end: () => '}',
  560. }),
  561. createSelector({
  562. selector: 'sup',
  563. match: element => !element.style.verticalAlign && hasContent(element),
  564. start: () => '\\textsuperscript{',
  565. end: () => '}',
  566. }),
  567. createSelector({
  568. selector: 'span',
  569. match: element =>
  570. element.style.verticalAlign === 'super' && hasContent(element),
  571. start: () => '\\textsuperscript{',
  572. end: () => '}',
  573. }),
  574. createSelector({
  575. selector: 'sub',
  576. match: element => !element.style.verticalAlign && hasContent(element),
  577. start: () => '\\textsubscript{',
  578. end: () => '}',
  579. }),
  580. createSelector({
  581. selector: 'span',
  582. match: element =>
  583. element.style.verticalAlign === 'sub' && hasContent(element),
  584. start: () => '\\textsubscript{',
  585. end: () => '}',
  586. }),
  587. createSelector({
  588. selector: 'a',
  589. match: element => !!element.href && hasContent(element),
  590. start: (element: HTMLAnchorElement) => {
  591. const url = protectUrlCharacters(element.href)
  592. return `\\href{${url}}{`
  593. },
  594. end: () => `}`,
  595. }),
  596. createSelector({
  597. selector: 'h1',
  598. match: element => !element.closest('table') && hasContent(element),
  599. start: () => `\n\n\\section{`,
  600. end: () => `}\n\n`,
  601. }),
  602. createSelector({
  603. selector: 'h2',
  604. match: element => !element.closest('table') && hasContent(element),
  605. start: () => `\n\n\\subsection{`,
  606. end: () => `}\n\n`,
  607. }),
  608. createSelector({
  609. selector: 'h3',
  610. match: element => !element.closest('table') && hasContent(element),
  611. start: () => `\n\n\\subsubsection{`,
  612. end: () => `}\n\n`,
  613. }),
  614. createSelector({
  615. selector: 'h4',
  616. match: element => !element.closest('table') && hasContent(element),
  617. start: () => `\n\n\\paragraph{`,
  618. end: () => `}\n\n`,
  619. }),
  620. createSelector({
  621. selector: 'h5',
  622. match: element => !element.closest('table') && hasContent(element),
  623. start: () => `\n\n\\subparagraph{`,
  624. end: () => `}\n\n`,
  625. }),
  626. // TODO: h6?
  627. createSelector({
  628. selector: 'br',
  629. match: element => !element.closest('table'),
  630. start: () => `\n\n`,
  631. }),
  632. createSelector({
  633. selector: 'code',
  634. match: element =>
  635. element.parentElement?.nodeName !== 'PRE' && hasContent(element),
  636. start: () => `\\verb|`,
  637. end: () => `|`,
  638. }),
  639. createSelector({
  640. selector: 'pre > code',
  641. match: element => hasContent(element),
  642. start: () => `\n\n\\begin{verbatim}\n`,
  643. end: () => `\n\\end{verbatim}\n\n`,
  644. }),
  645. createSelector({
  646. selector: 'pre',
  647. match: element =>
  648. element.style.fontFamily.includes('monospace') &&
  649. element.firstElementChild?.nodeName !== 'CODE' &&
  650. hasContent(element),
  651. start: () => `\n\n\\begin{verbatim}\n`,
  652. end: () => `\n\\end{verbatim}\n\n`,
  653. }),
  654. createSelector({
  655. selector: '.ol-table-wrap',
  656. start: () => `\n\n\\begin{table}\n\\centering\n`,
  657. end: () => `\n\\end{table}\n\n`,
  658. }),
  659. createSelector({
  660. selector: 'table',
  661. start: element => `\n\\begin{tabular}{${tabular(element)}}`,
  662. end: () => `\\end{tabular}\n`,
  663. }),
  664. createSelector({
  665. selector: 'thead',
  666. start: () => `\n`,
  667. end: () => `\n`,
  668. }),
  669. createSelector({
  670. selector: 'tfoot',
  671. start: () => `\n`,
  672. end: () => `\n`,
  673. }),
  674. createSelector({
  675. selector: 'tbody',
  676. start: () => `\n`,
  677. end: () => `\n`,
  678. }),
  679. createSelector({
  680. selector: 'tr',
  681. start: element => {
  682. const borderTop = rowHasBorderStyle(element, 'borderTopStyle')
  683. return borderTop ? '\\hline\n' : ''
  684. },
  685. end: element => {
  686. const borderBottom = rowHasBorderStyle(element, 'borderBottomStyle')
  687. return borderBottom && !nextRowHasBorderStyle(element, 'borderTopStyle')
  688. ? '\n\\hline\n'
  689. : '\n'
  690. },
  691. }),
  692. createSelector({
  693. selector: 'tr > td, tr > th',
  694. start: (element: HTMLTableCellElement) => {
  695. let output = ''
  696. const colspan = element.getAttribute('colspan')
  697. if (colspan && Number(colspan) > 1) {
  698. output += startMulticolumn(element)
  699. }
  700. // NOTE: multirow is nested inside multicolumn
  701. const rowspan = element.getAttribute('rowspan')
  702. if (rowspan && Number(rowspan) > 1) {
  703. output += startMultirow(element)
  704. }
  705. return output
  706. },
  707. end: element => {
  708. let output = ''
  709. // NOTE: multirow is nested inside multicolumn
  710. const rowspan = element.getAttribute('rowspan')
  711. if (rowspan && Number(rowspan) > 1) {
  712. output += '}'
  713. }
  714. const colspan = element.getAttribute('colspan')
  715. if (colspan && Number(colspan) > 1) {
  716. output += '}'
  717. }
  718. const row = element.parentElement as HTMLTableRowElement
  719. const isLastChild = row.cells.item(row.cells.length - 1) === element
  720. return output + (isLastChild ? ' \\\\' : ' & ')
  721. },
  722. }),
  723. createSelector({
  724. selector: 'caption',
  725. start: () => `\n\n\\caption{`,
  726. end: () => `}\n\n`,
  727. }),
  728. createSelector({
  729. // selector: 'ul:has(> li:nth-child(2))', // only select lists with at least 2 items (once Firefox supports :has())
  730. selector: 'ul',
  731. start: element => `\n\n${listIndent(element)}\\begin{itemize}`,
  732. end: element => `\n${listIndent(element)}\\end{itemize}\n`,
  733. }),
  734. createSelector({
  735. // selector: 'ol:has(> li:nth-child(2))', // only select lists with at least 2 items (once Firefox supports :has())
  736. selector: 'ol',
  737. start: element => `\n\n${listIndent(element)}\\begin{enumerate}`,
  738. end: element => `\n${listIndent(element)}\\end{enumerate}\n`,
  739. }),
  740. createSelector({
  741. selector: 'li',
  742. start: element => `\n${listIndent(element)}\t\\item `,
  743. }),
  744. createSelector({
  745. selector: 'p',
  746. match: element => {
  747. // must have content
  748. if (!hasContent(element)) {
  749. return false
  750. }
  751. // inside lists and tables, must precede another paragraph
  752. if (element.closest('li') || element.closest('table')) {
  753. return element.nextElementSibling?.nodeName === 'P'
  754. }
  755. return true
  756. },
  757. end: () => '\n\n',
  758. }),
  759. createSelector({
  760. selector: 'blockquote',
  761. start: () => `\n\n\\begin{quote}\n`,
  762. end: () => `\n\\end{quote}\n\n`,
  763. }),
  764. ]