paste-html.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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. inferred?: boolean
  416. }> = []
  417. const rows = element.querySelectorAll('tr')
  418. for (const row of rows) {
  419. const cells = [...row.childNodes].filter(
  420. element => element.nodeName === 'TD' || element.nodeName === 'TH'
  421. ) as Array<HTMLTableCellElement>
  422. let index = 0
  423. for (const cell of cells) {
  424. // NOTE: reading the alignment and borders from the first cell definition in each column
  425. const colspan = Number(cell.getAttribute('colspan') ?? 1)
  426. const { textAlign, borderLeftStyle, borderRightStyle } = cell.style
  427. for (let i = 0; i < colspan; i++) {
  428. if (
  429. // There's no definition for this column
  430. definitions[index + i] === undefined ||
  431. // There's an inferred definition of the column, and we're a cell that
  432. // can accurately represent the whole column, since we're not a
  433. // multicolumn cell ourselves.
  434. (colspan === 1 && definitions[index + i].inferred)
  435. ) {
  436. definitions[index + i] = {
  437. alignment: textAlign,
  438. borderLeft: visibleBorderStyle(borderLeftStyle),
  439. borderRight: visibleBorderStyle(borderRightStyle),
  440. // We can't trust the details from a multicolumn cell to represent the
  441. // whole column, so we mark it as inferred.
  442. inferred: colspan > 1,
  443. }
  444. }
  445. }
  446. index += colspan
  447. }
  448. }
  449. for (let index = 0; index <= definitions.length; index++) {
  450. // fill in missing definitions
  451. const item = definitions[index] || {
  452. alignment: 'left',
  453. borderLeft: false,
  454. borderRight: false,
  455. }
  456. // remove left border if previous column had a right border
  457. if (item.borderLeft && index > 0 && definitions[index - 1]?.borderRight) {
  458. item.borderLeft = false
  459. }
  460. }
  461. return definitions
  462. .flatMap(definition => [
  463. definition.borderLeft ? '|' : '',
  464. cellAlignment.get(definition.alignment) ?? 'l',
  465. definition.borderRight ? '|' : '',
  466. ])
  467. .filter(Boolean)
  468. .join(' ')
  469. }
  470. const listDepth = (element: HTMLElement): number =>
  471. Math.max(0, matchingParents(element, 'ul,ol').length)
  472. const indentUnit = ' ' // TODO: replace hard-coded indent unit?
  473. const listIndent = (element: HTMLElement | null): string =>
  474. element ? indentUnit.repeat(listDepth(element)) : ''
  475. type ElementSelector<T extends string, E extends HTMLElement = HTMLElement> = {
  476. selector: T
  477. match?: (element: E) => boolean
  478. start?: (element: E) => string
  479. end?: (element: E) => string
  480. inside?: boolean
  481. }
  482. const createSelector = <
  483. T extends string,
  484. E extends HTMLElement = T extends keyof HTMLElementTagNameMap
  485. ? HTMLElementTagNameMap[T]
  486. : HTMLElement,
  487. >({
  488. selector,
  489. ...elementSelector
  490. }: ElementSelector<T, E>) => ({
  491. selector,
  492. ...elementSelector,
  493. })
  494. const headings = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']
  495. const isHeading = (element: HTMLElement | null) => {
  496. return element && headings.includes(element.nodeName)
  497. }
  498. const hasContent = (element: HTMLElement): boolean => {
  499. return Boolean(element.textContent && element.textContent.trim().length > 0)
  500. }
  501. type BorderStyle =
  502. | 'borderTopStyle'
  503. | 'borderRightStyle'
  504. | 'borderBottomStyle'
  505. | 'borderLeftStyle'
  506. const visibleBorderStyle = (style: CSSStyleDeclaration[BorderStyle]): boolean =>
  507. !!style && style !== 'none' && style !== 'hidden'
  508. const rowHasBorderStyle = (
  509. element: HTMLTableRowElement,
  510. style: BorderStyle
  511. ): boolean => {
  512. if (visibleBorderStyle(element.style[style])) {
  513. return true
  514. }
  515. const cells = element.querySelectorAll<HTMLTableCellElement>('th,td')
  516. return [...cells].every(cell => visibleBorderStyle(cell.style[style]))
  517. }
  518. const isTableRowElement = (
  519. element: Element | null
  520. ): element is HTMLTableRowElement => element?.nodeName === 'TR'
  521. const nextRowHasBorderStyle = (
  522. element: HTMLTableRowElement,
  523. style: BorderStyle
  524. ) => {
  525. const { nextElementSibling } = element
  526. return (
  527. isTableRowElement(nextElementSibling) &&
  528. rowHasBorderStyle(nextElementSibling, style)
  529. )
  530. }
  531. const startMulticolumn = (element: HTMLTableCellElement): string => {
  532. const { textAlign, borderLeftStyle, borderRightStyle } = element.style
  533. const colspan = Number(element.getAttribute('colspan') || 1)
  534. const alignment = cellAlignment.get(textAlign) ?? 'l'
  535. const borderLeft = visibleBorderStyle(borderLeftStyle)
  536. const borderRight = visibleBorderStyle(borderRightStyle)
  537. return `\\multicolumn{${colspan}}{${borderLeft ? '|' : ''}${alignment}${borderRight ? '|' : ''}}{`
  538. }
  539. const startMultirow = (element: HTMLTableCellElement): string => {
  540. const rowspan = Number(element.getAttribute('rowspan') || 1)
  541. // NOTE: it would be useful to read cell width if specified, using `*` as a starting point
  542. return `\\multirow{${rowspan}}{*}{`
  543. }
  544. const listPrefix = (element: HTMLOListElement | HTMLUListElement) => {
  545. if (isListOrListItemElement(element.parentElement)) {
  546. // within a list = newline
  547. return '\n'
  548. }
  549. // outside a list = double newline
  550. return '\n\n'
  551. }
  552. const listSuffix = (element: HTMLOListElement | HTMLUListElement) => {
  553. if (listDepth(element) === 0) {
  554. // a top-level list => newline
  555. return '\n'
  556. } else {
  557. // a nested list => no extra newline
  558. return ''
  559. }
  560. }
  561. const isListElement = (
  562. element: Element | null
  563. ): element is HTMLOListElement | HTMLUListElement =>
  564. element !== null && listNodeNames.includes(element.nodeName)
  565. const isListOrListItemElement = (
  566. element: Element | null
  567. ): element is HTMLOListElement | HTMLUListElement =>
  568. element !== null && (isListElement(element) || element.nodeName === 'LI')
  569. const listNodeNames = ['OL', 'UL']
  570. const selectors = [
  571. createSelector({
  572. selector: 'b',
  573. match: element =>
  574. !element.style.fontWeight &&
  575. !isHeading(element.parentElement) &&
  576. hasContent(element),
  577. start: () => '\\textbf{',
  578. end: () => '}',
  579. }),
  580. createSelector({
  581. selector: '*',
  582. match: element =>
  583. (element.style.fontWeight === 'bold' ||
  584. parseInt(element.style.fontWeight) >= 700) &&
  585. hasContent(element),
  586. start: () => '\\textbf{',
  587. end: () => '}',
  588. inside: true,
  589. }),
  590. createSelector({
  591. selector: 'strong',
  592. match: element => !element.style.fontWeight && hasContent(element),
  593. start: () => '\\textbf{',
  594. end: () => '}',
  595. }),
  596. createSelector({
  597. selector: 'i',
  598. match: element => !element.style.fontStyle && hasContent(element),
  599. start: () => '\\textit{',
  600. end: () => '}',
  601. }),
  602. createSelector({
  603. selector: '*',
  604. match: element =>
  605. element.style.fontStyle === 'italic' && hasContent(element),
  606. start: () => '\\textit{',
  607. end: () => '}',
  608. inside: true,
  609. }),
  610. createSelector({
  611. selector: 'em',
  612. match: element => !element.style.fontStyle && hasContent(element),
  613. start: () => '\\textit{',
  614. end: () => '}',
  615. }),
  616. createSelector({
  617. selector: 'sup',
  618. match: element => !element.style.verticalAlign && hasContent(element),
  619. start: () => '\\textsuperscript{',
  620. end: () => '}',
  621. }),
  622. createSelector({
  623. selector: 'span',
  624. match: element =>
  625. element.style.verticalAlign === 'super' && hasContent(element),
  626. start: () => '\\textsuperscript{',
  627. end: () => '}',
  628. }),
  629. createSelector({
  630. selector: 'sub',
  631. match: element => !element.style.verticalAlign && hasContent(element),
  632. start: () => '\\textsubscript{',
  633. end: () => '}',
  634. }),
  635. createSelector({
  636. selector: 'span',
  637. match: element =>
  638. element.style.verticalAlign === 'sub' && hasContent(element),
  639. start: () => '\\textsubscript{',
  640. end: () => '}',
  641. }),
  642. createSelector({
  643. selector: 'a',
  644. match: element => !!element.href && hasContent(element),
  645. start: (element: HTMLAnchorElement) => {
  646. const url = protectUrlCharacters(element.href)
  647. return `\\href{${url}}{`
  648. },
  649. end: () => `}`,
  650. }),
  651. createSelector({
  652. selector: 'h1',
  653. match: element => !element.closest('table') && hasContent(element),
  654. start: () => `\n\n\\section{`,
  655. end: () => `}\n\n`,
  656. }),
  657. createSelector({
  658. selector: 'h2',
  659. match: element => !element.closest('table') && hasContent(element),
  660. start: () => `\n\n\\subsection{`,
  661. end: () => `}\n\n`,
  662. }),
  663. createSelector({
  664. selector: 'h3',
  665. match: element => !element.closest('table') && hasContent(element),
  666. start: () => `\n\n\\subsubsection{`,
  667. end: () => `}\n\n`,
  668. }),
  669. createSelector({
  670. selector: 'h4',
  671. match: element => !element.closest('table') && hasContent(element),
  672. start: () => `\n\n\\paragraph{`,
  673. end: () => `}\n\n`,
  674. }),
  675. createSelector({
  676. selector: 'h5',
  677. match: element => !element.closest('table') && hasContent(element),
  678. start: () => `\n\n\\subparagraph{`,
  679. end: () => `}\n\n`,
  680. }),
  681. // TODO: h6?
  682. createSelector({
  683. selector: 'br',
  684. match: element => !element.closest('table'),
  685. start: () => `\n\n`,
  686. }),
  687. createSelector({
  688. selector: 'code',
  689. match: element =>
  690. element.parentElement?.nodeName !== 'PRE' && hasContent(element),
  691. start: () => `\\verb|`,
  692. end: () => `|`,
  693. }),
  694. createSelector({
  695. selector: 'pre > code',
  696. match: element => hasContent(element),
  697. start: () => `\n\n\\begin{verbatim}\n`,
  698. end: () => `\n\\end{verbatim}\n\n`,
  699. }),
  700. createSelector({
  701. selector: 'pre',
  702. match: element =>
  703. element.style.fontFamily.includes('monospace') &&
  704. element.firstElementChild?.nodeName !== 'CODE' &&
  705. hasContent(element),
  706. start: () => `\n\n\\begin{verbatim}\n`,
  707. end: () => `\n\\end{verbatim}\n\n`,
  708. }),
  709. createSelector({
  710. selector: '.ol-table-wrap',
  711. start: () => `\n\n\\begin{table}\n\\centering\n`,
  712. end: () => `\n\\end{table}\n\n`,
  713. }),
  714. createSelector({
  715. selector: 'table',
  716. start: element => `\n\\begin{tabular}{${tabular(element)}}`,
  717. end: () => `\\end{tabular}\n`,
  718. }),
  719. createSelector({
  720. selector: 'thead',
  721. start: () => `\n`,
  722. end: () => `\n`,
  723. }),
  724. createSelector({
  725. selector: 'tfoot',
  726. start: () => `\n`,
  727. end: () => `\n`,
  728. }),
  729. createSelector({
  730. selector: 'tbody',
  731. start: () => `\n`,
  732. end: () => `\n`,
  733. }),
  734. createSelector({
  735. selector: 'tr',
  736. start: element => {
  737. const borderTop = rowHasBorderStyle(element, 'borderTopStyle')
  738. return borderTop ? '\\hline\n' : ''
  739. },
  740. end: element => {
  741. const borderBottom = rowHasBorderStyle(element, 'borderBottomStyle')
  742. return borderBottom && !nextRowHasBorderStyle(element, 'borderTopStyle')
  743. ? '\n\\hline\n'
  744. : '\n'
  745. },
  746. }),
  747. createSelector({
  748. selector: 'tr > td, tr > th',
  749. start: (element: HTMLTableCellElement) => {
  750. let output = ''
  751. const colspan = element.getAttribute('colspan')
  752. if (colspan && Number(colspan) > 1) {
  753. output += startMulticolumn(element)
  754. }
  755. // NOTE: multirow is nested inside multicolumn
  756. const rowspan = element.getAttribute('rowspan')
  757. if (rowspan && Number(rowspan) > 1) {
  758. output += startMultirow(element)
  759. }
  760. return output
  761. },
  762. end: element => {
  763. let output = ''
  764. // NOTE: multirow is nested inside multicolumn
  765. const rowspan = element.getAttribute('rowspan')
  766. if (rowspan && Number(rowspan) > 1) {
  767. output += '}'
  768. }
  769. const colspan = element.getAttribute('colspan')
  770. if (colspan && Number(colspan) > 1) {
  771. output += '}'
  772. }
  773. const row = element.parentElement as HTMLTableRowElement
  774. const isLastChild = row.cells.item(row.cells.length - 1) === element
  775. return output + (isLastChild ? ' \\\\' : ' & ')
  776. },
  777. }),
  778. createSelector({
  779. selector: 'caption',
  780. start: () => `\n\n\\caption{`,
  781. end: () => `}\n\n`,
  782. }),
  783. createSelector({
  784. // selector: 'ul:has(> li:nth-child(2))', // only select lists with at least 2 items (once Firefox supports :has())
  785. selector: 'ul',
  786. start: element => {
  787. return `${listPrefix(element)}${listIndent(element)}\\begin{itemize}`
  788. },
  789. end: element => {
  790. return `\n${listIndent(element)}\\end{itemize}${listSuffix(element)}`
  791. },
  792. }),
  793. createSelector({
  794. // selector: 'ol:has(> li:nth-child(2))', // only select lists with at least 2 items (once Firefox supports :has())
  795. selector: 'ol',
  796. start: element => {
  797. return `${listPrefix(element)}${listIndent(element)}\\begin{enumerate}`
  798. },
  799. end: element => {
  800. return `\n${listIndent(element)}\\end{enumerate}${listSuffix(element)}`
  801. },
  802. }),
  803. createSelector({
  804. selector: 'li',
  805. start: element => {
  806. return `\n${listIndent(element.parentElement)}${indentUnit}\\item `
  807. },
  808. }),
  809. createSelector({
  810. selector: 'p',
  811. match: element => {
  812. // must have content
  813. if (!hasContent(element)) {
  814. return false
  815. }
  816. // inside lists and tables, must precede another paragraph
  817. if (element.closest('li') || element.closest('table')) {
  818. return element.nextElementSibling?.nodeName === 'P'
  819. }
  820. return true
  821. },
  822. end: () => '\n\n',
  823. }),
  824. createSelector({
  825. selector: 'blockquote',
  826. start: () => `\n\n\\begin{quote}\n`,
  827. end: () => `\n\\end{quote}\n\n`,
  828. }),
  829. ]