macrogen.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import xml.etree.ElementTree as ET
  2. import re, sys, os
  3. replace = (
  4. ("Math\\.Max\\(", "Math.max("),
  5. ("Math\\.Min\\(", "Math.min("),
  6. ("Math\\.Sqrt\\(", "Math.sqrt("),
  7. ("Math\\.Abs\\(", "Math.abs("),
  8. ("Math\\.Pow\\(", "Math.pow("),
  9. ("Math\\.Ceiling", "Math.ceil"),
  10. ("Math\\.Floor", "Math.floor"),
  11. ("var ", "let "),
  12. ("new List<List<([a-zA-Z]*)>>\(\)", "[]"),
  13. ("List<List<([a-zA-Z]*)>>", "$1[][]"),
  14. ("new List<([a-zA-Z]*)>\(\)", "[]"),
  15. ("List<([a-zA-Z]*)>", "$1[]"),
  16. ("IEnumerable<([a-zA-Z0-9]+)>", "$1[]"),
  17. ("\\.Count", ".length"),
  18. ("\\.Length", ".length"),
  19. ("\\.Add\(", ".push("),
  20. ("\\.First\(\)", "[0]"),
  21. ("\\.Insert\((.*), (.*)\)", ".splice($1, 0, $2)"),
  22. ("\\.RemoveAt\(([a-z|0-9]+)\)", ".splice($1, 1)"),
  23. ("\\.Clear\(\);", ".length = 0;"),
  24. ("\\.IndexOf", ".indexOf"),
  25. ("\\.ToArray\\(\\)", ""),
  26. ("\\.Contains\(([a-zA-Z0-9.]+)\)", ".indexOf($1) !== -1"),
  27. ("for each(?:[ ]*)\(([a-z|0-9]+) ([a-z|0-9]+) in ([a-z|0-9]+)\)", "for ($2 of $3)"),
  28. (", len([0-9]*) = ", ", len$1: number = "),
  29. (" == ", " === "),
  30. (" != ", " !== "),
  31. ("null", "undefined"),
  32. ("\\.ToLower\(\)", ".toLowerCase()"),
  33. ("Logger\\.DefaultLogger\\.LogError\(LogLevel\\.DEBUG,(?:[ ]*)", "Logging.debug("),
  34. ("Logger\\.DefaultLogger\\.LogError\(LogLevel\\.NORMAL,(?:[ ]*)", "Logging.log("),
  35. ("Logger\\.DefaultLogger\\.LogError\(PhonicScore\\.Common\\.Enums\\.LogLevel\\.NORMAL,(?:[ ]*)", "Logging.log("),
  36. ("Fraction\\.CreateFractionFromFraction\(([a-z|0-9]+)\)", "$1.clone()"),
  37. ("(\d{1})f([,;)\]} ])", "$1$2"),
  38. ("number\\.MaxValue", "Number.MAX_VALUE"),
  39. ("Int32\\.MaxValue", "Number.MAX_VALUE"),
  40. ("number\\.MinValue", "Number.MIN_VALUE"),
  41. ("__as__<([A-Za-z|0-9]+)>\(([A-Za-z|0-9.]+), ([A-Za-z|0-9]+)\)", "($2 as $3)"),
  42. ("new Dictionary<number, number>\(\)", "{}"),
  43. (": Dictionary<number, number>", ": {[_: number]: number; }"),
  44. ("String\\.Empty", '""'),
  45. ("return\\n", "return;\n"),
  46. ("}(\n[ ]*)else ", "} else "),
  47. ("\\.IdInMusicSheet", ".idInMusicSheet"),
  48. ("F_2D", "F2D"),
  49. )
  50. def checkForIssues(filename, content):
  51. if ".Last()" in content:
  52. print(" !!! Warning: .Last() found !!!")
  53. def applyAll():
  54. root = sys.argv[1]
  55. filenames = []
  56. if os.path.isdir(root):
  57. recurse(root, filenames)
  58. else:
  59. filenames.append(root)
  60. print("Apply replacements to:")
  61. for filename in filenames:
  62. print(" >>> " + os.path.basename(filename))
  63. content = None
  64. with open(filename) as f:
  65. content = f.read()
  66. checkForIssues(filename, content)
  67. for rep in replace:
  68. content = re.sub(rep[0], pythonic(rep[1]), content)
  69. with open(filename, "w") as f:
  70. f.write(content)
  71. print("Done.")
  72. def recurse(folder, files):
  73. if os.path.isfile(folder):
  74. files.append(folder)
  75. if os.path.isdir(folder):
  76. files.extend(os.path.join(folder, i) for i in os.listdir(folder))
  77. def keycode(c):
  78. if len(c) > 1:
  79. return ";".join(keycode(i) for i in c)
  80. if c.isalpha():
  81. return str(ord(c.upper())) + ":" + ("1" if c.isupper() else "0")
  82. if c.isdigit():
  83. return str(48 + int(c)) + ":0"
  84. return {'!': '49:1', '#': '51:1', '%': '53:1', '$': '52:1', "'": '222:0', '&': '55:1', ')': '48:1', '(': '57:1', '+': '61:1', '*': '56:1', '-': '45:0', ',': '44:0', '/': '47:0', '.': '46:0', ';': '59:0', ':': '59:1', '=': '61:0', '@': '50:1', '[': '91:0', ']': '93:0', '\\': '92:0', '_': '45:1', '^': '54:1', 'a': '65:0', '<': '44:1', '>': '46', ' ': "32:0", "|": "92:1", "?": "47:1", "{": "91:1", "}": "93:1"}[c]
  85. def escape(s):
  86. return s
  87. return s.replace("&", "&amp;").replace(">", "&gt;").replace("<", "&lt;")
  88. def generate():
  89. N = 0
  90. macroName = "TypeScript'ing Replacements"
  91. macro = ET.Element("macro")
  92. macro.set("name", macroName)
  93. replace = (("ABCDEfGHIJKL", "ABCDEfGHIJKL"),) + replace
  94. for rep in replace:
  95. N += 1
  96. # result.append('<macro name="%d">' % N)
  97. ET.SubElement(macro, "action").set("id", "$SelectAll")
  98. ET.SubElement(macro, "action").set("id", "Replace")
  99. for s in rep[0]:
  100. t = ET.SubElement(macro, "typing")
  101. t.set("text-keycode", keycode(s))
  102. t.text = escape(s)
  103. ET.SubElement(macro, "shortuct").set("text", "TAB")
  104. for s in rep[1]:
  105. t = ET.SubElement(macro, "typing")
  106. t.set("text-keycode", keycode(s))
  107. t.text = escape(s)
  108. # result.append('<action id="EditorEnter" />' * 50)
  109. for i in range(50):
  110. ET.SubElement(macro, "shortuct").set("text", "ENTER")
  111. ET.SubElement(macro, "shortuct").set("text", "ESCAPE")
  112. path = '/Users/acondolu/Library/Preferences/WebStorm11/options/macros.xml'
  113. tree = None
  114. try:
  115. tree = ET.parse(path)
  116. except IOError:
  117. print("Cannot find macro file.")
  118. sys.exit(1)
  119. component = tree.getroot().find("component")
  120. assert component.get("name") == "ActionMacroManager"
  121. found = None
  122. for m in component.iter("macro"):
  123. if m.get("name") == macroName:
  124. found = m
  125. break
  126. if found is not None:
  127. component.remove(found)
  128. component.append(macro)
  129. tree.write(path)
  130. print("Macro written on " + path)
  131. def pythonic(s):
  132. return s.replace("$", "\\")
  133. if __name__ == "__main__":
  134. if len(sys.argv) != 2:
  135. print("Usage: python macrogen.py path/to/files")
  136. sys.exit(1)
  137. # generate()
  138. else:
  139. applyAll()