paste-html.ts 19 KB

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