paste-html.ts 22 KB

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