convert.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /**
  2. Convert Ace themes to CodeMirror 6
  3. Tokens:
  4. https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode#common-tokens
  5. Highlight Rules:
  6. https://github.com/overleaf/ace/blob/overleaf/lib/ace/mode/latex_highlight_rules.js
  7. Conversion of TextMate themes to Ace:
  8. https://github.com/ajaxorg/ace/wiki/Importing-.tmtheme-and-.tmlanguage-Files-into-Ace
  9. https://github.com/ajaxorg/ace/blob/master/tool/tmtheme.js
  10. */
  11. const fs = require('fs')
  12. const globby = require('globby')
  13. const mensch = require('mensch')
  14. const path = require('path')
  15. const overrides = require('./overrides.json')
  16. const { merge } = require('lodash')
  17. // CSS files from https://github.com/overleaf/ace/tree/overleaf/lib/ace/theme copied into the "ace" folder
  18. const themePaths = globby.sync(['ace/*.css'], { cwd: path.dirname(__dirname) })
  19. const outputDir = path.join(path.dirname(__dirname), 'cm6')
  20. // from js/ide.js
  21. const darkThemes = [
  22. 'ambiance',
  23. 'chaos',
  24. 'clouds_midnight',
  25. 'cobalt',
  26. 'dracula',
  27. 'gob',
  28. 'gruvbox',
  29. 'idle_fingers',
  30. 'kr_theme',
  31. 'merbivore',
  32. 'merbivore_soft',
  33. 'mono_industrial',
  34. 'monokai',
  35. 'nord_dark',
  36. 'pastel_on_dark',
  37. 'solarized_dark',
  38. 'terminal',
  39. 'tomorrow_night',
  40. 'tomorrow_night_blue',
  41. 'tomorrow_night_bright',
  42. 'tomorrow_night_eighties',
  43. 'twilight',
  44. 'vibrant_ink',
  45. ]
  46. // manual mapping of Ace selectors to CM6 theme selectors
  47. const themeMapping = new Map([
  48. ['.ace_gutter', '.cm-gutters'],
  49. ['.ace_cursor', '.cm-cursor, .cm-dropCursor'],
  50. [
  51. '.ace_marker-layer .ace_selection',
  52. '&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection, .cm-searchMatch.cm-searchMatch.cm-searchMatch-selected',
  53. ],
  54. [
  55. '.ace_marker-layer .ace_selected-word',
  56. '.cm-selectionMatch.cm-selectionMatch, .cm-searchMatch.cm-searchMatch', // doubled to increase specificity over defaults
  57. ],
  58. [
  59. '.ace_marker-layer .ace_bracket',
  60. '&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket',
  61. ],
  62. ['.ace_marker-layer .ace_bracket-unmatched', '.cm-nonmatchingBracket'],
  63. ['.ace_marker-layer .ace_active-line', '.cm-activeLine'],
  64. ['.ace_gutter-active-line', '.cm-activeLineGutter'],
  65. ['.ace_fold', '.cm-foldPlaceholder'],
  66. ])
  67. const propertyRemapping = new Map([
  68. [
  69. '&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket',
  70. [['border', 'outline']],
  71. ],
  72. [
  73. '.cm-selectionMatch.cm-selectionMatch, .cm-searchMatch.cm-searchMatch',
  74. [['border', 'outline']],
  75. ],
  76. ])
  77. function remap(selector, rule) {
  78. const remappings = propertyRemapping.get(selector) ?? []
  79. for (const [oldKey, newKey] of remappings) {
  80. if (newKey in rule) {
  81. throw new Error(
  82. `Invalid remapping. Property ${newKey} already exists in rule '${selector}'`
  83. )
  84. }
  85. if (oldKey in rule) {
  86. rule[newKey] = rule[oldKey]
  87. delete rule[oldKey]
  88. }
  89. }
  90. return rule
  91. }
  92. // manual mapping of Ace selectors to CM6 highlight style selectors
  93. // https://codemirror.net/6/docs/ref/#highlight.tags
  94. // (the classHighlightStyle extension adds the class names for styling)
  95. const highlightStyleMapping = new Map([
  96. // ['.ace_support.ace_type', '.tok-typeName'],
  97. ['.ace_class', '.tok-class'],
  98. ['.ace_comment', '.tok-comment'],
  99. ['.ace_constant', '.tok-labelName'],
  100. ['.ace_constant.ace_character', '.tok-literal'],
  101. ['.ace_constant.ace_character.ace_escape', '.tok-literal'], // escape
  102. ['.ace_constant.ace_language', '.tok-literal'], // constant
  103. ['.ace_constant.ace_numeric', '.tok-literal'], // number
  104. ['.ace_constant.ace_other', '.tok-literal'], // constant
  105. ['.ace_entity.ace_name.ace_function', '.tok-function'],
  106. ['.ace_entity.ace_name.ace_tag', '.tok-tagName'],
  107. ['.ace_entity.ace_other.ace_attribute-name', '.tok-attributeName'],
  108. ['.ace_heading', '.tok-heading'],
  109. ['.ace_identifier', '.tok-string'], // TODO: identifier?
  110. ['.ace_invalid', '.tok-invalid'],
  111. ['.ace_keyword', '.tok-keyword'], // typeName?
  112. ['.ace_keyword.ace_operator', '.tok-operator'],
  113. ['.ace_list', '.tok-list'],
  114. ['.ace_lparen', '.tok-paren'],
  115. ['.ace_markup.ace_heading', '.tok-heading'],
  116. ['.ace_markup.ace_list', '.tok-list'],
  117. ['.ace_numeric', '.tok-number'],
  118. ['.ace_punctuation', '.tok-punctuation'],
  119. ['.ace_regexp', '.tok-string2'],
  120. ['.ace_rparen', '.tok-paren'],
  121. ['.ace_storage', '.tok-typeName'],
  122. ['.ace_storage.ace_type', '.tok-typeName'],
  123. ['.ace_string', '.tok-string'],
  124. ['.ace_string.ace_regexp', '.tok-regexp'],
  125. // ['.ace_support.ace_class', '.tok-className'],
  126. // ['.ace_support.ace_constant', '.tok-constant'],
  127. // ['.ace_support.ace_function', '.tok-function'],
  128. // ['.ace_support.ace_type', '.tok-function'],
  129. ['.ace_type', '.tok-typeName'],
  130. ['.ace_variable', '.tok-attributeValue'], // keyword // variableName
  131. ['.ace_variable.ace_language', '.tok-variableName'],
  132. ['.ace_variable.ace_parameter', '.tok-attributeValue'], // string
  133. ])
  134. for (const themePath of themePaths) {
  135. console.log(themePath)
  136. const input = fs.readFileSync(path.join(__dirname, themePath), 'utf-8')
  137. const ast = mensch.parse(input)
  138. const themeStyles = {
  139. // these styles should only be set if they're defined in a theme
  140. '.cm-gutters': {
  141. backgroundColor: 'transparent',
  142. borderRightColor: 'transparent',
  143. },
  144. }
  145. const highlightStyles = {}
  146. for (const rule of ast.stylesheet.rules) {
  147. const declarations = {}
  148. rule.declarations
  149. .filter(item => item.type === 'property')
  150. .forEach(declaration => {
  151. // convert CSS property to snake case
  152. const property = declaration.name.replace(/-(\w)/g, (_, letter) => {
  153. return letter.toUpperCase()
  154. })
  155. declarations[property] = declaration.value
  156. })
  157. for (const item of rule.selectors) {
  158. // ignore the first selector, which is the theme class
  159. const selector = item.split(/\s+/).slice(1).join(' ')
  160. // an empty selector was the theme class selector for the whole editor
  161. if (selector === '') {
  162. themeStyles['&'] = {
  163. ...themeStyles['&'],
  164. ...declarations,
  165. }
  166. continue
  167. }
  168. if (themeMapping.has(selector)) {
  169. const key = themeMapping.get(selector)
  170. themeStyles[key] = remap(key, {
  171. ...themeStyles[key],
  172. ...declarations,
  173. })
  174. } else if (highlightStyleMapping.has(selector)) {
  175. const key = highlightStyleMapping.get(selector)
  176. highlightStyles[key] = remap(key, {
  177. ...highlightStyles[key],
  178. ...declarations,
  179. })
  180. }
  181. }
  182. }
  183. console.log('theme', themeStyles)
  184. console.log('highlight', highlightStyles)
  185. const basename = path.basename(themePath, '.css')
  186. const themeOverrides = merge({}, overrides.all, overrides[basename])
  187. const theme = merge({}, themeStyles, themeOverrides.theme)
  188. const highlightStyle = merge(
  189. {},
  190. highlightStyles,
  191. themeOverrides.highlightStyle
  192. )
  193. const dark = darkThemes.includes(basename)
  194. const output = JSON.stringify({ theme, highlightStyle, dark }, null, 2)
  195. const outputPath = path.join(outputDir, `${basename}.json`)
  196. fs.writeFileSync(outputPath, output + '\n')
  197. if (basename !== 'overleaf') {
  198. copyLicense(basename)
  199. }
  200. }
  201. function copyLicense(basename) {
  202. const jsFilePath = path.join(__dirname, 'ace', `${basename}.js`)
  203. if (fs.existsSync(jsFilePath)) {
  204. const js = fs.readFileSync(jsFilePath, 'utf-8')
  205. const match = js.match(/\*+ BEGIN LICENSE BLOCK .+? END LICENSE BLOCK \*+/s)
  206. if (match) {
  207. const license = match[0].replace(/\n \* ?/g, '\n')
  208. const output = `Conversion by Overleaf from Ace to CodeMirror 6.\n\nSource: https://github.com/ajaxorg/ace/\n\nThe theme's original license is copied below:\n\n${license}`
  209. const licenseOutputPath = path.join(outputDir, `${basename}-license.txt`)
  210. fs.writeFileSync(licenseOutputPath, output)
  211. } else {
  212. console.warn(`No license in ${jsFilePath}`)
  213. }
  214. } else {
  215. console.warn(`No license file for ${basename}`)
  216. }
  217. }