paste-html.ts 21 KB

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