paste-html.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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 processLists = (element: HTMLElement) => {
  182. for (const list of element.querySelectorAll('ol,ul')) {
  183. // if the list has only one item, replace the list with an element containing the contents of the item
  184. if (list.childElementCount === 1) {
  185. const div = document.createElement('div')
  186. div.append(...list.firstElementChild!.childNodes)
  187. list.before('\n', div, '\n')
  188. list.remove()
  189. }
  190. }
  191. }
  192. const processTables = (element: HTMLElement) => {
  193. for (const table of element.querySelectorAll('table')) {
  194. // create a wrapper element for the table and the caption
  195. const container = document.createElement('div')
  196. container.className = 'ol-table-wrap'
  197. table.after(container)
  198. // move the caption (if it exists) into the container before the table
  199. const caption = table.querySelector('caption')
  200. if (caption) {
  201. container.append(caption)
  202. }
  203. // move the table into the container
  204. container.append(table)
  205. // add empty cells to account for rowspan
  206. for (const cell of table.querySelectorAll<HTMLTableCellElement>(
  207. 'th[rowspan],td[rowspan]'
  208. )) {
  209. const rowspan = Number(cell.getAttribute('rowspan') || '1')
  210. const colspan = Number(cell.getAttribute('colspan') || '1')
  211. let row: HTMLTableRowElement | null = cell.closest('tr')
  212. if (row) {
  213. let position = 0
  214. for (const child of row.cells) {
  215. if (child === cell) {
  216. break
  217. }
  218. position += Number(child.getAttribute('colspan') || '1')
  219. }
  220. for (let i = 1; i < rowspan; i++) {
  221. const nextElement: Element | null = row?.nextElementSibling
  222. if (!isTableRow(nextElement)) {
  223. break
  224. }
  225. row = nextElement
  226. let targetCell: HTMLTableCellElement | undefined
  227. let targetPosition = 0
  228. for (const child of row.cells) {
  229. if (targetPosition === position) {
  230. targetCell = child
  231. break
  232. }
  233. targetPosition += Number(child.getAttribute('colspan') || '1')
  234. }
  235. const fillerCells = Array.from({ length: colspan }, () =>
  236. document.createElement('td')
  237. )
  238. if (targetCell) {
  239. targetCell.before(...fillerCells)
  240. } else {
  241. row.append(...fillerCells)
  242. }
  243. }
  244. }
  245. }
  246. }
  247. }
  248. const isTableRow = (element: Element | null): element is HTMLTableRowElement =>
  249. element?.tagName === 'TR'
  250. const cellAlignment = new Map([
  251. ['left', 'l'],
  252. ['center', 'c'],
  253. ['right', 'r'],
  254. ])
  255. const tabular = (element: HTMLTableElement) => {
  256. const definitions: Array<{
  257. alignment: string
  258. borderLeft: boolean
  259. borderRight: boolean
  260. }> = []
  261. const rows = element.querySelectorAll('tr')
  262. for (const row of rows) {
  263. const cells = [...row.childNodes].filter(
  264. element => element.nodeName === 'TD' || element.nodeName === 'TH'
  265. ) as Array<HTMLTableCellElement>
  266. let index = 0
  267. for (const cell of cells) {
  268. // NOTE: reading the alignment and borders from the first cell definition in each column
  269. if (definitions[index] === undefined) {
  270. const { textAlign, borderLeftStyle, borderRightStyle } = cell.style
  271. definitions[index] = {
  272. alignment: textAlign,
  273. borderLeft: visibleBorderStyle(borderLeftStyle),
  274. borderRight: visibleBorderStyle(borderRightStyle),
  275. }
  276. }
  277. index += Number(cell.getAttribute('colspan') ?? 1)
  278. }
  279. }
  280. for (let index = 0; index <= definitions.length; index++) {
  281. // fill in missing definitions
  282. const item = definitions[index] || {
  283. alignment: 'left',
  284. borderLeft: false,
  285. borderRight: false,
  286. }
  287. // remove left border if previous column had a right border
  288. if (item.borderLeft && index > 0 && definitions[index - 1]?.borderRight) {
  289. item.borderLeft = false
  290. }
  291. }
  292. return definitions
  293. .flatMap(definition => [
  294. definition.borderLeft ? '|' : '',
  295. cellAlignment.get(definition.alignment) ?? 'l',
  296. definition.borderRight ? '|' : '',
  297. ])
  298. .filter(Boolean)
  299. .join(' ')
  300. }
  301. const listDepth = (
  302. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  303. ): number => Math.max(0, matchingParents(element, 'ul,ol').length - 1)
  304. const listIndent = (
  305. element: HTMLOListElement | HTMLUListElement | HTMLLIElement
  306. ): string => '\t'.repeat(listDepth(element))
  307. type ElementSelector<T extends string, E extends HTMLElement = HTMLElement> = {
  308. selector: T
  309. match?: (element: E) => boolean
  310. start?: (element: E) => string
  311. end?: (element: E) => string
  312. inside?: boolean
  313. }
  314. const createSelector = <
  315. T extends string,
  316. E extends HTMLElement = T extends keyof HTMLElementTagNameMap
  317. ? HTMLElementTagNameMap[T]
  318. : HTMLElement
  319. >({
  320. selector,
  321. ...elementSelector
  322. }: ElementSelector<T, E>) => ({
  323. selector,
  324. ...elementSelector,
  325. })
  326. const headings = ['H1', 'H2', 'H3', 'H4', 'H5', 'H6']
  327. const isHeading = (element: HTMLElement | null) => {
  328. return element && headings.includes(element.nodeName)
  329. }
  330. const hasContent = (element: HTMLElement): boolean => {
  331. return Boolean(element.textContent && element.textContent.trim().length > 0)
  332. }
  333. type BorderStyle =
  334. | 'borderTopStyle'
  335. | 'borderRightStyle'
  336. | 'borderBottomStyle'
  337. | 'borderLeftStyle'
  338. const visibleBorderStyle = (style: CSSStyleDeclaration[BorderStyle]): boolean =>
  339. !!style && style !== 'none' && style !== 'hidden'
  340. const rowHasBorderStyle = (
  341. element: HTMLTableRowElement,
  342. style: BorderStyle
  343. ): boolean => {
  344. if (visibleBorderStyle(element.style[style])) {
  345. return true
  346. }
  347. const cells = element.querySelectorAll<HTMLTableCellElement>('th,td')
  348. return [...cells].every(cell => visibleBorderStyle(cell.style[style]))
  349. }
  350. const isTableRowElement = (
  351. element: Element | null
  352. ): element is HTMLTableRowElement => element?.tagName === 'TR'
  353. const nextRowHasBorderStyle = (
  354. element: HTMLTableRowElement,
  355. style: BorderStyle
  356. ) => {
  357. const { nextElementSibling } = element
  358. return (
  359. isTableRowElement(nextElementSibling) &&
  360. rowHasBorderStyle(nextElementSibling, style)
  361. )
  362. }
  363. const startMulticolumn = (element: HTMLTableCellElement): string => {
  364. const colspan = Number(element.getAttribute('colspan') || 1)
  365. const alignment = cellAlignment.get(element.style.textAlign) ?? 'l'
  366. return `\\multicolumn{${colspan}}{${alignment}}{`
  367. }
  368. const startMultirow = (element: HTMLTableCellElement): string => {
  369. const rowspan = Number(element.getAttribute('rowspan') || 1)
  370. // NOTE: it would be useful to read cell width if specified, using `*` as a starting point
  371. return `\\multirow{${rowspan}}{*}{`
  372. }
  373. const selectors = [
  374. createSelector({
  375. selector: 'b',
  376. match: element =>
  377. element.style.fontWeight !== 'normal' &&
  378. !isHeading(element.parentElement) &&
  379. hasContent(element),
  380. start: () => '\\textbf{',
  381. end: () => '}',
  382. }),
  383. createSelector({
  384. selector: '*',
  385. match: element =>
  386. parseInt(element.style.fontWeight) >= 700 && hasContent(element),
  387. start: () => '\\textbf{',
  388. end: () => '}',
  389. inside: true,
  390. }),
  391. createSelector({
  392. selector: 'strong',
  393. match: element => hasContent(element),
  394. start: () => '\\textbf{',
  395. end: () => '}',
  396. }),
  397. createSelector({
  398. selector: 'i',
  399. match: element =>
  400. element.style.fontStyle !== 'normal' && hasContent(element),
  401. start: () => '\\textit{',
  402. end: () => '}',
  403. }),
  404. createSelector({
  405. selector: '*',
  406. match: element =>
  407. element.style.fontStyle === 'italic' && hasContent(element),
  408. start: () => '\\textit{',
  409. end: () => '}',
  410. }),
  411. createSelector({
  412. selector: 'em',
  413. match: element => hasContent(element),
  414. start: () => '\\textit{',
  415. end: () => '}',
  416. }),
  417. createSelector({
  418. selector: 'sup',
  419. match: element => hasContent(element),
  420. start: () => '\\textsuperscript{',
  421. end: () => '}',
  422. }),
  423. createSelector({
  424. selector: 'span',
  425. match: element =>
  426. element.style.verticalAlign === 'super' && hasContent(element),
  427. start: () => '\\textsuperscript{',
  428. end: () => '}',
  429. }),
  430. createSelector({
  431. selector: 'sub',
  432. match: element => hasContent(element),
  433. start: () => '\\textsubscript{',
  434. end: () => '}',
  435. }),
  436. createSelector({
  437. selector: 'span',
  438. match: element =>
  439. element.style.verticalAlign === 'sub' && hasContent(element),
  440. start: () => '\\textsubscript{',
  441. end: () => '}',
  442. }),
  443. createSelector({
  444. selector: 'a',
  445. match: element => !!element.href && hasContent(element),
  446. start: (element: HTMLAnchorElement) => `\\href{${element.href}}{`,
  447. end: element => `}`,
  448. }),
  449. createSelector({
  450. selector: 'h1',
  451. match: element => !element.closest('table') && hasContent(element),
  452. start: () => `\n\n\\section{`,
  453. end: () => `}\n\n`,
  454. }),
  455. createSelector({
  456. selector: 'h2',
  457. match: element => !element.closest('table') && hasContent(element),
  458. start: () => `\n\n\\subsection{`,
  459. end: () => `}\n\n`,
  460. }),
  461. createSelector({
  462. selector: 'h3',
  463. match: element => !element.closest('table') && hasContent(element),
  464. start: () => `\n\n\\subsubsection{`,
  465. end: () => `}\n\n`,
  466. }),
  467. createSelector({
  468. selector: 'h4',
  469. match: element => !element.closest('table') && hasContent(element),
  470. start: () => `\n\n\\paragraph{`,
  471. end: () => `}\n\n`,
  472. }),
  473. createSelector({
  474. selector: 'h5',
  475. match: element => !element.closest('table') && hasContent(element),
  476. start: () => `\n\n\\subparagraph{`,
  477. end: () => `}\n\n`,
  478. }),
  479. // TODO: h6?
  480. createSelector({
  481. selector: 'br',
  482. match: element => element.parentElement?.nodeName !== 'TD', // TODO: why?
  483. start: () => `\n\n`,
  484. }),
  485. createSelector({
  486. selector: 'code',
  487. match: element =>
  488. element.parentElement?.nodeName !== 'PRE' && hasContent(element),
  489. start: () => `\\verb|`,
  490. end: () => `|`,
  491. }),
  492. createSelector({
  493. selector: 'pre > code',
  494. match: element => hasContent(element),
  495. start: () => `\n\n\\begin{verbatim}\n`,
  496. end: () => `\n\\end{verbatim}\n\n`,
  497. }),
  498. createSelector({
  499. selector: '.ol-table-wrap',
  500. start: () => `\n\n\\begin{table}\n\\centering\n`,
  501. end: () => `\n\\end{table}\n\n`,
  502. }),
  503. createSelector({
  504. selector: 'table',
  505. start: element => `\n\\begin{tabular}{${tabular(element)}}`,
  506. end: () => `\\end{tabular}\n`,
  507. }),
  508. createSelector({
  509. selector: 'thead',
  510. start: () => `\n`,
  511. end: () => `\n`,
  512. }),
  513. createSelector({
  514. selector: 'tfoot',
  515. start: () => `\n`,
  516. end: () => `\n`,
  517. }),
  518. createSelector({
  519. selector: 'tbody',
  520. start: () => `\n`,
  521. end: () => `\n`,
  522. }),
  523. createSelector({
  524. selector: 'tr',
  525. start: element => {
  526. const borderTop = rowHasBorderStyle(element, 'borderTopStyle')
  527. return borderTop ? '\\hline\n' : ''
  528. },
  529. end: element => {
  530. const borderBottom = rowHasBorderStyle(element, 'borderBottomStyle')
  531. return borderBottom && !nextRowHasBorderStyle(element, 'borderTopStyle')
  532. ? '\n\\hline\n'
  533. : '\n'
  534. },
  535. }),
  536. createSelector({
  537. selector: 'tr > td, tr > th',
  538. start: (element: HTMLTableCellElement) => {
  539. let output = ''
  540. if (element.getAttribute('colspan')) {
  541. output += startMulticolumn(element)
  542. }
  543. // NOTE: multirow is nested inside multicolumn
  544. if (element.getAttribute('rowspan')) {
  545. output += startMultirow(element)
  546. }
  547. return output
  548. },
  549. end: element => {
  550. let output = ''
  551. // NOTE: multirow is nested inside multicolumn
  552. if (element.getAttribute('rowspan')) {
  553. output += '}'
  554. }
  555. if (element.getAttribute('colspan')) {
  556. output += '}'
  557. }
  558. const row = element.parentElement as HTMLTableRowElement
  559. const isLastChild = row.cells.item(row.cells.length - 1) === element
  560. return output + (isLastChild ? ' \\\\' : ' & ')
  561. },
  562. }),
  563. createSelector({
  564. selector: 'caption',
  565. start: () => `\n\n\\caption{`,
  566. end: () => `}\n\n`,
  567. }),
  568. createSelector({
  569. // selector: 'ul:has(> li:nth-child(2))', // only select lists with at least 2 items (once Firefox supports :has())
  570. selector: 'ul',
  571. start: element => `\n\n${listIndent(element)}\\begin{itemize}`,
  572. end: element => `\n${listIndent(element)}\\end{itemize}\n`,
  573. }),
  574. createSelector({
  575. // selector: 'ol:has(> li:nth-child(2))', // only select lists with at least 2 items (once Firefox supports :has())
  576. selector: 'ol',
  577. start: element => `\n\n${listIndent(element)}\\begin{enumerate}`,
  578. end: element => `\n${listIndent(element)}\\end{enumerate}\n`,
  579. }),
  580. createSelector({
  581. selector: 'li',
  582. start: element => `\n${listIndent(element)}\t\\item `,
  583. }),
  584. createSelector({
  585. selector: 'p',
  586. match: element => {
  587. // must have content
  588. if (!hasContent(element)) {
  589. return false
  590. }
  591. // inside lists and tables, must precede another paragraph
  592. if (element.closest('li') || element.closest('table')) {
  593. return element.nextElementSibling?.nodeName === 'P'
  594. }
  595. return true
  596. },
  597. end: () => '\n\n',
  598. }),
  599. createSelector({
  600. selector: 'blockquote',
  601. start: () => `\n\n\\begin{quote}\n`,
  602. end: () => `\n\\end{quote}\n\n`,
  603. }),
  604. ]