paste-html.ts 25 KB

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