Skip to content

Commit

Permalink
Adv. option for custom styles; Refactoring; Better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
glutanimate committed Feb 27, 2018
1 parent 3e71fa8 commit 92a7db1
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 18 deletions.
2 changes: 2 additions & 0 deletions docs/description.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ An overview of the most important changes in this release follows below:
- **New**: Anki 2.1 compatibility
- **New**: Option to apply syntax highlighting via CSS (thanks to [Tim Rae](https://github.com/timrae/SyntaxHighlight)!)
- **New**: Ability to customize language selection and hotkey
- **New**: Ability to customize [syntax highlighting theme](https://help.farbox.com/pygments.html)
- **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
- **Fixed**: Position options dialog correctly
- **Fixed**: Various improvements and bug fixes (e.g. the ImportErrors and KeyErrors frequently reported in earlier reviews)
Expand Down Expand Up @@ -71,6 +72,7 @@ The following options may be customized:

- `hotkey` [string]: Add-on invocation hotkey. Default: `Alt+S`
- `limitToLags` [list]: List of programming languages to limit combobox menu to. Default: `[]` (i.e. no limit). Example: `["Python", "Java", "JavaScript"]`.
- `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`.

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

Expand Down
3 changes: 2 additions & 1 deletion src/syntax_highlighting/config.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"hotkey": "Alt+s",
"limitToLangs": []
"limitToLangs": [],
"style": "default"
}
3 changes: 2 additions & 1 deletion src/syntax_highlighting/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
These advanced settings do not sync and require a restart to apply.

- `hotkey` [string]: Add-on invocation hotkey. Default: `Alt+S`
- `limitToLags` [list]: List of programming languages to limit combobox menu to. Default: `[]` (i.e. no limit). Example: `["Python", "Java", "JavaScript"]`.
- `limitToLags` [list]: List of programming languages to limit combobox menu to. Default: `[]` (i.e. no limit). Example: `["Python", "Java", "JavaScript"]`.
- `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`.
51 changes: 35 additions & 16 deletions src/syntax_highlighting/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,15 @@
from aqt.qt import *
from aqt import mw
from aqt.editor import Editor
from aqt.utils import tooltip
from aqt.utils import showWarning
from anki.utils import json
from anki.hooks import addHook, wrap

from .config import local_conf


HOTKEY = local_conf["hotkey"]
STYLE = local_conf["style"]
LIMITED_LANGS = local_conf["limitToLangs"]

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

ERR_STYLE = ("<b>Error</b>: Selected style not found.<br>"
"If you set a custom style please make sure<br>"
"you typed it correctly.")


# Misc

def showError(msg, parent):
showWarning(msg, title="Syntax Highlighting Error", parent=parent)

# Synced options and corresponding dialogs

def get_deck_name(mw):
Expand Down Expand Up @@ -273,8 +284,9 @@ def addWidgets20(ed, previous_lang):
def onCodeHighlightLangSelect(ed, lang):
try:
alias = LANGUAGES_MAP[lang]
except KeyError:
tooltip(ERR_LEXER)
except KeyError as e:
print(e)
showError(ERR_LEXER, parent=ed.parentWindow)
ed.codeHighlightLangAlias = ""
return False
set_default_lang(mw, lang)
Expand All @@ -288,11 +300,11 @@ def onCodeHighlightLangSelect(ed, lang):
"""style='vertical-align: top;'>{}</select>""")


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


def onBridgeCmd(self, cmd, _old):
def onBridgeCmd(ed, cmd, _old):
if not cmd.startswith("shLang"):
return _old(self, cmd)
return _old(ed, cmd)
(type, lang) = cmd.split(":")
onCodeHighlightLangSelect(self, lang)
onCodeHighlightLangSelect(ed, lang)


# Actual code highlighting


def highlight_code(self):
def highlight_code(ed):
addon_conf = mw.col.conf['syntax_highlighting_conf']

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

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

langAlias = self.codeHighlightLangAlias
langAlias = ed.codeHighlightLangAlias

# Select the lexer for the correct language
try:
my_lexer = get_lexer_by_name(langAlias, stripall=True)
except ClassNotFound:
tooltip(ERR_LEXER)
except ClassNotFound as e:
print(e)
showError(ERR_LEXER, parent=ed.parentWindow)
return False

# Create html formatter object including flags for line nums and css classes
my_formatter = HtmlFormatter(
linenos=linenos, noclasses=noclasses, font_size=16)
try:
my_formatter = HtmlFormatter(
linenos=linenos, noclasses=noclasses,
font_size=16, style=STYLE)
except ClassNotFound as e:
print(e)
showError(ERR_STYLE, parent=ed.parentWindow)
return False

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

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


Expand Down

0 comments on commit 92a7db1

Please sign in to comment.