| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
""" |
| 4 |
Copyright (c) 2022 Rafał Lalik <[email protected]> |
| 5 |
|
| 6 |
Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 |
of this software and associated documentation files (the "Software"), to deal |
| 8 |
in the Software without restriction, including without limitation the rights |
| 9 |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 |
copies of the Software, and to permit persons to whom the Software is |
| 11 |
furnished to do so, subject to the following conditions: |
| 12 |
|
| 13 |
The above copyright notice and this permission notice shall be included in all |
| 14 |
copies or substantial portions of the Software. |
| 15 |
|
| 16 |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 |
SOFTWARE. |
| 23 |
""" |
| 24 |
|
| 25 |
import argparse |
| 26 |
import xml.etree.ElementTree as ET |
| 27 |
import pygments.lexers as pyglex |
| 28 |
import re |
| 29 |
import yaml |
| 30 |
from itertools import combinations |
| 31 |
from colorama import Fore, Back, Style |
| 32 |
#from fuzzywuzzy import fuzz |
| 33 |
|
| 34 |
def main(): |
| 35 |
parser = argparse.ArgumentParser() |
| 36 |
parser.add_argument('-o', '--output', help='output file', type=str, default="lexers_found.xml") |
| 37 |
parser.add_argument('-v', '--verbose', help='verbose mode', action='store_true', default=False) |
| 38 |
opts, args = parser.parse_known_args() |
| 39 |
if opts.verbose: |
| 40 |
print("Options: ", opts, args) |
| 41 |
|
| 42 |
with open('config.yml', 'r') as file: |
| 43 |
config = yaml.safe_load(file) |
| 44 |
print(config) |
| 45 |
|
| 46 |
pygment_lexers = list(pyglex.get_all_lexers()) |
| 47 |
|
| 48 |
kde_langs = [] |
| 49 |
|
| 50 |
for xmlfile in args: |
| 51 |
if xmlfile == 'latex.xml': |
| 52 |
continue |
| 53 |
#print(f"Read {xmlfile}") |
| 54 |
rc = parseXML(xmlfile) |
| 55 |
if rc is not None: |
| 56 |
print(f"Found '{rc}' language syntax file") |
| 57 |
kde_langs.append(rc) |
| 58 |
|
| 59 |
if opts.verbose: |
| 60 |
print("***\nKDE languages: ", kde_langs) |
| 61 |
print("***\nPygments lexers: ", pygment_lexers, f"total = {len(pygment_lexers)}") |
| 62 |
print("\n***\nSearch for KDE lexer") |
| 63 |
|
| 64 |
matched_lexers = [] |
| 65 |
minted_used_lexers = set() |
| 66 |
for kde_lang in kde_langs: |
| 67 |
lower_kl = kde_lang.lower() |
| 68 |
|
| 69 |
if kde_lang in config['minted_mapping']: |
| 70 |
val_of_minted_mapping = config['minted_mapping'][kde_lang] |
| 71 |
if opts.verbose: |
| 72 |
print(Fore.YELLOW + f"+ Mapped KDE lang '{kde_lang}' to minted lang '{val_of_minted_mapping}'" + Style.RESET_ALL) |
| 73 |
|
| 74 |
lexers = list(filter(lambda x: x[0] == val_of_minted_mapping, pygment_lexers)) |
| 75 |
if len(lexers): |
| 76 |
#print(f"Lexers are {lexers[0][1]} from {pygment_lexers} and {kde_lang}") |
| 77 |
selected_lexers = filter_minted_lexers(lexers[0], config['minted_blacklisted'], minted_used_lexers) |
| 78 |
|
| 79 |
matched_lexers.append([kde_lang, val_of_minted_mapping, selected_lexers]) |
| 80 |
else: |
| 81 |
if opts.verbose: |
| 82 |
print(Fore.RED + f"No lexers from {pygment_lexers} and {kde_lang}" + Style.RESET_ALL) |
| 83 |
continue |
| 84 |
|
| 85 |
key_of_minted_matching = list(filter(lambda x: x[0].casefold() == kde_lang.casefold(), pygment_lexers)) |
| 86 |
if len(key_of_minted_matching): |
| 87 |
if opts.verbose: |
| 88 |
print(Fore.GREEN + f"+ Matched KDE lang '{kde_lang}' to minted lang '{key_of_minted_matching[0][0]}'" + Style.RESET_ALL) |
| 89 |
|
| 90 |
selected_lexers = filter_minted_lexers(key_of_minted_matching[0], config['minted_blacklisted'], minted_used_lexers) |
| 91 |
|
| 92 |
matched_lexers.append([kde_lang, key_of_minted_matching[0][0], selected_lexers]) |
| 93 |
continue |
| 94 |
|
| 95 |
#klm = max(kde_langs, key=lambda x: fuzz.ratio(ll[0].lower(), x.lower())) |
| 96 |
#klf = fuzz.ratio(ll[0].lower(), klm.lower()) |
| 97 |
##print(f" Fuzz znalazł '{klm}'={klf} dla szukanego '{ll[1]}'") |
| 98 |
#if klf > int(config['fuzz_level']): |
| 99 |
#print(Fore.YELLOW + f"+ Fuzzed lexer '{ll[0]}' ({klf}) lang '{ll[1]}' with KDE lang '{klm}'" + Style.RESET_ALL) |
| 100 |
##matched_lexers.append([ll[0], klm, ll[1]]) |
| 101 |
#else: |
| 102 |
if opts.verbose: |
| 103 |
print(Fore.RED + f"- Lexer for KDE lang '{kde_lang}' not found" + Style.RESET_ALL) |
| 104 |
|
| 105 |
generate_output(matched_lexers, opts.output) |
| 106 |
|
| 107 |
|
| 108 |
def generate_output(lexers, filename): |
| 109 |
print("\n***\nGenerate outputs") |
| 110 |
|
| 111 |
used_codes = [] |
| 112 |
with open(filename, "w") as f: |
| 113 |
f.write(' <list name="MintedCodeLang">\n') |
| 114 |
last_lang = None |
| 115 |
|
| 116 |
for code,lang,ll in lexers: |
| 117 |
if last_lang is None or last_lang is not lang: |
| 118 |
f.write(f" <!-- {code} lexers -->\n") |
| 119 |
|
| 120 |
for l in ll: |
| 121 |
f.write(f" <item>{l}code*</item>\n") |
| 122 |
f.write(f" <item>{l}code</item>\n") |
| 123 |
f.write(' </list>\n') |
| 124 |
|
| 125 |
used_langs = [] |
| 126 |
mintenv_list = [] |
| 127 |
f.write('\n\n\n\n\n') |
| 128 |
f.write(' <!-- environment type 5: minted environment created with newminted -->\n') |
| 129 |
f.write(' <context name="MintedCodeEnv" attribute="Environment" lineEndContext="#stay" fallthroughContext="#pop#pop#pop#pop">\n') |
| 130 |
for code,lang,ll in lexers: |
| 131 |
for l in ll: |
| 132 |
f.write(f' <WordDetect String="{l}code*" attribute="Environment" context="Highlighting{code}CodeEnvS"/>\n'); |
| 133 |
f.write(f' <WordDetect String="{l}code" attribute="Environment" context="Highlighting{code}CodeEnv"/>\n'); |
| 134 |
|
| 135 |
mintenv_list.append(f' <WordDetect String="{l}" insensitive="true" context="Highlighting{code}CodeEnv"/>\n') |
| 136 |
|
| 137 |
f.write(''' <RegExpr String=".+code\*" attribute="Environment" context="UnknownHighlightingCodeEnvS"/> |
| 138 |
<RegExpr String=".+code" attribute="Environment" context="UnknownHighlightingCodeEnv"/> |
| 139 |
</context>\n\n''') |
| 140 |
|
| 141 |
|
| 142 |
f.write(' <context name="HighlightingSelector" attribute="Normal Text" lineEndContext="#stay">\n') |
| 143 |
f.write(''.join(mintenv_list)) |
| 144 |
f.write(''' <AnyChar String="}]" context="#pop!UnknownHighlightingBegin"/> |
| 145 |
<RegExpr String="[^]}]*" context="#stay"/> |
| 146 |
</context> |
| 147 |
''') |
| 148 |
f.write('\n') |
| 149 |
f.write(''' <context name="HighlightingCommon" attribute="Normal Text" lineEndContext="#stay"> |
| 150 |
<RegExpr String="\\\\end\s*\{(?:lstlisting|minted|[a-zA-Z]+code)\*?\}" attribute="Structure" lookAhead="true" context="#pop#pop#pop#pop#pop#pop"/> |
| 151 |
</context>\n''') |
| 152 |
|
| 153 |
|
| 154 |
for code,lang,ll in lexers: |
| 155 |
f.write(''' |
| 156 |
<context name="Highlighting{0}CodeEnvS" attribute="Error" lineEndContext="#stay"> |
| 157 |
<DetectSpaces/> |
| 158 |
<DetectChar char="{2}" attribute="Normal Text" context="#pop!Highlighting{0}CodeEnvSParam"/> |
| 159 |
</context> |
| 160 |
<context name="Highlighting{0}CodeEnvSParam" attribute="Error" lineEndContext="#stay"> |
| 161 |
<DetectSpaces attribute="Normal Text"/> |
| 162 |
<DetectChar char="{1}" attribute="Normal Text" context="Highlighting{0}CodeEnvSParamInside"/> |
| 163 |
<IncludeRules context="FindComments"/> |
| 164 |
</context> |
| 165 |
<context name="Highlighting{0}CodeEnvSParamInside" attribute="Normal Text" lineEndContext="#stay"> |
| 166 |
<DetectSpaces/> |
| 167 |
<DetectIdentifier/> |
| 168 |
<DetectChar char="{2}" attribute="Normal Text" context="#pop!HighlightingBegin{0}"/> |
| 169 |
<IncludeRules context="FindComments"/> |
| 170 |
<RegExpr String="\&envname;" attribute="Macro" context="#stay"/> |
| 171 |
</context> |
| 172 |
<context name="Highlighting{0}CodeEnv" attribute="Normal Text" lineEndContext="#stay"> |
| 173 |
<DetectChar char="{2}" context="HighlightingBegin{0}"/> |
| 174 |
<RegExpr String="[^{2}]*" attribute="Normal Text" context="#stay"/> |
| 175 |
</context> |
| 176 |
<context name="HighlightingBegin{0}" attribute="Normal Text" lineEndContext="#pop!Highlighting{0}"> |
| 177 |
<DetectSpaces/> |
| 178 |
<RegExpr String=".+" attribute="Error" context="#stay"/> |
| 179 |
</context> |
| 180 |
<context name="Highlighting{0}" attribute="Normal Text" lineEndContext="#stay"> |
| 181 |
<IncludeRules context="HighlightingCommon"/> |
| 182 |
<IncludeRules context="##{0}" includeAttrib="true"/> |
| 183 |
</context> |
| 184 |
'''.format(code, '{', '}')) |
| 185 |
|
| 186 |
f.write(' <!-- end of mintedcode environment -->\n') |
| 187 |
|
| 188 |
|
| 189 |
def filter_minted_lexers(lexers_list, blacklist, used_lexers): |
| 190 |
"""Loop over lexers, filter out blacklisted and simplify names, pick up uniques""" |
| 191 |
selected = set() |
| 192 |
current_set = set() |
| 193 |
|
| 194 |
name_filter = r"^[^a-z]+|[^a-z]+$" |
| 195 |
|
| 196 |
for ll in lexers_list[1]: |
| 197 |
if ll in blacklist: |
| 198 |
print(f" Ignore blacklisted '{ll[1]}' lexer") |
| 199 |
continue |
| 200 |
|
| 201 |
new_ll = ll |
| 202 |
#rc = re.search(name_filter, new_ll) |
| 203 |
#new_ll = re.sub(r"[^a-z]", "", ll[0]) |
| 204 |
new_ll = re.sub(r"\+\+", "pp", new_ll) |
| 205 |
new_ll = re.sub(r"\#", "sharp", new_ll) |
| 206 |
new_ll = re.sub(r"[^a-z]", "", new_ll) |
| 207 |
#new_ll = re.sub(r"[0-9]", "", new_ll) |
| 208 |
|
| 209 |
if new_ll != ll: |
| 210 |
print(f" {ll} => {new_ll}" + Fore.YELLOW + " - Replaced" + Style.RESET_ALL) |
| 211 |
|
| 212 |
rc = re.search(name_filter, new_ll) |
| 213 |
if rc is not None: |
| 214 |
print(f" {ll} => {new_ll}" + Fore.RED + " - Removed" + Style.RESET_ALL) |
| 215 |
continue |
| 216 |
|
| 217 |
if new_ll in used_lexers: |
| 218 |
print(f" {ll} => {new_ll}" + Fore.RED + " - Ignored" + Style.RESET_ALL) |
| 219 |
continue |
| 220 |
|
| 221 |
print(f" {ll} => {new_ll}" + Fore.GREEN + " - Added" + Style.RESET_ALL) |
| 222 |
selected.add(new_ll) |
| 223 |
|
| 224 |
used_lexers.update(selected) # update set of all lexers |
| 225 |
return sorted(selected) |
| 226 |
|
| 227 |
|
| 228 |
def search_lexer(langname, pygment_lexers): |
| 229 |
for l in pygment_lexers: |
| 230 |
#print(l) |
| 231 |
if langname.lower() in (x.lower() for x in l[1]): |
| 232 |
return l[0] |
| 233 |
|
| 234 |
return None |
| 235 |
|
| 236 |
|
| 237 |
def split_lexers(lexers): |
| 238 |
"""Get pygments language with lexers and create all lexers list""" |
| 239 |
lexers_list = [] |
| 240 |
for l in lexers: |
| 241 |
for ll in l[1]: |
| 242 |
lexers_list.append([ll, l[0], False]) |
| 243 |
|
| 244 |
return lexers_list |
| 245 |
|
| 246 |
|
| 247 |
def parseXML(xmlfile): |
| 248 |
tree = ET.parse(xmlfile) |
| 249 |
root = tree.getroot(); |
| 250 |
if root.tag == 'language': |
| 251 |
langname = root.attrib['name'] |
| 252 |
rc = root.find('highlighting') |
| 253 |
if rc is None: |
| 254 |
if opts.verbose: |
| 255 |
print(f"Language {langname} has no highlightng") |
| 256 |
return None |
| 257 |
|
| 258 |
return langname |
| 259 |
return None |
| 260 |
|
| 261 |
if __name__ == '__main__': |
| 262 |
main() |