Skip to content

Commit 92a7db1

Browse files
committed
Adv. option for custom styles; Refactoring; Better error handling
1 parent 3e71fa8 commit 92a7db1

File tree

4 files changed

+41
-18
lines changed

4 files changed

+41
-18
lines changed

docs/description.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ An overview of the most important changes in this release follows below:
2929
- **New**: Anki 2.1 compatibility
3030
- **New**: Option to apply syntax highlighting via CSS (thanks to [Tim Rae](https://github.com/timrae/SyntaxHighlight)!)
3131
- **New**: Ability to customize language selection and hotkey
32+
- **New**: Ability to customize [syntax highlighting theme](https://help.farbox.com/pygments.html)
3233
- **New**: Upgraded pygments from v1.6 to v2.2.0. This is a [major jump](http://pygments.org/docs/changelog/#version-2-2-0) and should come with a lot of added functionality in terms of supported languages and language features
3334
- **Fixed**: Position options dialog correctly
3435
- **Fixed**: Various improvements and bug fixes (e.g. the ImportErrors and KeyErrors frequently reported in earlier reviews)
@@ -71,6 +72,7 @@ The following options may be customized:
7172

7273
- `hotkey` [string]: Add-on invocation hotkey. Default: `Alt+S`
7374
- `limitToLags` [list]: List of programming languages to limit combobox menu to. Default: `[]` (i.e. no limit). Example: `["Python", "Java", "JavaScript"]`.
75+
- `style` [string]: Pre-defined [pygments style](https://help.farbox.com/pygments.html) to use for inline styling of code (not applicable to CSS mode). Default: `default`. Example: `monokai`.
7476

7577
These advanced settings do not sync and require a restart to apply.
7678

src/syntax_highlighting/config.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
{
22
"hotkey": "Alt+s",
3-
"limitToLangs": []
3+
"limitToLangs": [],
4+
"style": "default"
45
}

src/syntax_highlighting/config.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33
These advanced settings do not sync and require a restart to apply.
44

55
- `hotkey` [string]: Add-on invocation hotkey. Default: `Alt+S`
6-
- `limitToLags` [list]: List of programming languages to limit combobox menu to. Default: `[]` (i.e. no limit). Example: `["Python", "Java", "JavaScript"]`.
6+
- `limitToLags` [list]: List of programming languages to limit combobox menu to. Default: `[]` (i.e. no limit). Example: `["Python", "Java", "JavaScript"]`.
7+
- `style` [string]: Pre-defined [pygments style](https://help.farbox.com/pygments.html) to use for inline styling of code (not applicable to CSS mode). Default: `default`. Example: `monokai`.

src/syntax_highlighting/main.py

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,15 @@
2929
from aqt.qt import *
3030
from aqt import mw
3131
from aqt.editor import Editor
32-
from aqt.utils import tooltip
32+
from aqt.utils import showWarning
3333
from anki.utils import json
3434
from anki.hooks import addHook, wrap
3535

3636
from .config import local_conf
3737

3838

3939
HOTKEY = local_conf["hotkey"]
40+
STYLE = local_conf["style"]
4041
LIMITED_LANGS = local_conf["limitToLangs"]
4142

4243
# This code sets a correspondence between:
@@ -51,6 +52,16 @@
5152
"If you set a custom lang selection please make sure<br>"
5253
"you typed all list entries correctly.")
5354

55+
ERR_STYLE = ("<b>Error</b>: Selected style not found.<br>"
56+
"If you set a custom style please make sure<br>"
57+
"you typed it correctly.")
58+
59+
60+
# Misc
61+
62+
def showError(msg, parent):
63+
showWarning(msg, title="Syntax Highlighting Error", parent=parent)
64+
5465
# Synced options and corresponding dialogs
5566

5667
def get_deck_name(mw):
@@ -273,8 +284,9 @@ def addWidgets20(ed, previous_lang):
273284
def onCodeHighlightLangSelect(ed, lang):
274285
try:
275286
alias = LANGUAGES_MAP[lang]
276-
except KeyError:
277-
tooltip(ERR_LEXER)
287+
except KeyError as e:
288+
print(e)
289+
showError(ERR_LEXER, parent=ed.parentWindow)
278290
ed.codeHighlightLangAlias = ""
279291
return False
280292
set_default_lang(mw, lang)
@@ -288,11 +300,11 @@ def onCodeHighlightLangSelect(ed, lang):
288300
"""style='vertical-align: top;'>{}</select>""")
289301

290302

291-
def onSetupButtons21(buttons, editor):
303+
def onSetupButtons21(buttons, ed):
292304
"""Add buttons to Editor for Anki 2.1.x"""
293305
# no need for a lambda since onBridgeCmd passes current editor instance
294306
# to method anyway (cf. "self._links[cmd](self)")
295-
b = editor.addButton(icon_path, "CH", highlight_code,
307+
b = ed.addButton(icon_path, "CH", highlight_code,
296308
tip="Paste highlighted code ({})".format(HOTKEY),
297309
keys=HOTKEY)
298310
buttons.append(b)
@@ -318,17 +330,17 @@ def onSetupButtons21(buttons, editor):
318330
return buttons
319331

320332

321-
def onBridgeCmd(self, cmd, _old):
333+
def onBridgeCmd(ed, cmd, _old):
322334
if not cmd.startswith("shLang"):
323-
return _old(self, cmd)
335+
return _old(ed, cmd)
324336
(type, lang) = cmd.split(":")
325-
onCodeHighlightLangSelect(self, lang)
337+
onCodeHighlightLangSelect(ed, lang)
326338

327339

328340
# Actual code highlighting
329341

330342

331-
def highlight_code(self):
343+
def highlight_code(ed):
332344
addon_conf = mw.col.conf['syntax_highlighting_conf']
333345

334346
# Do we want line numbers? linenos is either true or false according
@@ -343,7 +355,7 @@ def highlight_code(self):
343355
# setting the styling on every note type where code is used
344356
noclasses = not addon_conf['cssclasses']
345357

346-
selected_text = self.web.selectedText()
358+
selected_text = ed.web.selectedText()
347359
if selected_text:
348360
# Sometimes, self.web.selectedText() contains the unicode character
349361
# '\u00A0' (non-breaking space). This character messes with the
@@ -355,18 +367,25 @@ def highlight_code(self):
355367
# Get the code from the clipboard
356368
code = clipboard.text()
357369

358-
langAlias = self.codeHighlightLangAlias
370+
langAlias = ed.codeHighlightLangAlias
359371

360372
# Select the lexer for the correct language
361373
try:
362374
my_lexer = get_lexer_by_name(langAlias, stripall=True)
363-
except ClassNotFound:
364-
tooltip(ERR_LEXER)
375+
except ClassNotFound as e:
376+
print(e)
377+
showError(ERR_LEXER, parent=ed.parentWindow)
365378
return False
366379

367380
# Create html formatter object including flags for line nums and css classes
368-
my_formatter = HtmlFormatter(
369-
linenos=linenos, noclasses=noclasses, font_size=16)
381+
try:
382+
my_formatter = HtmlFormatter(
383+
linenos=linenos, noclasses=noclasses,
384+
font_size=16, style=STYLE)
385+
except ClassNotFound as e:
386+
print(e)
387+
showError(ERR_STYLE, parent=ed.parentWindow)
388+
return False
370389

371390
if linenos:
372391
if centerfragments:
@@ -388,7 +407,7 @@ def highlight_code(self):
388407
"</td></tr></tbody></table><br>"])
389408

390409
# These two lines insert a piece of HTML in the current cursor position
391-
self.web.eval("document.execCommand('inserthtml', false, %s);"
410+
ed.web.eval("document.execCommand('inserthtml', false, %s);"
392411
% json.dumps(pretty_code))
393412

394413

0 commit comments

Comments
 (0)