paste-html.ts 22 KB

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