paste-html.ts 21 KB

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