paste-html.ts 25 KB

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