` tags work right when I do them, but MdPopups' work correctly?**
+
+ This is because the HTML engine in Sublime treats `#!html
` tags just as a normal block elements; it doesn't treat the content as preformatted. When MdPopups creates code blocks, it actually does a lot of special formatting to the blocks. It converts tabs to 4 spaces, and spaces are converted to `#!html ` to prevent wrapping. Lastly, new lines get converted to `#!html ` tags.
+ {: style="font-style: italic"}
+
+- **Why in code blocks do tabs get converted to 4 spaces?**
+
+ Because I like it that way. If you are planning on having a snippet of text sent through the syntax highlighter and do not want your tabs to be converted to 4 spaces, you should convert it to the number of spaces you like **before** sending it through the syntax highlighter.
+ {: style="font-style: italic"}
+
+- **Why does <insert element> not work, or cause the popup/phantom not to show?**
+
+ Because Sublime's HTML engine is extremely limited or the element you are trying to use hasn't been styled correctly yet. Though I do not have a complete list of all supported elements, you can check out the provided `default.css` on the repository to see what is supported. There are probably some elements you could style and then would work correctly, but there are others like `#!html
` will not *currently* work. In general, you should keep things basic, but feel free to experiment to get an understanding of Sublime's `minihtml` engine limitations.
+ {: style="font-style: italic"}
diff --git a/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/images/tooltips_test.png b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/images/tooltips_test.png
new file mode 100644
index 0000000..b4b9da2
Binary files /dev/null and b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/images/tooltips_test.png differ
diff --git a/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/index.md b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/index.md
new file mode 100644
index 0000000..6575ba9
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/index.md
@@ -0,0 +1,18 @@
+# About Markdown Popups
+
+## Overview
+
+Sublime Markdown Popups (MdPopups) is a library for Sublime Text plugins. It utilizes the new plugin API found in ST3 Beta to create popups and phantoms from Markdown or HTML. It requires at least ST3 3124+. MdPopups utilizes Python Markdown with a couple of special extensions to convert Markdown to HTML that can be used to create popups and/or phantoms. It also provides a number of other helpful API commands to aid in creating great popups and phantoms.
+
+MdPopups will use your color scheme to create popups/phantoms that fit your editors look.
+
+![Screenshot](images/tooltips_test.png)
+
+## Features
+
+- Can take Markdown or HTML and create nice looking popups and phantoms.
+- Dynamically creates popup and phantom themes from your current Sublime color scheme.
+- Can create syntax highlighted code blocks easily using your existing Sublime color scheme (can also use Pygments with some setup).
+- Can create color preview boxes via API calls.
+- A CSS template environment that allows users to override and tweak the overall look of the popups and phantoms to better fit their preferred look.
+- Plugins can extend the current CSS to inject plugin specific class styling.
diff --git a/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/installation.md b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/installation.md
new file mode 100644
index 0000000..b3d9f1a
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/installation.md
@@ -0,0 +1,11 @@
+# Installation
+
+## Package Control
+
+In order for your plugin to utilize Markdown Popups, you must be using [Package Control][package-control], and you must add `mdpopups` (and other related dependencies) as a dependency for your plugin. This can be done in one of two ways, both of which are [documented][pc-dependencies] by Package Control; see **Using Dependencies**. Package Control will install and update the dependency for you. Package Control will also ensure that `mdpopups` is loaded before your plugin loads.
+
+If ever you are on a older version than is currently released, and Package Control has not updated to the latest, you can force the update by running the `Package Control: Satisfy Dependencies` command from the command palette.
+
+Remember, MdPopups is for Sublime Text 3 builds 3124+.
+
+--8<-- "refs.md"
diff --git a/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/license.md b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/license.md
new file mode 100644
index 0000000..d224dc7
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/license.md
@@ -0,0 +1,11 @@
+# License
+
+Sublime Markdown Popups is released under the MIT license.
+
+Copyright (c) 2015 - 2018 Isaac Muse
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/settings.md b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/settings.md
new file mode 100644
index 0000000..7922e47
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/settings.md
@@ -0,0 +1,81 @@
+# User Settings
+
+## Configuring MdPopups
+
+All settings for MdPopups are placed in Sublime's `Preferences.sublime-settings`. They are applied globally and to all popups and phantoms.
+
+## `mdpopups.debug`
+
+Turns on debug mode. This will dump out all sorts of info to the console. Content before parsing to HTML, final HTML output, traceback from failures, etc.. This is more useful for plugin developers. It works by specifying an error level. `0` or `false` would disable it. 1 would trigger on errors. 2 would trigger on warnings and any level below. 3 would be general info (like HTML output) and any level below.
+
+```js
+ "mdpopups.debug": 1,
+```
+
+## `mdpopups.disable`
+
+Global kill switch to prevent popups (created by MdPopups) from appearing.
+
+```js
+ "mdpopups.disable": true,
+```
+
+## `mdpopups.cache_refresh_time`
+
+Control how long a CSS theme file will be in the cache before being refreshed. Value should be a positive integer greater than 0. Units are in minutes. Default is 30.
+
+```js
+ "mdpopups.cache_refresh_time": 30,
+```
+
+## `mdpopups.cache_limit`
+
+Control how many CSS theme files will be kept in cache at any given time. Value should be a positive integer greater than or equal to 0.
+
+```js
+ "mdpopups.cache_limit": 10
+```
+
+## `mdpopups.use_sublime_highlighter`
+
+Controls whether the Pygments or the native Sublime syntax highlighter is used for code highlighting. This affects code highlighting in Markdown conversion and when code is directly processed using [syntax_highlight](./api.md#syntax-highlight). To learn more about the syntax highlighter see [Syntax Highlighting](./styling.md#syntax-highlighting).
+
+```js
+ "mdpopups.use_sublime_highlighter": true
+```
+
+## `mdpopups.user_css`
+
+Overrides the default CSS and/or CSS of a plugin. Value should be a relative path pointing to the CSS file: `Packages/User/my_custom_theme.css`. Slashes should be forward slashes. By default, it will point to `Packages/User/mdpopups.css`. User CSS overrides **all** CSS as it is the last to be processed.
+
+```js
+ "mdpopups.user_css": "Packages/User/mdpopups.css"
+```
+
+## `mdpopups.default_style`
+
+Controls whether MdPopups' default styling (contained in [`default.css`][default-css]) will be applied or not.
+
+## `mdpopups.sublime_user_lang_map`
+
+This setting is for the Sublime Syntax Highlighter and allows the mapping of personal Sublime syntax languages which are not yet included, or will not be included, in the official mapping table. You can either define your own new entry, or use the same language name of an existing entry to extend the language `mapping_alias` or syntax languages. When extending, the user mappings will be cycled through first.
+
+```js
+ 'mdpopups.sublime_user_lang_map': {
+ "language": (('mapping_alias',), ('MyPackage/MySyntaxLanguage'))
+ }
+```
+
+**Example**:
+```js
+'mdpopups.sublime_user_lang_map': {
+ 'javascript': (('javascript', 'js'), ('JavaScript/JavaScript', 'JavaScriptNext - ES6 Syntax/JavaScriptNext'))
+}
+```
+
+For a list of all currently supported syntax mappings, see the official [mapping file][language-map].
+
+!!! tip "Tip"
+ When submitting new languages to the mapping table, it is encouraged to pick key names that correspond to what is used in Pygments so a User can switch between Pygments' and Sublime's syntax highlighter and still get highlighting.
+
+--8<-- "refs.md"
diff --git a/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/styling.md b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/styling.md
new file mode 100644
index 0000000..83990e1
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/docs/src/markdown/styling.md
@@ -0,0 +1,472 @@
+# CSS Styling
+
+## Syntax Highlighting
+
+MdPopups has two syntax highlighting methods: the native Sublime syntax highlighter (default) and Pygments. When developing a plugin, it is wise to test out both. The native Sublime Syntax Highlighter has most default languages mapped along with a few others.
+
+### Sublime Syntax Highlighter
+
+As previously mentioned, MdPopups uses the internal syntax highlighter to highlight your code. The benefit here is that you get code highlighting in your popup that matches your current theme. The highlighting ability is dependent upon what syntax packages you have installed in Sublime. It also depends on whether that syntax is enabled and mapped to a language keyword. Pull requests are welcome to expand and keep the [language mapping][language-map] updated. You can also define in your `Preferences.sublime-settings` file additional mappings. See [`mdpopups.sublime_user_lang_map`](./settings.md#mdpopupssublime_user_lang_map) for more info.
+
+Most users prefer using syntax highlighting that matches their current color scheme. If you are a developer, it is recommended to issue a pull request to add missing languages you need to the mapping. Optionally you can also describe how users can map what they need locally.
+
+### Pygments
+
+In order to use Pygments, you have to disable `mdpopups.use_sublime_highlighter`. Pygments has a great variety of highlighters out of the box. It also comes with a number of built-in color schemes that can be used. When enabling Pygments, you must specify the color scheme to use in your user CSS using the [CSS template filter](#css-templates).
+
+```css+jinja
+/* Syntax Highlighting */
+{%- if var.use_pygments %}
+ {%- if var.is_light %}
+{{'default'|pygments}}
+ {%- else %}
+{{'native'|pygments}}
+ {%- endif %}
+{%- endif %}
+```
+
+You can also paste your own custom Pygments CSS directly into your User CSS, but you will have to format it to work properly.
+
+Pygments defines special classes for each span that needs to be highlighted in a coding block. Pygments CSS classes are not only given syntax classes that are applied to each span, but usually an overall class is assigned to a `#!html
` wrapper as well. For instance, a class for whitespace may look like this (where `#!css .highlight` is the div wrapper's class and `#!css .w` i the span's class):
+
+```css
+.highlight .w { color: #cccccc } /* Text.Whitespace */
+```
+
+If doing your own, the Pygments CSS should define a rule to highlight general background and foregrounds.
+
+```css
+.mdpopups .highlight { background-color: #f8f8f8; color: #4d4d4c }
+```
+
+??? settings "Full Pygments CSS Example"
+
+ ```css
+ .mdpopups .highlight { background-color: #f8f8f8; color: #4d4d4c }
+ .mdpopups .highlight .c { color: #8e908c; font-style: italic } /* Comment */
+ .mdpopups .highlight .err { color: #c82829 } /* Error */
+ .mdpopups .highlight .k { color: #8959a8; font-weight: bold } /* Keyword */
+ .mdpopups .highlight .l { color: #f5871f } /* Literal */
+ .mdpopups .highlight .n { color: #4d4d4c } /* Name */
+ .mdpopups .highlight .o { color: #3e999f } /* Operator */
+ .mdpopups .highlight .p { color: #4d4d4c } /* Punctuation */
+ .mdpopups .highlight .cm { color: #8e908c; font-style: italic } /* Comment.Multiline */
+ .mdpopups .highlight .cp { color: #8e908c; font-weight: bold } /* Comment.Preproc */
+ .mdpopups .highlight .c1 { color: #8e908c; font-style: italic } /* Comment.Single */
+ .mdpopups .highlight .cs { color: #8e908c; font-style: italic } /* Comment.Special */
+ .mdpopups .highlight .gd { color: #c82829 } /* Generic.Deleted */
+ .mdpopups .highlight .ge { font-style: italic } /* Generic.Emph */
+ .mdpopups .highlight .gh { color: #4d4d4c; font-weight: bold } /* Generic.Heading */
+ .mdpopups .highlight .gi { color: #718c00 } /* Generic.Inserted */
+ .mdpopups .highlight .gp { color: #8e908c; font-weight: bold } /* Generic.Prompt */
+ .mdpopups .highlight .gs { font-weight: bold } /* Generic.Strong */
+ .mdpopups .highlight .gu { color: #3e999f; font-weight: bold } /* Generic.Subheading */
+ .mdpopups .highlight .kc { color: #8959a8; font-weight: bold } /* Keyword.Constant */
+ .mdpopups .highlight .kd { color: #8959a8; font-weight: bold } /* Keyword.Declaration */
+ .mdpopups .highlight .kn { color: #8959a8; font-weight: bold } /* Keyword.Namespace */
+ .mdpopups .highlight .kp { color: #8959a8; font-weight: bold } /* Keyword.Pseudo */
+ .mdpopups .highlight .kr { color: #8959a8; font-weight: bold } /* Keyword.Reserved */
+ .mdpopups .highlight .kt { color: #eab700; font-weight: bold } /* Keyword.Type */
+ .mdpopups .highlight .ld { color: #718c00 } /* Literal.Date */
+ .mdpopups .highlight .m { color: #f5871f } /* Literal.Number */
+ .mdpopups .highlight .s { color: #718c00 } /* Literal.String */
+ .mdpopups .highlight .na { color: #4271ae } /* Name.Attribute */
+ .mdpopups .highlight .nb { color: #4271ae } /* Name.Builtin */
+ .mdpopups .highlight .nc { color: #c82829; font-weight: bold } /* Name.Class */
+ .mdpopups .highlight .no { color: #c82829 } /* Name.Constant */
+ .mdpopups .highlight .nd { color: #3e999f } /* Name.Decorator */
+ .mdpopups .highlight .ni { color: #4d4d4c } /* Name.Entity */
+ .mdpopups .highlight .ne { color: #c82829; font-weight: bold } /* Name.Exception */
+ .mdpopups .highlight .nf { color: #4271ae; font-weight: bold } /* Name.Function */
+ .mdpopups .highlight .nl { color: #4d4d4c } /* Name.Label */
+ .mdpopups .highlight .nn { color: #4d4d4c } /* Name.Namespace */
+ .mdpopups .highlight .nx { color: #4271ae } /* Name.Other */
+ .mdpopups .highlight .py { color: #4d4d4c } /* Name.Property */
+ .mdpopups .highlight .nt { color: #c82829 } /* Name.Tag */
+ .mdpopups .highlight .nv { color: #c82829 } /* Name.Variable */
+ .mdpopups .highlight .ow { color: #3e999f } /* Operator.Word */
+ .mdpopups .highlight .w { color: #4d4d4c } /* Text.Whitespace */
+ .mdpopups .highlight .mb { color: #f5871f } /* Literal.Number.Bin */
+ .mdpopups .highlight .mf { color: #f5871f } /* Literal.Number.Float */
+ .mdpopups .highlight .mh { color: #f5871f } /* Literal.Number.Hex */
+ .mdpopups .highlight .mi { color: #f5871f } /* Literal.Number.Integer */
+ .mdpopups .highlight .mo { color: #f5871f } /* Literal.Number.Oct */
+ .mdpopups .highlight .sb { color: #718c00 } /* Literal.String.Backtick */
+ .mdpopups .highlight .sc { color: #4d4d4c } /* Literal.String.Char */
+ .mdpopups .highlight .sd { color: #8e908c } /* Literal.String.Doc */
+ .mdpopups .highlight .s2 { color: #718c00 } /* Literal.String.Double */
+ .mdpopups .highlight .se { color: #f5871f } /* Literal.String.Escape */
+ .mdpopups .highlight .sh { color: #718c00 } /* Literal.String.Heredoc */
+ .mdpopups .highlight .si { color: #f5871f } /* Literal.String.Interpol */
+ .mdpopups .highlight .sx { color: #718c00 } /* Literal.String.Other */
+ .mdpopups .highlight .sr { color: #718c00 } /* Literal.String.Regex */
+ .mdpopups .highlight .s1 { color: #718c00 } /* Literal.String.Single */
+ .mdpopups .highlight .ss { color: #718c00 } /* Literal.String.Symbol */
+ .mdpopups .highlight .bp { color: #f5871f } /* Name.Builtin.Pseudo */
+ .mdpopups .highlight .vc { color: #c82829 } /* Name.Variable.Class */
+ .mdpopups .highlight .vg { color: #c82829 } /* Name.Variable.Global */
+ .mdpopups .highlight .vi { color: #c82829 } /* Name.Variable.Instance */
+ .mdpopups .highlight .il { color: #f5871f } /* Literal.Number.Integer.Long */
+ ```
+
+## CSS Styling
+
+One reason MdPopups was created was to give consistent popups across plugins. Originally MdPopups forced its style so that plugins couldn't override the it. Later it was realized that plugins may have reasons to override certain things, and in recent versions, this constraint was relaxed. Despite changes since its inception, one thing has stayed the same: the user has the last say in how popups work. This is achieved by controlling which CSS gets loaded when.
+
+```flow
+st=>operation: Sublime CSS/Color Scheme CSS
+md=>operation: MdPopups Default CSS
+pg=>operation: Plugin CSS
+us=>operation: User CSS
+
+st->md->pg->us
+```
+
+Sublime first provides its CSS which includes some basic styling and CSS from color schemes. MdPopups provides its own default CSS that styles the common HTML tags and provides minimal colors. Plugins come next and extend the CSS with plugin specific CSS. The user's CSS is loaded last and can override anything.
+
+All CSS is passed through the Jinja2 template engine where special filters can provide things like appropriate CSS that matches your color scheme for a specific scope, load additional CSS from another source, have condition logic for specific Sublime and/or MdPopups versions, or even provide CSS for specific color schemes.
+
+Templates are used so that a user can easily tap into all the colors, color filters, and other useful logic to control their popups and phantoms in one place without having to hard code a specific CSS for a specific color scheme.
+
+In general, it is encouraged to use Sublime CSS variables such as `--redish`, `--bluish`, etc. to get appropriate colors for a given theme. Sublime calculates these colors from the color scheme directly. If it calculates a color that is not quite right, you can always request that the color scheme in question redefines that variable with an appropriate color. Or you, as the user, can define one in your user CSS. You can read more about `minihtml` and it's features in the [`minihtml` documentation][minihtml].
+
+MdPopups also provides its own CSS variables that can be overridden by a user:
+
+Variable | Description
+----------------------------------- | -----------
+`--mdpopups-font-mono` | Monospace font stack for elements that require monospace (like code blocks).
+`--mdpopups-hr` | `#!html ` tag color.
+`--mdpopups-admon-fg` | General admonition foreground/text color.
+`--mdpopups-admon-info-fg` | Info admonition foreground/text color.
+`--mdpopups-admon-error-fg` | Error admonition foreground/text color.
+`--mdpopups-admon-success-fg` | Success admonition foreground/text color.
+`--mdpopups-admon-warning-fg` | Warning admonition foreground/text color.
+`--mdpopups-admon-title-fg` | General admonition title foreground/text color.
+`--mdpopups-admon-info-title-fg` | Info admonition title foreground/text color.
+`--mdpopups-admon-error-title-fg` | Error admonition title foreground/text color.
+`--mdpopups-admon-success-title-fg` | Success admonition title foreground/text color.
+`--mdpopups-admon-warning-title-fg` | Warning admonition title foreground/text color.
+`--mdpopups-admon-bg` | General admonition background color.
+`--mdpopups-admon-info-bg` | Info admonition background color.
+`--mdpopups-admon-error-bg` | Error admonition background color.
+`--mdpopups-admon-warning-bg` | Warning admonition background color.
+`--mdpopups-admon-success-bg` | Success admonition background color.
+`--mdpopups-admon-accent` | General admonition accent color (border/title bar background).
+`--mdpopups-admon-info-accent` | Info admonition accent color (border/title bar background).
+`--mdpopups-admon-error-accent` | Error admonition accent color (border/title bar background).
+`--mdpopups-admon-success-accent` | Success admonition accent color (border/title bar background).
+`--mdpopups-admon-warning-accent` | Warning admonition accent color (border/title bar background).
+`--mdpopups-kbd-fg` | `#!html ` foreground/text color.
+`--mdpopups-kbd-bg` | `#!html ` background color.
+`--mdpopups-kbd-border` | `#!html ` border color.
+`--mdpopups-hl-border` | Inline and block code border color.
+`--mdpopups-hl-bg` | Inline and block code background color.
+
+## CSS Templates
+
+All variables and filters provided by default *only* apply to the CSS, not the markdown or HTML content. The default provided variables are namespaced under `var`.
+
+The Markdown and HTML content only receives the variables that are given via `template_vars` parameters and any options via the `template_env_options`; user defined variables will get passed to the CSS, but not the options. User defined variables will be namespaced under `plugin`.
+
+### CSS Filter
+
+With the template environment, colors and style from the current Sublime color scheme can be accessed and manipulated. Access to the Sublime color scheme styles CSS is done via the `css` filter.
+
+`css`
+:
+ Retrieves the style for a specific Sublime scope from a Sublime color scheme. By specifying either `foreground`, `background`, or any scope (complexity doesn't really matter) and feeding it into the `css` filter, all the related styling of the specified scope will be inserted as CSS into the CSS document.
+
+ **Example**:
+
+ This:
+
+ ```css+jinja
+ h1, h2, h3, h4, h5, h6 { {{'comment'|css}} }
+ ```
+
+ Might become this:
+
+ ```css+jinja
+ h1, h2, h3, h4, h5, h6 { color: #888888; font-style: italic; }
+ ```
+
+ Notice that the format of insertion is `key: value; `. You do not need a semicolon after as the CSS lines are all formatted properly with semicolons. If you add one, you may get multiple semicolons which *may* break the CSS.
+
+ If you need to get at a specific CSS attribute, you can specify its name in the `css` filter (available attributes are `color`, `background-color`, `font-style`, and `font-weight`).
+
+ This:
+
+ ```css+jinja
+ h1, h2, h3, h4, h5, h6 { {{'.comment'|css('color')}} }
+ ```
+
+ Would then only include the color:
+
+ ```css+jinja
+ h1, h2, h3, h4, h5, h6 { color: #888888; }
+ ```
+
+ In general, a foreground color is always returned, but by default, a background color is only returned if one is explicitly defined. To always get a background (which most likely will default to the overall scheme background), you can set the additional `explicit_background` parameter to `#!py False`.
+
+ ```css+jinja
+ /* If `keyword.operator` is not explicitly used, fallback to `.keyword` */
+ h1, h2, h3, h4, h5, h6 { {{'keyword.operator'|css('color', False)}} }
+ ```
+
+### Color Filters
+
+MdPopups also provides a number of color filters within the template environment that can manipulate the CSS colors returned from the `css` filter (or equivalent formatted CSS). These filters will strip out the color and modify it, and return the appropriate CSS. To manipulate a color value directly, you can use Sublime's built in color blending. In most cases, it is advised to use Sublime's color blending functionality, but these are available to aid those who wish to access and manipulate CSS of scopes directly. See Sublime's [`minihtml` documentation][minihtml] for more info.
+
+Even though Sublime generally provides contrast to popups, lets pretend you had a popup that was the same color as the view window and it was difficult to see where the popup starts and ends. You can take the color schemes background and apply a brightness filter to it allowing you now see the popup clearly.
+
+Here we can make the background of the popup darker:
+
+```css+jinja
+.mdpopups div.myplugin { {{'.background'|css('background-color')|brightness(0.9)}} }
+```
+
+Color filters take a single color attribute of the form `key: value;`. So when feeding the color template filters your CSS via the `css` filter, you should specify the color attribute (`background-color` or `color`) that you wish to apply the filter to; it may be difficult to tell how many attributes `css` could return without explicitly specifying attribute. Color filters only take either `color` or `background-color` attributes.
+
+Filters can be chained if more intensity is needed (as some filters may clamp the value in one call), or if you want to apply multiple filters. These are all the available filters:
+
+`foreground` and `background`
+:
+
+ If desired, you can convert a foreground color to a background color or vice versa. To convert to a foreground color, you can use the `foreground` filter. To convert to a background color, you can use the `background` filter. Remember, this is augmenting the CSS returned by the `css` filter, you can't just give it a color.
+
+
+ To convert a background to a foreground.
+
+ **Example**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|foreground}} }
+ ```
+
+ To convert a foreground to a background.
+
+ **Example**:
+ ```css+jinja
+ body { {{'.foreground'|css('color')|background}} }
+ ```
+
+`brightness`
+:
+ Shifts brightness either dark or lighter. Brightness is relative to 1 where 1 means no change. Accepted values are floats that are greater than 0. Ranges are clamped between 0 and 2.
+
+ **Example - Darken**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|brightness(0.9)}} }
+ ```
+
+ **Example - Lighten**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|brightness(1.1)}} }
+ ```
+
+`contrast`
+:
+ Increases/decreases the contrast. Contrast is relative to 1 where 1 means no change. Accepted values are floats that are greater than 0. Ranges are clamped between 0 and 2.
+
+ **Example - Decrease contrast**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|contrast(0.9)}} }
+ ```
+
+ **Example - Increase contrast**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|contrast(1.1)}} }
+ ```
+
+`saturation`
+:
+ Shifts the saturation either to right (saturate) or the left (desaturate). Saturation is relative to 1 where 1 means no change. Accepted values are floats that are greater than 0. Ranges are clamped between 0 and 2.
+
+ **Example - Desaturate**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|saturation(0.9)}} }
+ ```
+
+ **Example - Saturate**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|saturation(1.1)}} }
+ ```
+
+`grayscale`
+:
+ Filters all colors to a grayish tone.
+
+ **Example**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|grayscale}} }
+ ```
+
+`sepia`
+:
+ Filters all colors to a sepia tone.
+
+ **Example**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|sepia}} }
+ ```
+
+`invert`
+:
+ Inverts a color.
+
+ **Example**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|invert}} }
+ ```
+
+`colorize`
+:
+ Filters all colors to a shade of the specified hue. Think grayscale, but instead of gray, you define a non-gray hue. The values are angular dimensions starting at the red primary at 0°, passing through the green primary at 120° and the blue primary at 240°, and then wrapping back to red at 360°.
+
+ **Example**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|colorize(30)}} }
+ ```
+
+`hue`
+:
+ Shifts the current hue either to the left or right. The values are angular dimensions starting at the red primary at 0°, passing through the green primary at 120° and the blue primary at 240°, and then wrapping back to red at 360°. Values can either be negative to shift left or positive to shift the hue to the right.
+
+ **Example - Left Shift**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|hue(-30)}} }
+ ```
+
+ **Example - Left Right**:
+ ```css+jinja
+ body { {{'.background'|css('background-color')|hue(30)}} }
+ ```
+
+`fade`
+:
+ Fades a color. Essentially it is like apply transparency to the color allowing the color schemes base background color to show through.
+
+ **Example - Fade 50%**:
+ ```css+jinja
+ body { {{'.foreground'|css('color')|fade(0.5)}} }
+ ```
+
+### Include CSS Filter
+
+The template environment allows for retrieving CSS resources from Sublime Packages or built-in Pygments CSS from the Pygments library.
+
+`getcss`
+:
+ Retrieve a CSS file from Sublime's `Packages` folder. CSS retrieved in this manner can include template variables and filters.
+
+ **Example**:
+ ```css+jinja
+ {{'Packages/User/aprosopo-dark.css'|getcss}}
+ ```
+
+`pygments`
+:
+ Retrieve a built-in Pygments color scheme.
+
+ **Example**:
+ ```css+jinja
+ {{'native'|pygments}}
+ ```
+
+## Template Variables
+
+The template environment provides a couple of variables that can be used to conditionally alter the CSS output. Variables are found under `var`.
+
+`var.sublime_version`
+:
+ `sublime_version` contains the current Sublime Text version. This allows you conditionally handle CSS features that are specific to a Sublime Text version.
+
+ **Example**
+ ```css+jinja
+ {% if var.sublime_version >= 3119 %}
+ padding: 0.2rem;
+ {% else %}
+ padding: 0.2em;
+ {% endif %}
+ ```
+
+`var.mdpopups_version`
+:
+ `mdpopups_version` contains the current MdPopups version which you can use in your CSS templates if needed.
+
+ **Example**
+ ```css+jinja
+ {% if var.mdpopups_version >= (1, 9, 0) %}
+ /* do something */
+ {% else %}
+ /* do something else */
+ {% endif %}
+ ```
+
+`var.default_style`
+:
+ Flag specifying whether default styling is being used. See [`mdpopups.default_style`](./settings.md#mdpopupsdefault_style) for how to control this flag. And see [`default.css`][default-css] for an example of how it is used.
+
+`var.is_dark` and `var.is_light`
+:
+ `is_dark` checks if the color scheme is a dark color scheme. Alternatively, `is_light` checks if the color scheme is a light color scheme.
+
+ **Example**:
+ ```css+jinja
+ {% if var.is_light %}
+ html{ {{'.background'|css('background-color')|brightness(0.9)}} }
+ {% else %}
+ html{ {{'.background'|css('background-color')|brightness(1.1)}} }
+ {% endif %}
+ ```
+
+`var.is_popup` and `var.is_phantom`
+:
+ `is_phantom` checks if the current CSS is for a phantom instead of a popup. Alternatively, `is_popup` checks if the current use of the CSS is for a popup.
+
+ **Example**:
+ ```css+jinja
+ {% if var.is_phantom %}
+ html{ {{'.background'|css('background-color')|brightness(0.9)}} }
+ {% else %}
+ html{ {{'.background'|css('background-color')|brightness(1.1)}} }
+ {% endif %}
+ ```
+
+`var.use_pygments`
+:
+ Checks if the Pygments syntax highlighter is being used.
+
+ **Example**:
+ ```css+jinja
+ {% if var.use_pygments %}
+ {% if var.is_light %}
+ {{'default'|pygments}}
+ {% else %}
+ {{'native'|pygments}}
+ {% endif %}
+ {% endif %}
+ ```
+
+`var.color_scheme`
+:
+ Retrieves the current color schemes name.
+
+ **Example**:
+ ```css+jinja
+ {% if (
+ var.color_scheme in (
+ 'Packages/Theme - Aprosopo/Tomorrow-Night-Eighties-Stormy.tmTheme',
+ 'Packages/Theme - Aprosopo/Tomorrow-Morning.tmTheme',
+ )
+ ) %}
+ a { {{'.keyword.operator'|css('color')}} }
+ {% else %}
+ a { {{'.support.function'|css('color')}} }
+ {% endif %}
+ ```
+
+--8<--
+refs.md
+
+uml.md
+--8<--
diff --git a/.config/sublime-text-3/Packages/mdpopups/docs/theme/extra-d04c85ed4a.css b/.config/sublime-text-3/Packages/mdpopups/docs/theme/extra-d04c85ed4a.css
new file mode 100644
index 0000000..e85113b
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/docs/theme/extra-d04c85ed4a.css
@@ -0,0 +1 @@
+@charset "UTF-8";.md-typeset .magiclink:before{position:relative;padding-right:.25rem;font-family:FontAwesome;-moz-osx-font-smoothing:initial;-webkit-font-smoothing:initial;font-weight:400}.md-typeset .magiclink-repository.magiclink-github:before{content:""}.md-typeset .magiclink-repository.magiclink-gitlab:before{content:""}.md-typeset .magiclink-repository.magiclink-bitbucket:before{content:""}.md-typeset .keys kbd:after,.md-typeset .keys kbd:before{position:relative;margin:0;color:#bdbdbd;font-family:sans-serif;-moz-osx-font-smoothing:initial;-webkit-font-smoothing:initial;font-weight:400}.md-typeset .keys span{padding:0 .2rem;color:#bdbdbd}.md-typeset .keys .key-backspace:before{padding-left:.2rem;content:"←"}.md-typeset .keys .key-command:before{padding-left:.2rem;content:"⌘"}.md-typeset .keys .key-windows:before{padding-left:.2rem;content:"⊞"}.md-typeset .keys .key-caps-lock:before{padding-left:.2rem;content:"⇪"}.md-typeset .keys .key-control:before{padding-left:.2rem;content:"⌃"}.md-typeset .keys .key-meta:before{padding-left:.2rem;content:"◆"}.md-typeset .keys .key-shift:before{padding-left:.2rem;content:"⇧"}.md-typeset .keys .key-option:before{padding-left:.2rem;content:"⌥"}.md-typeset .keys .key-tab:after{padding-left:.2rem;content:"↹"}.md-typeset .keys .key-num-enter:after{padding-left:.2rem;content:"↵"}.md-typeset .keys .key-enter:after{padding-left:.2rem;content:"↩"}.md-typeset .admonition.settings,.md-typeset details.settings{border-left:.4rem solid #a0f}.md-typeset .admonition.settings>.admonition-title,.md-typeset details.settings>.admonition-title,.md-typeset details.settings>summary{border-bottom:.1rem solid rgba(170,0,255,.1);background-color:rgba(170,0,255,.1)}.md-typeset .admonition.settings>.admonition-title:before,.md-typeset details.settings>.admonition-title:before,.md-typeset details.settings>summary:before{color:#a0f;content:"settings"}.md-typeset .uml-flowchart,.md-typeset .uml-sequence-diagram{width:100%;padding:1rem 0;overflow:auto}.md-typeset .uml-flowchart svg,.md-typeset .uml-sequence-diagram svg{max-width:none}.md-typeset a>code{margin:0 .29412em;padding:.07353em 0;border-radius:.2rem;background-color:hsla(0,0%,93%,.5);box-shadow:.29412em 0 0 hsla(0,0%,93%,.5),-.29412em 0 0 hsla(0,0%,93%,.5);-webkit-box-decoration-break:clone;box-decoration-break:clone}.md-typeset .linenodiv .special{color:#fff;font-weight:800}.md-typeset td code{word-break:normal}.md-typeset .codehilite .hll,.md-typeset .highlight .hll{display:inline}.md-typeset .headerlink{font:normal 400 2rem Material Icons;vertical-align:middle}.md-typeset h2 .headerlink{margin-top:-.4rem}.md-typeset h3 .headerlink{margin-top:-.3rem}.md-typeset h4 .headerlink,.md-typeset h5 .headerlink,.md-typeset h6 .headerlink{margin-top:-.2rem}.md-typeset .progress-label{position:absolute;width:100%;margin:0;color:rgba(0,0,0,.5);font-weight:700;line-height:1.4rem;text-align:center;white-space:nowrap}.md-typeset .progress-bar{height:1.2rem;float:left;background-color:#2979ff}.md-typeset .candystripe-animate .progress-bar{-webkit-animation:a 3s linear infinite;animation:a 3s linear infinite}.md-typeset .progress{display:block;position:relative;width:100%;height:1.2rem;margin:.5rem 0;background-color:#eee}.md-typeset .progress.thin{height:.4rem;margin-top:.9rem}.md-typeset .progress.thin .progress-label{margin-top:-.4rem}.md-typeset .progress.thin .progress-bar{height:.4rem}.md-typeset .progress.candystripe .progress-bar{background-image:linear-gradient(135deg,hsla(0,0%,100%,.8) 27%,transparent 0,transparent 52%,hsla(0,0%,100%,.8) 0,hsla(0,0%,100%,.8) 77%,transparent 0,transparent);background-size:2rem 2rem}.md-typeset .progress-80plus .progress-bar,.md-typeset .progress-100plus .progress-bar{background-color:#00e676}.md-typeset .progress-60plus .progress-bar{background-color:#fbc02d}.md-typeset .progress-40plus .progress-bar{background-color:#ff9100}.md-typeset .progress-20plus .progress-bar{background-color:#ff5252}.md-typeset .progress-0plus .progress-bar{background-color:#ff1744}.md-typeset .progress.note .progress-bar{background-color:#2979ff}.md-typeset .progress.summary .progress-bar{background-color:#00b0ff}.md-typeset .progress.tip .progress-bar{background-color:#00bfa5}.md-typeset .progress.success .progress-bar{background-color:#00e676}.md-typeset .progress.warning .progress-bar{background-color:#ff9100}.md-typeset .progress.failure .progress-bar{background-color:#ff5252}.md-typeset .progress.danger .progress-bar{background-color:#ff1744}.md-typeset .progress.bug .progress-bar{background-color:#f50057}.md-typeset .progress.quote .progress-bar{background-color:#9e9e9e}@-webkit-keyframes a{0%{background-position:0 0}to{background-position:6rem 0}}@keyframes a{0%{background-position:0 0}to{background-position:6rem 0}}.md-footer .md-footer-custom-text{color:hsla(0,0%,100%,.3)}@media only screen and (min-width:76.1876em){.md-typeset .headerlink{margin-left:-2.4rem;float:left}.md-typeset h2 .headerlink{margin-top:.6rem}.md-typeset h3 .headerlink{margin-top:.4rem}.md-typeset h4 .headerlink{margin-top:.2rem}.md-typeset h5 .headerlink,.md-typeset h6 .headerlink{margin-top:0}}
\ No newline at end of file
diff --git a/.config/sublime-text-3/Packages/mdpopups/docs/theme/extra-d8800ea088.js b/.config/sublime-text-3/Packages/mdpopups/docs/theme/extra-d8800ea088.js
new file mode 100644
index 0000000..020e42f
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/docs/theme/extra-d8800ea088.js
@@ -0,0 +1 @@
+!function(){"use strict";var e=function(e,t,n){for(var o=function(e){for(var t="",n=0;nIsaac Muse
+ emoji provided free by EmojiOne
+
+docs_dir: docs/src/markdown
+theme:
+ name: material
+ custom_dir: docs/theme
+ palette:
+ primary: blue
+ accent: blue
+ logo:
+ icon: description
+ font:
+ text: Roboto
+ code: Roboto Mono
+
+pages:
+ - About Markdown Popups: index.md
+ - Installation: installation.md
+ - User Settings: settings.md
+ - API: api.md
+ - CSS Styling: styling.md
+ - F.A.Q: faq.md
+ - Contributing & Support: contributing.md
+ - Changelog: changelog.md
+ - License: license.md
+
+markdown_extensions:
+ - markdown.extensions.toc:
+ slugify: !!python/name:pymdownx.slugs.uslugify
+ permalink: "\ue157"
+ - markdown.extensions.admonition:
+ - markdown.extensions.smarty:
+ smart_quotes: false
+ - pymdownx.betterem:
+ - markdown.extensions.attr_list:
+ - markdown.extensions.def_list:
+ - markdown.extensions.tables:
+ - markdown.extensions.abbr:
+ - markdown.extensions.footnotes:
+ - pymdownx.extrarawhtml:
+ - pymdownx.superfences:
+ - pymdownx.highlight:
+ css_class: codehilite
+ extend_pygments_lang:
+ - name: php-inline
+ lang: php
+ options:
+ startinline: true
+ - name: pycon3
+ lang: pycon
+ options:
+ python3: true
+ - pymdownx.inlinehilite:
+ - pymdownx.magiclink:
+ repo_url_shortener: true
+ repo_url_shorthand: true
+ social_url_shorthand: true
+ user: facelessuser
+ repo: sublime-markdown-popups
+ - pymdownx.tilde:
+ - pymdownx.caret:
+ - pymdownx.smartsymbols:
+ - pymdownx.emoji:
+ emoji_generator: !!python/name:pymdownx.emoji.to_png
+ - pymdownx.escapeall:
+ hardbreak: true
+ nbsp: true
+ - pymdownx.tasklist:
+ custom_checkbox: true
+ - pymdownx.progressbar:
+ - pymdownx.striphtml:
+ - pymdownx.snippets:
+ base_path: docs/src/markdown/_snippets
+ - pymdownx.keys:
+ separator: "\uff0b"
+ - pymdownx.details:
+
+extra:
+ social:
+ - type: github
+ link: https://github.com/facelessuser
+extra_css:
+ - extra-4e53a56959.css
+extra_javascript:
+ - extra-d8800ea088.js
diff --git a/.config/sublime-text-3/Packages/mdpopups/setup.cfg b/.config/sublime-text-3/Packages/mdpopups/setup.cfg
new file mode 100644
index 0000000..de0954f
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/setup.cfg
@@ -0,0 +1,4 @@
+[flake8]
+ignore=D202,D203,D401,N802,E741
+max-line-length=120
+exclude=st3/mdpopups/png.py,site/*.py
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/__init__.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/__init__.py
new file mode 100644
index 0000000..fa6e00b
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/__init__.py
@@ -0,0 +1,786 @@
+# -*- coding: utf-8 -*-
+"""
+Markdown popup.
+
+Markdown tooltips and phantoms for SublimeText.
+
+TextMate theme to CSS.
+
+https://manual.macromates.com/en/language_grammars#naming_conventions
+"""
+import sublime
+import markdown
+import jinja2
+import traceback
+import time
+from . import version as ver
+from . import colorbox
+from collections import OrderedDict
+from .st_scheme_template import SchemeTemplate, POPUP, PHANTOM, NEW_SCHEMES
+from .st_clean_css import clean_css
+from .st_pygments_highlight import syntax_hl as pyg_syntax_hl
+from .st_code_highlight import SublimeHighlight
+from .st_mapping import lang_map
+from . import imagetint
+import re
+import os
+from . import frontmatter
+try:
+ import bs4
+except Exception:
+ bs4 = None
+
+DEFAULT_CSS = 'Packages/mdpopups/css/default.css'
+DEFAULT_USER_CSS = 'Packages/User/mdpopups.css'
+IDK = '''
+
+
¯\_(ツ)_/¯
+
+MdPopups failed to create
+the popup/phantom!
+Check the console to see if
+there are helpful errors.
+'''
+HL_SETTING = 'mdpopups.use_sublime_highlighter'
+STYLE_SETTING = 'mdpopups.default_style'
+RE_BAD_ENTITIES = re.compile(r'(&(?!amp;|lt;|gt;|nbsp;)(?:\w+;|#\d+;))')
+
+NODEBUG = 0
+ERROR = 1
+WARNING = 2
+INFO = 3
+
+
+def _log(msg):
+ """Log."""
+
+ print('mdpopups: %s' % str(msg))
+
+
+def _debug(msg, level):
+ """Debug log."""
+
+ if int(_get_setting('mdpopups.debug', NODEBUG)) >= level:
+ _log(msg)
+
+
+def _get_setting(name, default=None):
+ """Get the Sublime setting."""
+
+ return sublime.load_settings('Preferences.sublime-settings').get(name, default)
+
+
+def _can_show(view, location=-1):
+ """
+ Check if popup can be shown.
+
+ I have seen Sublime can sometimes crash if trying
+ to do a popup off screen. Normally it should just not show,
+ but sometimes it can crash. We will check if popup
+ can/should be attempted.
+ """
+
+ can_show = True
+ sel = view.sel()
+ if location >= 0:
+ region = view.visible_region()
+ if region.begin() > location or region.end() < location:
+ can_show = False
+ elif len(sel) >= 1:
+ region = view.visible_region()
+ if region.begin() > sel[0].b or region.end() < sel[0].b:
+ can_show = False
+ else:
+ can_show = False
+
+ return can_show
+
+
+##############################
+# Theme/Scheme cache management
+##############################
+_scheme_cache = OrderedDict()
+_highlighter_cache = OrderedDict()
+
+
+def _clear_cache():
+ """Clear the css cache."""
+
+ global _scheme_cache
+ global _highlighter_cache
+ _scheme_cache = OrderedDict()
+ _highlighter_cache = OrderedDict()
+
+
+def _is_cache_expired(cache_time):
+ """Check if the cache entry is expired."""
+
+ delta_time = _get_setting('mdpopups.cache_refresh_time', 30)
+ if not isinstance(delta_time, int) or delta_time < 0:
+ delta_time = 30
+ return delta_time == 0 or (time.time() - cache_time) >= (delta_time * 60)
+
+
+def _prune_cache():
+ """Prune older items in cache (related to when they were inserted)."""
+
+ limit = _get_setting('mdpopups.cache_limit', 10)
+ if limit is None or not isinstance(limit, int) or limit <= 0:
+ limit = 10
+ while len(_scheme_cache) >= limit:
+ _scheme_cache.popitem(last=True)
+ while len(_highlighter_cache) >= limit:
+ _highlighter_cache.popitem(last=True)
+
+
+def _get_sublime_highlighter(view):
+ """Get the SublimeHighlighter."""
+
+ scheme = view.settings().get('color_scheme')
+ obj = None
+ if scheme is not None:
+ if scheme in _highlighter_cache:
+ obj, t = _highlighter_cache[scheme]
+ if _is_cache_expired(t):
+ obj = None
+ if obj is None:
+ try:
+ obj = SublimeHighlight(scheme)
+ _prune_cache()
+ _highlighter_cache[scheme] = (obj, time.time())
+ except Exception:
+ _log('Failed to get Sublime highlighter object!')
+ _debug(traceback.format_exc(), ERROR)
+ pass
+ return obj
+
+
+def _get_scheme(view):
+ """Get the scheme object and user CSS."""
+
+ scheme = view.settings().get('color_scheme')
+ settings = sublime.load_settings("Preferences.sublime-settings")
+ obj = None
+ user_css = ''
+ default_css = ''
+ if scheme is not None:
+ if scheme in _scheme_cache:
+ obj, user_css, default_css, t = _scheme_cache[scheme]
+ # Check if cache expired or user changed pygments setting.
+ if (
+ _is_cache_expired(t) or
+ obj.use_pygments != (not settings.get(HL_SETTING, True)) or
+ obj.default_style != settings.get(STYLE_SETTING, True)
+ ):
+ obj = None
+ user_css = ''
+ default_css = ''
+ if obj is None:
+ try:
+ obj = SchemeTemplate(scheme)
+ _prune_cache()
+ user_css = _get_user_css()
+ default_css = _get_default_css()
+ _scheme_cache[scheme] = (obj, user_css, default_css, time.time())
+ except Exception:
+ _log('Failed to convert/retrieve scheme to CSS!')
+ _debug(traceback.format_exc(), ERROR)
+ return obj, user_css, default_css
+
+
+def _get_default_css():
+ """Get default CSS."""
+
+ return clean_css(sublime.load_resource(DEFAULT_CSS))
+
+
+def _get_user_css():
+ """Get user css."""
+
+ css = None
+
+ user_css = _get_setting('mdpopups.user_css', DEFAULT_USER_CSS)
+ try:
+ css = clean_css(sublime.load_resource(user_css))
+ except Exception:
+ pass
+ return css if css else ''
+
+
+##############################
+# Markdown parsing
+##############################
+class _MdWrapper(markdown.Markdown):
+ """
+ Wrapper around Python Markdown's class.
+
+ This allows us to gracefully continue when a module doesn't load.
+ """
+
+ Meta = {}
+
+ def __init__(self, *args, **kwargs):
+ """Call original init."""
+
+ if 'allow_code_wrap' in kwargs:
+ self.sublime_wrap = kwargs['allow_code_wrap']
+ del kwargs['allow_code_wrap']
+ if 'sublime_hl' in kwargs:
+ self.sublime_hl = kwargs['sublime_hl']
+ del kwargs['sublime_hl']
+
+ super(_MdWrapper, self).__init__(*args, **kwargs)
+
+ def registerExtensions(self, extensions, configs): # noqa
+ """
+ Register extensions with this instance of Markdown.
+
+ Keyword arguments:
+
+ * extensions: A list of extensions, which can either
+ be strings or objects. See the docstring on Markdown.
+ * configs: A dictionary mapping module names to config options.
+
+ """
+
+ from markdown import util
+ from markdown.extensions import Extension
+
+ for ext in extensions:
+ try:
+ if isinstance(ext, util.string_type):
+ ext = self.build_extension(ext, configs.get(ext, {}))
+ if isinstance(ext, Extension):
+ ext.extendMarkdown(self, globals())
+ elif ext is not None:
+ raise TypeError(
+ 'Extension "%s.%s" must be of type: "markdown.Extension"'
+ % (ext.__class__.__module__, ext.__class__.__name__)
+ )
+ except Exception:
+ # We want to gracefully continue even if an extension fails.
+ _log('Failed to load markdown module!')
+ _debug(traceback.format_exc(), ERROR)
+
+ return self
+
+
+def _get_theme(view, css=None, css_type=POPUP, template_vars=None):
+ """Get the theme."""
+
+ obj, user_css, default_css = _get_scheme(view)
+ try:
+ return obj.apply_template(
+ view,
+ default_css + '\n' +
+ ((clean_css(css) + '\n') if css else '') +
+ user_css,
+ css_type,
+ template_vars
+ ) if obj is not None else ''
+ except Exception:
+ _log('Failed to retrieve scheme CSS!')
+ _debug(traceback.format_exc(), ERROR)
+ return ''
+
+
+def _remove_entities(text):
+ """Remove unsupported HTML entities."""
+
+ import html.parser
+ html = html.parser.HTMLParser()
+
+ def repl(m):
+ """Replace entites except &, <, >, and nbsp."""
+ return html.unescape(m.group(1))
+
+ return RE_BAD_ENTITIES.sub(repl, text)
+
+
+def _create_html(
+ view, content, md=True, css=None, debug=False, css_type=POPUP,
+ wrapper_class=None, template_vars=None, template_env_options=None, nl2br=True,
+ allow_code_wrap=False
+):
+ """Create html from content."""
+
+ debug = _get_setting('mdpopups.debug', NODEBUG)
+
+ if css is None or not isinstance(css, str):
+ css = ''
+
+ style = _get_theme(view, css, css_type, template_vars)
+
+ if debug:
+ _debug('=====CSS=====', INFO)
+ _debug(style, INFO)
+
+ if md:
+ content = md2html(
+ view, content, template_vars=template_vars,
+ template_env_options=template_env_options, nl2br=nl2br,
+ allow_code_wrap=allow_code_wrap
+ )
+ else:
+ # Strip out frontmatter if found as we don't currently
+ # do anything with it when content is just HTML.
+ content = _markup_template(frontmatter.get_frontmatter(content)[1], template_vars, template_env_options)
+
+ if debug:
+ _debug('=====HTML OUTPUT=====', INFO)
+ if bs4:
+ soup = bs4.BeautifulSoup(content, "html.parser")
+ _debug('\n' + soup.prettify(), INFO)
+ else:
+ _debug('\n' + content, INFO)
+
+ if wrapper_class:
+ wrapper = ('
' % wrapper_class) + '%s
'
+ else:
+ wrapper = '
%s
'
+
+ html = "" % (style)
+ html += _remove_entities(wrapper % content)
+ return html
+
+
+def _markup_template(markup, variables, options):
+ """Template for markup."""
+
+ if variables:
+ if options is None:
+ options = {}
+ env = jinja2.Environment(**options)
+ return env.from_string(markup).render(plugin=variables)
+ return markup
+
+
+##############################
+# Public functions
+##############################
+def version():
+ """Get the current version."""
+
+ return ver.version()
+
+
+def md2html(
+ view, markup, template_vars=None, template_env_options=None,
+ nl2br=True, allow_code_wrap=False
+):
+ """Convert Markdown to HTML."""
+
+ if _get_setting('mdpopups.use_sublime_highlighter'):
+ sublime_hl = (True, _get_sublime_highlighter(view))
+ else:
+ sublime_hl = (False, None)
+
+ fm, markup = frontmatter.get_frontmatter(markup)
+
+ # We allways include these
+ extensions = [
+ "mdpopups.mdx.highlight",
+ "mdpopups.mdx.inlinehilite",
+ "mdpopups.mdx.superfences"
+ ]
+
+ configs = {
+ "mdpopups.mdx.highlight": {
+ "guess_lang": False
+ },
+ "mdpopups.mdx.inlinehilite": {
+ "style_plain_text": True
+ },
+ "mdpopups.mdx.superfences": {
+ "custom_fences": fm.get('custom_fences', [])
+ }
+ }
+
+ # Check if plugin is overriding extensions
+ md_exts = fm.get('markdown_extensions', None)
+ if md_exts is None:
+ # No extension override, use defaults
+ extensions.extend(
+ [
+ "markdown.extensions.admonition",
+ "markdown.extensions.attr_list",
+ "markdown.extensions.def_list",
+ "pymdownx.betterem",
+ "pymdownx.magiclink",
+ "pymdownx.extrarawhtml"
+ ]
+ )
+
+ # Use legacy method to determine if nl2b should be used
+ if nl2br:
+ extensions.append('markdown.extensions.nl2br')
+ else:
+ for ext in md_exts:
+ if isinstance(ext, (dict, OrderedDict)):
+ k, v = next(iter(ext.items()))
+ # We don't allow plugins to overrides the internal color
+ if not k.startswith('mdpopups.'):
+ extensions.append(k)
+ if v is not None:
+ configs[k] = v
+ elif isinstance(ext, str):
+ if not ext.startswith('mdpopups.'):
+ extensions.append(ext)
+
+ return _MdWrapper(
+ extensions=extensions,
+ extension_configs=configs,
+ sublime_hl=sublime_hl,
+ allow_code_wrap=fm.get('allow_code_wrap', allow_code_wrap)
+ ).convert(_markup_template(markup, template_vars, template_env_options)).replace('"', '"').replace('\n', '')
+
+
+def color_box(
+ colors, border="#000000ff", border2=None, height=32, width=32,
+ border_size=1, check_size=4, max_colors=5, alpha=False, border_map=0xF
+):
+ """Color box."""
+
+ return colorbox.color_box(
+ colors, border, border2, height, width,
+ border_size, check_size, max_colors, alpha, border_map
+ )
+
+
+def color_box_raw(
+ colors, border="#000000ff", border2=None, height=32, width=32,
+ border_size=1, check_size=4, max_colors=5, alpha=False, border_map=0xF
+):
+ """Color box raw."""
+
+ return colorbox.color_box_raw(
+ colors, border, border2, height, width,
+ border_size, check_size, max_colors, alpha, border_map
+ )
+
+
+def tint(img, color, opacity=255, height=None, width=None):
+ """Tint the image."""
+
+ if isinstance(img, str):
+ try:
+ img = sublime.load_binary_resource(img)
+ except Exception:
+ _log('Could not open binary file!')
+ _debug(traceback.format_exc(), ERROR)
+ return ''
+ return imagetint.tint(img, color, opacity, height, width)
+
+
+def tint_raw(img, color, opacity=255):
+ """Tint the image."""
+
+ if isinstance(img, str):
+ try:
+ img = sublime.load_binary_resource(img)
+ except Exception:
+ _log('Could not open binary file!')
+ _debug(traceback.format_exc(), ERROR)
+ return ''
+ return imagetint.tint_raw(img, color, opacity)
+
+
+def get_language_from_view(view):
+ """Guess current language from view."""
+
+ lang = None
+ user_map = sublime.load_settings('Preferences.sublime-settings').get('mdpopups.sublime_user_lang_map', {})
+ syntax = os.path.splitext(view.settings().get('syntax').replace('Packages/', '', 1))[0]
+ keys = set(list(lang_map.keys()) + list(user_map.keys()))
+ for key in keys:
+ v1 = lang_map.get(key, (tuple(), tuple()))[1]
+ v2 = user_map.get(key, (tuple(), tuple()))[1]
+ if syntax in (tuple(v2) + v1):
+ lang = key
+ break
+ return lang
+
+
+def syntax_highlight(view, src, language=None, inline=False, allow_code_wrap=False):
+ """Syntax highlighting for code."""
+
+ try:
+ if _get_setting('mdpopups.use_sublime_highlighter'):
+ highlighter = _get_sublime_highlighter(view)
+ code = highlighter.syntax_highlight(
+ src, language, inline=inline, code_wrap=(not inline and allow_code_wrap)
+ )
+ else:
+ code = pyg_syntax_hl(
+ src, language, inline=inline, code_wrap=(not inline and allow_code_wrap)
+ )
+ except Exception:
+ code = src
+ _log('Failed to highlight code!')
+ _debug(traceback.format_exc(), ERROR)
+
+ return code
+
+
+def tabs2spaces(text, tab_size=4):
+ """
+ Convert tabs to spaces on tab stops.
+
+ Does not account for char width.
+ """
+
+ return text.expandtabs(tab_size)
+
+
+def scope2style(view, scope, selected=False, explicit_background=False):
+ """Convert the scope to a style."""
+
+ style = {
+ 'color': None,
+ 'background': None,
+ 'style': ''
+ }
+ obj = _get_scheme(view)[0]
+ style_obj = obj.guess_style(view, scope, selected, explicit_background)
+ if NEW_SCHEMES:
+ style['color'] = style_obj['foreground']
+ style['background'] = style_obj['background']
+ font = []
+ if style_obj['bold']:
+ font.append('bold')
+ if style_obj['italic']:
+ font.append('italic')
+ style['style'] = ' '.join(font)
+ else:
+ style['color'] = style_obj.fg_simulated
+ style['background'] = style_obj.bg_simulated
+ style['style'] = style_obj.style
+ return style
+
+
+def clear_cache():
+ """Clear cache."""
+
+ _clear_cache()
+
+
+def hide_popup(view):
+ """Hide the popup."""
+
+ view.hide_popup()
+
+
+def update_popup(
+ view, content, md=True, css=None, wrapper_class=None,
+ template_vars=None, template_env_options=None, nl2br=True,
+ allow_code_wrap=False
+):
+ """Update the popup."""
+
+ disabled = _get_setting('mdpopups.disable', False)
+ if disabled:
+ _debug('Popups disabled', WARNING)
+ return
+
+ try:
+ html = _create_html(
+ view, content, md, css, css_type=POPUP, wrapper_class=wrapper_class,
+ template_vars=template_vars, template_env_options=template_env_options, nl2br=nl2br,
+ allow_code_wrap=allow_code_wrap
+ )
+ except Exception:
+ _log(traceback.format_exc())
+ html = IDK
+
+ view.update_popup(html)
+
+
+def show_popup(
+ view, content, md=True, css=None,
+ flags=0, location=-1, max_width=320, max_height=240,
+ on_navigate=None, on_hide=None, wrapper_class=None,
+ template_vars=None, template_env_options=None, nl2br=True,
+ allow_code_wrap=False
+):
+ """Parse the color scheme if needed and show the styled pop-up."""
+
+ disabled = _get_setting('mdpopups.disable', False)
+ if disabled:
+ _debug('Popups disabled', WARNING)
+ return
+
+ if not _can_show(view, location):
+ return
+
+ try:
+ html = _create_html(
+ view, content, md, css, css_type=POPUP, wrapper_class=wrapper_class,
+ template_vars=template_vars, template_env_options=template_env_options,
+ nl2br=nl2br, allow_code_wrap=allow_code_wrap
+ )
+ except Exception:
+ _log(traceback.format_exc())
+ html = IDK
+
+ view.show_popup(
+ html, flags=flags, location=location, max_width=max_width,
+ max_height=max_height, on_navigate=on_navigate, on_hide=on_hide
+ )
+
+
+def is_popup_visible(view):
+ """Check if popup is visible."""
+
+ return view.is_popup_visible()
+
+
+def add_phantom(
+ view, key, region, content, layout, md=True,
+ css=None, on_navigate=None, wrapper_class=None,
+ template_vars=None, template_env_options=None, nl2br=True,
+ allow_code_wrap=False
+):
+ """Add a phantom and return phantom id."""
+
+ disabled = _get_setting('mdpopups.disable', False)
+ if disabled:
+ _debug('Phantoms disabled', WARNING)
+ return
+
+ try:
+ html = _create_html(
+ view, content, md, css, css_type=PHANTOM, wrapper_class=wrapper_class,
+ template_vars=template_vars, template_env_options=template_env_options,
+ nl2br=nl2br, allow_code_wrap=allow_code_wrap
+ )
+ except Exception:
+ _log(traceback.format_exc())
+ html = IDK
+
+ return view.add_phantom(key, region, html, layout, on_navigate)
+
+
+def erase_phantoms(view, key):
+ """Erase phantoms."""
+
+ view.erase_phantoms(key)
+
+
+def erase_phantom_by_id(view, pid):
+ """Erase phantom by ID."""
+
+ view.erase_phantom_by_id(pid)
+
+
+def query_phantom(view, pid):
+ """Query phantom."""
+
+ return view.query_phantom(pid)
+
+
+def query_phantoms(view, pids):
+ """Query phantoms."""
+
+ return view.query_phantoms(pids)
+
+
+class Phantom(sublime.Phantom):
+ """A phantom object."""
+
+ def __init__(
+ self, region, content, layout, md=True,
+ css=None, on_navigate=None, wrapper_class=None,
+ template_vars=None, template_env_options=None, nl2br=True,
+ allow_code_wrap=False
+ ):
+ """Initialize."""
+
+ super().__init__(region, content, layout, on_navigate)
+ self.md = md
+ self.css = css
+ self.wrapper_class = wrapper_class
+ self.template_vars = template_vars
+ self.template_env_options = template_env_options
+ self.nl2br = nl2br
+ self.allow_code_wrap = allow_code_wrap
+
+ def __eq__(self, rhs):
+ """Check if phantoms are equal."""
+
+ # Note that self.id is not considered
+ return (
+ self.region == rhs.region and self.content == rhs.content and
+ self.layout == rhs.layout and self.on_navigate == rhs.on_navigate and
+ self.md == rhs.md and self.css == rhs.css and self.nl2br == rhs.nl2br and
+ self.wrapper_class == rhs.wrapper_class and self.template_vars == rhs.template_vars and
+ self.template_env_options == rhs.template_env_options and
+ self.allow_code_wrap == rhs.allow_code_wrap
+ )
+
+
+class PhantomSet(sublime.PhantomSet):
+ """Object that allows easy updating of phantoms."""
+
+ def __init__(self, view, key=""):
+ """Initialize."""
+
+ super().__init__(view, key)
+
+ def __del__(self):
+ """Delete phantoms."""
+
+ for p in self.phantoms:
+ erase_phantom_by_id(self.view, p.id)
+
+ def update(self, new_phantoms):
+ """Update the list of phantoms that exist in the text buffer with their current location."""
+
+ regions = query_phantoms(self.view, [p.id for p in self.phantoms])
+ for i in range(len(regions)):
+ self.phantoms[i].region = regions[i]
+
+ count = 0
+ for p in new_phantoms:
+ if not isinstance(p, Phantom):
+ # Convert sublime.Phantom to mdpopups.Phantom
+ p = Phantom(
+ p.region, p.content, p.layout,
+ md=False, css=None, on_navigate=p.on_navigate, wrapper_class=None,
+ template_vars=None, template_env_options=None, nl2br=False,
+ allow_code_wrap=False
+ )
+ new_phantoms[count] = p
+ try:
+ # Phantom already exists, copy the id from the current one
+ idx = self.phantoms.index(p)
+ p.id = self.phantoms[idx].id
+ except ValueError:
+ p.id = add_phantom(
+ self.view,
+ self.key,
+ p.region,
+ p.content,
+ p.layout,
+ p.md,
+ p.css,
+ p.on_navigate,
+ p.wrapper_class,
+ p.template_vars,
+ p.template_env_options,
+ p.nl2br,
+ p.allow_code_wrap
+ )
+ count += 1
+
+ for p in self.phantoms:
+ # if the region is -1, then it's already been deleted, no need to call erase
+ if p not in new_phantoms and p.region != sublime.Region(-1):
+ erase_phantom_by_id(self.view, p.id)
+
+ self.phantoms = new_phantoms
+
+
+def format_frontmatter(values):
+ """Format values as frontmatter."""
+
+ return frontmatter.dump_frontmatter(values)
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/colorbox.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/colorbox.py
new file mode 100644
index 0000000..5dfdb64
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/colorbox.py
@@ -0,0 +1,251 @@
+"""
+Sublime tooltip color box.
+
+Licensed under MIT
+Copyright (c) 2015 - 2016 Isaac Muse
+"""
+from .png import Writer
+from .rgba import RGBA
+import base64
+import io
+
+CHECK_LIGHT = "#FFFFFF"
+CHECK_DARK = "#CCCCCC"
+
+LIGHT = 0
+DARK = 1
+
+TOP = 1
+RIGHT = 2
+BOTTOM = 4
+LEFT = 8
+
+X = 0
+Y = 1
+
+__all__ = ('color_box',)
+
+
+def to_list(rgb, alpha=False):
+ """
+ Break rgb channel itno a list.
+
+ Take a color of the format #RRGGBBAA (alpha optional and will be stripped)
+ and convert to a list with format [r, g, b].
+ """
+ if alpha:
+ return [
+ int(rgb[1:3], 16),
+ int(rgb[3:5], 16),
+ int(rgb[5:7], 16),
+ int(rgb[7:9], 16) if len(rgb) > 7 else 255
+ ]
+ else:
+ return [
+ int(rgb[1:3], 16),
+ int(rgb[3:5], 16),
+ int(rgb[5:7], 16)
+ ]
+
+
+def checkered_color(color, background):
+ """Mix color with the checkered color."""
+
+ checkered = RGBA(color)
+ checkered.apply_alpha(background)
+ return checkered.get_rgb()
+
+
+def get_border_size(direction, border_map):
+ """Get size of border map."""
+
+ size = 0
+ if direction == X:
+ if border_map & LEFT:
+ size += 1
+ if border_map & RIGHT:
+ size += 1
+ elif direction == Y:
+ if border_map & TOP:
+ size += 1
+ if border_map & BOTTOM:
+ size += 1
+ return size
+
+
+def color_box_raw(
+ colors, border="#000000", border2=None, height=32, width=32,
+ border_size=1, check_size=4, max_colors=5, alpha=False, border_map=0xF
+):
+ """
+ Generate palette preview.
+
+ Create a color box with the specified RGBA color(s)
+ and RGB(A) border (alpha will be stripped out of border color).
+ Colors is a list of colors, but only up to 5
+ Border can be up to 2 colors (double border).
+
+ Hight, width and border thickness can all be defined.
+
+ If using a transparent color, you can define the checkerboard pattern size that shows through.
+ If using multiple colors, you can control the max colors to display. Colors currently are done
+ horizontally only.
+
+ Define size of swatch, border width, and size of checkerboard squares.
+ """
+
+ assert height - (border_size * 2) >= 0, "Border size too big!"
+ assert width - (border_size * 2) >= 0, "Border size too big!"
+
+ # Gather preview colors
+ preview_colors = []
+ count = max_colors if len(colors) >= max_colors else len(colors)
+
+ border = to_list(border, False)
+ if border2 is not None:
+ border2 = to_list(border2, False)
+
+ border1_size = border2_size = int(border_size / 2)
+ border1_size += border_size % 2
+ if border2 is None:
+ border1_size += border2_size
+ border2_size = 0
+
+ if count:
+ for c in range(0, count):
+ if alpha:
+ preview_colors.append(
+ (
+ to_list(colors[c], True),
+ to_list(colors[c], True)
+ )
+ )
+ else:
+ preview_colors.append(
+ (
+ to_list(checkered_color(colors[c], CHECK_LIGHT)),
+ to_list(checkered_color(colors[c], CHECK_DARK))
+ )
+ )
+ else:
+ if alpha:
+ preview_colors.append(
+ (to_list('#00000000'), to_list('#00000000'))
+ )
+ else:
+ preview_colors.append(
+ (to_list(CHECK_LIGHT), to_list(CHECK_DARK))
+ )
+
+ color_height = height - (border_size * get_border_size(Y, border_map))
+ color_width = width - (border_size * get_border_size(X, border_map))
+
+ if count:
+ dividers = int(color_width / count)
+ if color_width % count:
+ dividers += 1
+ else:
+ dividers = 0
+
+ color_size_x = color_width
+
+ p = []
+
+ # Top Border
+ if border_map & TOP:
+ for x in range(0, border1_size):
+ row = list(border * width)
+ p.append(row)
+ for x in range(0, border2_size):
+ row = []
+ if border_map & LEFT and border_map & RIGHT:
+ row += list(border * border1_size)
+ row += list(border2 * border2_size)
+ row += list(border2 * color_width)
+ row += list(border2 * border2_size)
+ row += list(border * border1_size)
+ elif border_map & RIGHT:
+ row += list(border2 * color_width)
+ row += list(border2 * border2_size)
+ row += list(border * border1_size)
+ elif border_map & LEFT:
+ row += list(border * border1_size)
+ row += list(border2 * border2_size)
+ row += list(border2 * color_width)
+ else:
+ row += list(border2 * color_width)
+ p.append(row)
+
+ check_color_y = DARK
+ for y in range(0, color_height):
+ index = 0
+ if y % check_size == 0:
+ check_color_y = DARK if check_color_y == LIGHT else LIGHT
+
+ # Left border
+ row = []
+ if border_map & LEFT:
+ row += list(border * border1_size)
+ if border2:
+ row += list(border2 * border2_size)
+
+ check_color_x = check_color_y
+ for x in range(0, color_size_x):
+ if x != 0 and dividers != 0 and x % dividers == 0:
+ index += 1
+ if x % check_size == 0:
+ check_color_x = DARK if check_color_x == LIGHT else LIGHT
+ row += (preview_colors[index][1] if check_color_x == DARK else preview_colors[index][0])
+
+ if border_map & RIGHT:
+ # Right border
+ if border2:
+ row += list(border2 * border2_size)
+ row += list(border * border1_size)
+
+ p.append(row)
+
+ if border_map & BOTTOM:
+ # Bottom border
+ for x in range(0, border2_size):
+ row = []
+ if border_map & LEFT and border_map & RIGHT:
+ row += list(border * border1_size)
+ row += list(border2 * border2_size)
+ row += list(border2 * color_width)
+ row += list(border2 * border2_size)
+ row += list(border * border1_size)
+ elif border_map & LEFT:
+ row += list(border * border1_size)
+ row += list(border2 * border2_size)
+ row += list(border2 * color_width)
+ elif border_map & RIGHT:
+ row += list(border2 * color_width)
+ row += list(border2 * border2_size)
+ row += list(border * border1_size)
+ else:
+ row += list(border2 * color_width)
+ p.append(row)
+ for x in range(0, border1_size):
+ row = list(border * width)
+ p.append(row)
+
+ # Create bytes buffer for png
+ with io.BytesIO() as f:
+
+ # Write out png
+ img = Writer(width, height, alpha=alpha)
+ img.write(f, p)
+
+ # Read out png bytes and base64 encode
+ f.seek(0)
+
+ return f.read()
+
+
+def color_box(*args, **kwargs):
+ """Generate palette preview and base64 encode it."""
+
+ return "" % (
+ base64.b64encode(color_box_raw(*args, **kwargs)).decode('ascii')
+ )
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/file_strip/__init__.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/file_strip/__init__.py
new file mode 100644
index 0000000..379abc3
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/file_strip/__init__.py
@@ -0,0 +1 @@
+"""File Strip."""
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/file_strip/comments.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/file_strip/comments.py
new file mode 100644
index 0000000..9c6d248
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/file_strip/comments.py
@@ -0,0 +1,130 @@
+"""
+File Strip.
+
+Licensed under MIT
+Copyright (c) 2012 Isaac Muse
+"""
+import re
+
+LINE_PRESERVE = re.compile(r"\r?\n", re.MULTILINE)
+CPP_PATTERN = re.compile(
+ r'''(?x)
+ (?P
+ /\*[^*]*\*+(?:[^/*][^*]*\*+)*/ # multi-line comments
+ | \s*//(?:[^\r\n])* # single line comments
+ )
+ | (?P
+ "(?:\\.|[^"\\])*" # double quotes
+ | '(?:\\.|[^'\\])*' # single quotes
+ | .[^/"']* # everything else
+ )
+ ''',
+ re.DOTALL
+)
+PY_PATTERN = re.compile(
+ r'''(?x)
+ (?P
+ \s*\#(?:[^\r\n])* # single line comments
+ )
+ | (?P
+ "{3}(?:\\.|[^\\])*"{3} # triple double quotes
+ | '{3}(?:\\.|[^\\])*'{3} # triple single quotes
+ | "(?:\\.|[^"\\])*" # double quotes
+ | '(?:\\.|[^'])*' # single quotes
+ | .[^\#"']* # everything else
+ )
+ ''',
+ re.DOTALL
+)
+
+
+def _strip_regex(pattern, text, preserve_lines):
+ """Generic function that strips out comments pased on the given pattern."""
+
+ def remove_comments(group, preserve_lines=False):
+ """Remove comments."""
+
+ return ''.join([x[0] for x in LINE_PRESERVE.findall(group)]) if preserve_lines else ''
+
+ def evaluate(m, preserve_lines):
+ """Search for comments."""
+
+ g = m.groupdict()
+ return g["code"] if g["code"] is not None else remove_comments(g["comments"], preserve_lines)
+
+ return ''.join(map(lambda m: evaluate(m, preserve_lines), pattern.finditer(text)))
+
+
+@staticmethod
+def _cpp(text, preserve_lines=False):
+ """C/C++ style comment stripper."""
+
+ return _strip_regex(
+ CPP_PATTERN,
+ text,
+ preserve_lines
+ )
+
+
+@staticmethod
+def _python(text, preserve_lines=False):
+ """Python style comment stripper."""
+
+ return _strip_regex(
+ PY_PATTERN,
+ text,
+ preserve_lines
+ )
+
+
+class CommentException(Exception):
+ """Comment exception."""
+
+ def __init__(self, value):
+ """Setup exception."""
+
+ self.value = value
+
+ def __str__(self):
+ """Return exception value repr on string convert."""
+
+ return repr(self.value)
+
+
+class Comments(object):
+ """Comment strip class."""
+
+ styles = []
+
+ def __init__(self, style=None, preserve_lines=False):
+ """Initialize."""
+
+ self.preserve_lines = preserve_lines
+ self.call = self.__get_style(style)
+
+ @classmethod
+ def add_style(cls, style, fn):
+ """Add comment style."""
+
+ if style not in cls.__dict__:
+ setattr(cls, style, fn)
+ cls.styles.append(style)
+
+ def __get_style(self, style):
+ """Get the comment style."""
+
+ if style in self.styles:
+ return getattr(self, style)
+ else:
+ raise CommentException(style)
+
+ def strip(self, text):
+ """Strip comments."""
+
+ return self.call(text, self.preserve_lines)
+
+
+Comments.add_style("c", _cpp)
+Comments.add_style("json", _cpp)
+Comments.add_style("cpp", _cpp)
+Comments.add_style("python", _python)
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/file_strip/json.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/file_strip/json.py
new file mode 100644
index 0000000..a25118d
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/file_strip/json.py
@@ -0,0 +1,70 @@
+"""
+File Strip.
+
+Licensed under MIT
+Copyright (c) 2012 Isaac Muse
+"""
+import re
+from .comments import Comments
+
+JSON_PATTERN = re.compile(
+ r'''(?x)
+ (
+ (?P
+ , # trailing comma
+ (?P[\s\r\n]*) # white space
+ (?P\]) # bracket
+ )
+ | (?P
+ , # trailing comma
+ (?P[\s\r\n]*) # white space
+ (?P\}) # bracket
+ )
+ )
+ | (?P
+ "(?:\\.|[^"\\])*" # double quoted string
+ | '(?:\\.|[^'\\])*' # single quoted string
+ | .[^,"']* # everything else
+ )
+ ''',
+ re.DOTALL
+)
+
+
+def strip_dangling_commas(text, preserve_lines=False):
+ """Strip dangling commas."""
+
+ regex = JSON_PATTERN
+
+ def remove_comma(g, preserve_lines):
+ """Remove comma."""
+
+ if preserve_lines:
+ # ,] -> ] else ,} -> }
+ if g["square_comma"] is not None:
+ return g["square_ws"] + g["square_bracket"]
+ else:
+ return g["curly_ws"] + g["curly_bracket"]
+ else:
+ # ,] -> ] else ,} -> }
+ return g["square_bracket"] if g["square_comma"] else g["curly_bracket"]
+
+ def evaluate(m, preserve_lines):
+ """Search for dangling comma."""
+
+ g = m.groupdict()
+ return remove_comma(g, preserve_lines) if g["code"] is None else g["code"]
+
+ return ''.join(map(lambda m: evaluate(m, preserve_lines), regex.finditer(text)))
+
+
+def strip_comments(text, preserve_lines=False):
+ """Strip JavaScript like comments."""
+
+ return Comments('json', preserve_lines).strip(text)
+
+
+def sanitize_json(text, preserve_lines=False):
+ """Sanitize the JSON file by removing comments and dangling commas."""
+
+ return strip_dangling_commas(Comments('json', preserve_lines).strip(text), preserve_lines)
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/frontmatter.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/frontmatter.py
new file mode 100644
index 0000000..4958a90
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/frontmatter.py
@@ -0,0 +1,88 @@
+"""Frontmatter stripping."""
+import yaml
+import re
+from collections import OrderedDict
+
+
+def yaml_load(stream, loader=yaml.Loader, object_pairs_hook=OrderedDict):
+ """
+ Custom yaml loader.
+
+ Make all YAML dictionaries load as ordered Dicts.
+ http://stackoverflow.com/a/21912744/3609487
+
+ Load all strings as unicode.
+ http://stackoverflow.com/a/2967461/3609487
+ """
+
+ def construct_mapping(loader, node):
+ """Convert to ordered dict."""
+
+ loader.flatten_mapping(node)
+ return object_pairs_hook(loader.construct_pairs(node))
+
+ def construct_yaml_str(self, node):
+ """Override the default string handling function to always return unicode objects."""
+
+ return self.construct_scalar(node)
+
+ class Loader(loader):
+ """Custom Loader."""
+
+ Loader.add_constructor(
+ yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
+ construct_mapping
+ )
+
+ Loader.add_constructor(
+ 'tag:yaml.org,2002:str',
+ construct_yaml_str
+ )
+
+ return yaml.load(stream, Loader)
+
+
+def yaml_dump(data, stream=None, dumper=yaml.Dumper):
+ """Special dumper wrapper to modify the yaml dumper."""
+
+ class Dumper(dumper):
+ """Custom dumper."""
+
+ # Handle Ordered Dict
+ Dumper.add_representer(
+ OrderedDict,
+ lambda self, data: self.represent_mapping('tag:yaml.org,2002:map', data.items())
+ )
+
+ return yaml.dump(data, stream, Dumper, width=None, indent=4, allow_unicode=True, default_flow_style=False)
+
+
+def dump_frontmatter(values):
+ """Turn Python dict values to frontmatter string."""
+
+ return '---\n%s\n...\n' % yaml_dump(values)
+
+
+def get_frontmatter(string):
+ """Get frontmatter from string."""
+
+ frontmatter = OrderedDict()
+
+ if string.startswith("---"):
+ m = re.search(r'^(-{3}\r?\n(?!\r?\n)(.*?)(?<=\n)(?:-{3}|\.{3})\r?\n)', string, re.DOTALL)
+ if m:
+ yaml_okay = True
+ try:
+ frontmatter = yaml_load(m.group(2))
+ if frontmatter is None:
+ frontmatter = OrderedDict()
+ # If we didn't get a dictionary, we don't want this as it isn't frontmatter.
+ assert isinstance(frontmatter, (dict, OrderedDict)), TypeError
+ except Exception:
+ # We had a parsing error. This is not the YAML we are looking for.
+ yaml_okay = False
+ frontmatter = OrderedDict()
+ if yaml_okay:
+ string = string[m.end(1):]
+
+ return frontmatter, string
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/imagetint.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/imagetint.py
new file mode 100644
index 0000000..60d2760
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/imagetint.py
@@ -0,0 +1,67 @@
+"""
+Image tinting.
+
+Licensed under MIT
+Copyright (c) 2015 - 2016 Isaac Muse
+"""
+from .png import Reader, Writer
+from .rgba import RGBA
+import base64
+import io
+
+
+def tint_raw(byte_string, color, opacity=255):
+ """Tint the image and return a byte string."""
+
+ # Read the bytestring as a rgba image.
+ width, height, pixels, meta = Reader(bytes=byte_string).asRGBA()
+
+ # Clamp opacity
+ if opacity < 0:
+ opacity = 0
+ elif opacity > 255:
+ opacity = 255
+
+ # Tint
+ p = []
+ y = 0
+ for row in pixels:
+ p.append([])
+ columns = int(len(row) / 4)
+ start = 0
+ for x in range(columns):
+ rgba = RGBA(color)
+ rgba.a = opacity
+ rgba.apply_alpha(background='#%02X%02X%02XFF' % tuple(row[start:start + 3]))
+ p[y] += [rgba.r, rgba.g, rgba.b, row[start + 3]]
+ start += 4
+ y += 1
+
+ # Create bytes buffer for png
+ with io.BytesIO() as f:
+
+ # Write out png
+ img = Writer(width, height, alpha=True)
+ img.write(f, p)
+
+ # Read out png bytes and base64 encode
+ f.seek(0)
+
+ return f.read()
+
+
+def tint(byte_string, color, opacity=255, height=None, width=None):
+ """Base64 encode the tint."""
+
+ style = ''
+ if width:
+ style = 'style="width: %dpx;"' % width
+ if height is not None and style is None:
+ style = 'style="height: %dpx;"' % width
+ elif height is not None:
+ style = style[:-1] + (' height: %dpx;" ' % height)
+
+ return "" % (
+ style,
+ base64.b64encode(tint_raw(byte_string, color, opacity)).decode('ascii')
+ )
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/mdx/__init__.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/mdx/__init__.py
new file mode 100644
index 0000000..68549fc
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/mdx/__init__.py
@@ -0,0 +1 @@
+"""Modules for Python Markdown."""
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/mdx/highlight.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/mdx/highlight.py
new file mode 100644
index 0000000..c725446
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/mdx/highlight.py
@@ -0,0 +1,476 @@
+"""
+Highlight.
+
+A library for managing code highlighting.
+
+All Changes Copyright 2014-2017 Isaac Muse.
+
+---
+
+CodeHilite Extension for Python-Markdown
+========================================
+
+Adds code/syntax highlighting to standard Python-Markdown code blocks.
+
+See
+for documentation.
+
+Original code Copyright 2006-2008 [Waylan Limberg](http://achinghead.com/).
+
+All changes Copyright 2008-2014 The Python Markdown Project
+
+License: [BSD](http://www.opensource.org/licenses/bsd-license.php)
+"""
+from __future__ import absolute_import
+from __future__ import unicode_literals
+from markdown import Extension
+from markdown.treeprocessors import Treeprocessor
+from markdown import util as md_util
+import copy
+from collections import OrderedDict
+import re
+try:
+ from pygments import highlight
+ from pygments.lexers import get_lexer_by_name, guess_lexer
+ from pygments.formatters import find_formatter_class
+ HtmlFormatter = find_formatter_class('html')
+ pygments = True
+except ImportError: # pragma: no cover
+ pygments = False
+try:
+ from markdown.extensions.codehilite import CodeHiliteExtension
+except Exception: # pragma: no cover
+ CodeHiliteExtension = None
+
+CODE_WRAP = '
%s
'
+CLASS_ATTR = ' class="%s"'
+DEFAULT_CONFIG = {
+ 'use_pygments': [
+ True,
+ 'Use Pygments to highlight code blocks. '
+ 'Disable if using a JavaScript library. '
+ 'Default: True'
+ ],
+ 'guess_lang': [
+ False,
+ "Automatic language detection - Default: True"
+ ],
+ 'css_class': [
+ 'highlight',
+ "CSS class to apply to wrapper element."
+ ],
+ 'pygments_style': [
+ 'default',
+ 'Pygments HTML Formatter Style '
+ '(color scheme) - Default: default'
+ ],
+ 'noclasses': [
+ False,
+ 'Use inline styles instead of CSS classes - '
+ 'Default false'
+ ],
+ 'linenums': [
+ False,
+ 'Display line numbers in block code output (not inline) - Default: False'
+ ],
+ 'extend_pygments_lang': [
+ [],
+ 'Extend pygments language with special language entry - Default: {}'
+ ]
+}
+
+multi_space = re.compile(r'(?<= ) {2,}')
+
+
+def replace_nbsp(m):
+ """Replace spaces with nbsp."""
+
+ return ' ' * len(m.group(0))
+
+
+if pygments:
+ html_re = re.compile(
+ r'''(?x)
+ (?P]+>)|(?P[^<>]+)|(?P)
+ '''
+ )
+
+ class InlineHtmlFormatter(HtmlFormatter):
+ """Format the code blocks."""
+
+ def wrap(self, source, outfile):
+ """Overload wrap."""
+
+ return self._wrap_code(source)
+
+ def _wrap_code(self, source):
+ """Return source, but do not wrap in inline block."""
+
+ yield 0, ''
+ for i, t in source:
+ yield i, t.strip()
+ yield 0, ''
+
+ class SublimeInlineHtmlFormatter(HtmlFormatter):
+ """Format the code blocks."""
+
+ def wrap(self, source, outfile):
+ """Overload wrap."""
+
+ return self._wrap_code(source)
+
+ def _wrap_code(self, source):
+ """
+ Wrap the pygmented code.
+
+ Sublime popups don't really support 'code', but since it doesn't
+ hurt anything, we leave it in for the possiblity of future support.
+ We get around the lack of proper 'code' support by converting any
+ spaces after the intial space to nbsp. We go ahead and convert tabs
+ to 4 spaces as well.
+ """
+
+ yield 0, ''
+ for i, t in source:
+ text = ''
+ matched = False
+ for m in html_re.finditer(t):
+ matched = True
+ if m.group(1):
+ text += m.group(1)
+ elif m.group(3):
+ text += m.group(3)
+ else:
+ text += multi_space.sub(
+ replace_nbsp, m.group(2).replace('\t', ' ' * 4)
+ )
+ if not matched:
+ text = multi_space.sub(
+ replace_nbsp, t.replace('\t', ' ' * 4)
+ )
+ yield i, text
+ yield 0, ''
+
+ class SublimeBlockFormatter(HtmlFormatter):
+ """Format the code blocks."""
+
+ def wrap(self, source, outfile):
+ """Overload wrap."""
+
+ return self._wrap_code(source)
+
+ def _wrap_code(self, source):
+ """
+ Wrap the pygmented code.
+
+ Sublime popups don't really support 'pre', but since it doesn't
+ hurt anything, we leave it in for the possiblity of future support.
+ We get around the lack of proper 'pre' suppurt by converting any
+ spaces after the intial space to nbsp. We go ahead and convert tabs
+ to 4 spaces as well. We also manually inject line breaks.
+ """
+
+ yield 0, '
' % self.cssclass
+ for i, t in source:
+ text = ''
+ matched = False
+ for m in html_re.finditer(t):
+ matched = True
+ if m.group(1):
+ text += m.group(1)
+ elif m.group(3):
+ text += m.group(3)
+ else:
+ text += m.group(2).replace('\t', ' ' * 4).replace(' ', ' ')
+ if not matched:
+ text = t.replace('\t', ' ' * 4).replace(' ', ' ')
+ if i == 1:
+ # it's a line of formatted code
+ text += ' '
+ yield i, text
+ yield 0, '
'
+
+ class SublimeWrapBlockFormatter(HtmlFormatter):
+ """Format the code blocks."""
+
+ def wrap(self, source, outfile):
+ """Overload wrap."""
+
+ return self._wrap_code(source)
+
+ def _wrap_code(self, source):
+ """
+ Wrap the pygmented code.
+
+ Sublime popups don't really support 'pre', but since it doesn't
+ hurt anything, we leave it in for the possiblity of future support.
+ We get around the lack of proper 'pre' suppurt by converting any
+ spaces after the intial space to nbsp. We go ahead and convert tabs
+ to 4 spaces as well. We also manually inject line breaks.
+ """
+
+ yield 0, '
' % self.cssclass
+ for i, t in source:
+ text = ''
+ matched = False
+ for m in html_re.finditer(t):
+ matched = True
+ if m.group(1):
+ text += m.group(1)
+ elif m.group(3):
+ text += m.group(3)
+ else:
+ text += multi_space.sub(
+ replace_nbsp, m.group(2).replace('\t', ' ' * 4)
+ )
+ if not matched:
+ text = multi_space.sub(
+ replace_nbsp, t.replace('\t', ' ' * 4)
+ )
+ if i == 1:
+ # it's a line of formatted code
+ text += ' '
+ yield i, text
+ yield 0, '
'
+
+
+class Highlight(object):
+ """Highlight class."""
+
+ def __init__(
+ self, guess_lang=True, pygments_style='default', use_pygments=True,
+ noclasses=False, extend_pygments_lang=None, linenums=False
+ ):
+ """Initialize."""
+
+ self.guess_lang = guess_lang
+ self.pygments_style = pygments_style
+ self.use_pygments = use_pygments
+ self.noclasses = noclasses
+ self.linenums = linenums
+ self.linenums_style = 'table'
+ self.sublime_hl = Highlight.sublime_hl
+ self.sublime_wrap = Highlight.sublime_wrap
+
+ if extend_pygments_lang is None:
+ extend_pygments_lang = []
+ self.extend_pygments_lang = {}
+ for language in extend_pygments_lang:
+ if isinstance(language, (dict, OrderedDict)):
+ name = language.get('name')
+ if name is not None and name not in self.extend_pygments_lang:
+ self.extend_pygments_lang[name] = [
+ language.get('lang'),
+ language.get('options', {})
+ ]
+
+ @classmethod
+ def set_sublime_vars(cls, sublime_hl, sublime_wrap):
+ """Set Sublime_vars."""
+
+ cls.sublime_hl = sublime_hl
+ cls.sublime_wrap = sublime_wrap
+
+ def get_extended_language(self, language):
+ """Get extended language."""
+
+ return self.extend_pygments_lang.get(language, (language, {}))
+
+ def get_lexer(self, src, language):
+ """Get the Pygments lexer."""
+
+ if language:
+ language, lexer_options = self.get_extended_language(language)
+ else:
+ lexer_options = {}
+
+ # Try and get lexer by the name given.
+ try:
+ lexer = get_lexer_by_name(language, **lexer_options)
+ except Exception:
+ lexer = None
+
+ if lexer is None:
+ if self.guess_lang:
+ lexer = guess_lexer(src)
+ else:
+ lexer = get_lexer_by_name('text')
+ return lexer
+
+ def escape(self, txt, code_wrap):
+ """Basic html escaping."""
+
+ txt = txt.replace('&', '&')
+ txt = txt.replace('<', '<')
+ txt = txt.replace('>', '>')
+ txt = txt.replace('"', '"')
+ # Special format for sublime.
+ if code_wrap:
+ txt = multi_space.sub(replace_nbsp, txt.replace('\t', ' ' * 4))
+ else:
+ txt = txt.replace('\t', ' ' * 4)
+ txt = txt.replace(' ', ' ')
+ return txt
+
+ def highlight(
+ self, src, language, css_class='highlight', hl_lines=None,
+ linestart=-1, linestep=-1, linespecial=-1, inline=False
+ ):
+ """Highlight code."""
+
+ # Convert with Pygments.
+ if self.sublime_hl[0]:
+ # Sublime highlight
+ code = self.sublime_hl[1].syntax_highlight(
+ src, language, inline=inline, no_wrap=inline, code_wrap=(not inline and self.sublime_wrap)
+ )
+ if inline:
+ class_str = css_class
+ elif pygments and self.use_pygments:
+ # Setup language lexer.
+ lexer = self.get_lexer(src, language)
+
+ # Setup line specific settings.
+ linenums = self.linenums_style if (self.linenums or linestart >= 0) and not inline > 0 else False
+ if not linenums or linestep < 1:
+ linestep = 1
+ if not linenums or linestart < 1:
+ linestart = 1
+ if not linenums or linespecial < 0:
+ linespecial = 0
+ if hl_lines is None or inline:
+ hl_lines = []
+
+ # Setup formatter
+ if inline:
+ html_formatter = SublimeInlineHtmlFormatter
+ elif self.sublime_wrap:
+ html_formatter = SublimeWrapBlockFormatter
+ else:
+ html_formatter = SublimeBlockFormatter
+ formatter = html_formatter(
+ cssclass=css_class,
+ linenos=linenums,
+ linenostart=linestart,
+ linenostep=linestep,
+ linenospecial=linespecial,
+ style=self.pygments_style,
+ noclasses=self.noclasses,
+ hl_lines=hl_lines
+ )
+
+ # Convert
+ code = highlight(src, lexer, formatter)
+ if inline:
+ class_str = css_class
+ elif inline:
+ # Format inline code for a JavaScript Syntax Highlighter by specifying language.
+ code = self.escape(src, True)
+ classes = [css_class] if css_class else []
+ if language:
+ classes.append('language-%s' % language)
+ class_str = ''
+ if len(classes):
+ class_str = ' '.join(classes)
+ else:
+ # Format block code for a JavaScript Syntax Highlighter by specifying language.
+ classes = []
+ linenums = self.linenums_style if (self.linenums or linestart >= 0) and not inline > 0 else False
+ if language:
+ classes.append('language-%s' % language)
+ if linenums:
+ classes.append('linenums')
+ class_str = ''
+ if classes:
+ class_str = CLASS_ATTR % ' '.join(classes)
+ higlight_class = (CLASS_ATTR % css_class) if css_class else ''
+ code = CODE_WRAP % (higlight_class, class_str, self.escape(src, self.sublime_wrap))
+
+ if inline:
+ el = md_util.etree.Element('code', {'class': class_str} if class_str else {})
+ el.text = code
+ return el
+ else:
+ return code.strip()
+
+
+def get_hl_settings(md):
+ """Get the specified extension."""
+ target = None
+
+ for ext in md.registeredExtensions:
+ if isinstance(ext, HighlightExtension):
+ target = ext.getConfigs()
+ break
+
+ if target is None:
+ for ext in md.registeredExtensions:
+ if isinstance(ext, CodeHiliteExtension):
+ target = ext.getConfigs()
+ break
+
+ if target is None:
+ target = {}
+ config_clone = copy.deepcopy(DEFAULT_CONFIG)
+ for k, v in config_clone.items():
+ target[k] = config_clone[k][0]
+ return target
+
+
+class HighlightTreeprocessor(Treeprocessor):
+ """Highlight source code in code blocks."""
+
+ def run(self, root):
+ """Find code blocks and store in `htmlStash`."""
+
+ blocks = root.iter('pre')
+ for block in blocks:
+ if len(block) == 1 and block[0].tag == 'code':
+ code = Highlight(
+ guess_lang=self.config['guess_lang'],
+ pygments_style=self.config['pygments_style'],
+ use_pygments=self.config['use_pygments'],
+ noclasses=self.config['noclasses'],
+ linenums=self.config['linenums'],
+ extend_pygments_lang=self.config['extend_pygments_lang']
+ )
+ placeholder = self.markdown.htmlStash.store(
+ code.highlight(
+ block[0].text,
+ '',
+ self.config['css_class']
+ ),
+ safe=True
+ )
+
+ # Clear codeblock in etree instance
+ block.clear()
+ # Change to p element which will later
+ # be removed when inserting raw html
+ block.tag = 'p'
+ block.text = placeholder
+
+
+class HighlightExtension(Extension):
+ """Configure highlight settings globally."""
+
+ def __init__(self, *args, **kwargs):
+ """Initialize."""
+
+ self.config = copy.deepcopy(DEFAULT_CONFIG)
+ super(HighlightExtension, self).__init__(*args, **kwargs)
+
+ def extendMarkdown(self, md, md_globals):
+ """Add support for code highlighting."""
+
+ Highlight.set_sublime_vars(md.sublime_hl, md.sublime_wrap)
+ ht = HighlightTreeprocessor(md)
+ ht.config = self.getConfigs()
+ md.treeprocessors.add("indent-highlight", ht, "
+"""
+
+from __future__ import absolute_import
+from __future__ import unicode_literals
+from markdown import Extension
+from markdown.inlinepatterns import Pattern
+from markdown import util as md_util
+from . import highlight as hl
+
+ESCAPED_BSLASH = '%s%s%s' % (md_util.STX, ord('\\'), md_util.ETX)
+DOUBLE_BSLASH = '\\\\'
+BACKTICK_CODE_RE = r'''(?x)
+(?:
+(?(?:\\{2})+)(?=`+) | # Process code escapes before code
+(?`+)
+((?:\:{3,}|\#!)(?P[\w#.+-]*)\s+)? # Optional language
+(?P.+?) # Code
+(?', '>')
+ txt = txt.replace('"', '"')
+ return txt
+
+
+class InlineHilitePattern(Pattern):
+ """Handle the inline code patterns."""
+
+ def __init__(self, pattern, md):
+ """Initialize."""
+
+ Pattern.__init__(self, pattern)
+ self.markdown = md
+ self.get_hl_settings = False
+
+ def get_settings(self):
+ """Check for CodeHilite extension and gather its settings."""
+
+ if not self.get_hl_settings:
+ self.get_hl_settings = True
+ self.style_plain_text = self.config['style_plain_text']
+
+ config = hl.get_hl_settings(self.markdown)
+ css_class = self.config['css_class']
+ self.css_class = css_class if css_class else config['css_class']
+
+ self.extend_pygments_lang = config.get('extend_pygments_lang', None)
+ self.guess_lang = config['guess_lang']
+ self.pygments_style = config['pygments_style']
+ self.use_pygments = config['use_pygments']
+ self.noclasses = config['noclasses']
+
+ def highlight_code(self, language, src):
+ """Syntax highlight the inline code block."""
+
+ process_text = self.style_plain_text or language or self.guess_lang
+
+ if process_text:
+ el = hl.Highlight(
+ guess_lang=self.guess_lang,
+ pygments_style=self.pygments_style,
+ use_pygments=self.use_pygments,
+ noclasses=self.noclasses,
+ extend_pygments_lang=self.extend_pygments_lang
+ ).highlight(src, language, self.css_class, inline=True)
+ el.text = self.markdown.htmlStash.store(el.text, safe=True)
+ else:
+ el = md_util.etree.Element('code')
+ el.text = self.markdown.htmlStash.store(_escape(src), safe=True)
+ return el
+
+ def handleMatch(self, m):
+ """Handle the pattern match."""
+
+ if m.group('escapes'):
+ return m.group('escapes').replace(DOUBLE_BSLASH, ESCAPED_BSLASH)
+ else:
+ lang = m.group('lang') if m.group('lang') else ''
+ src = m.group('code').strip()
+ self.get_settings()
+ return self.highlight_code(lang, src)
+
+
+class InlineHiliteExtension(Extension):
+ """Add inline highlighting extension to Markdown class."""
+
+ def __init__(self, *args, **kwargs):
+ """Initialize."""
+
+ self.config = {
+ 'style_plain_text': [
+ False,
+ "Process inline code even when a language is not specified "
+ "or langauge is specified as 'text'. "
+ "When 'False', no classes will be added to 'text' code blocks"
+ "and no scoping will performed. The content will just be escaped."
+ "- Default: False"
+ ],
+ 'css_class': [
+ '',
+ "Set class name for wrapper element. The default of CodeHilite or Highlight will be used"
+ "if nothing is set. - "
+ "Default: ''"
+ ]
+ }
+ super(InlineHiliteExtension, self).__init__(*args, **kwargs)
+
+ def extendMarkdown(self, md, md_globals):
+ """Add support for `:::language code` and `#!language code` highlighting."""
+
+ config = self.getConfigs()
+ inline_hilite = InlineHilitePattern(BACKTICK_CODE_RE, md)
+ inline_hilite.config = config
+ md.inlinePatterns['backtick'] = inline_hilite
+
+
+def makeExtension(*args, **kwargs):
+ """Return extension."""
+
+ return InlineHiliteExtension(*args, **kwargs)
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/mdx/superfences.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/mdx/superfences.py
new file mode 100644
index 0000000..86df52b
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/mdx/superfences.py
@@ -0,0 +1,640 @@
+"""
+SuperFences.
+
+pymdownx.superfences
+Nested Fenced Code Blocks
+
+This is a modification of the original Fenced Code Extension.
+Algorithm has been rewritten to allow for fenced blocks in blockquotes,
+lists, etc. And also , allow for special UML fences like 'flow' for flowcharts
+and `sequence` for sequence diagrams.
+
+Modified: 2014 - 2017 Isaac Muse
+---
+
+Fenced Code Extension for Python Markdown
+=========================================
+
+This extension adds Fenced Code Blocks to Python-Markdown.
+
+See
+for documentation.
+
+Original code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com/).
+
+
+All changes Copyright 2008-2014 The Python Markdown Project
+
+License: [BSD](http://www.opensource.org/licenses/bsd-license.php)
+"""
+
+from __future__ import absolute_import
+from __future__ import unicode_literals
+from markdown.extensions import Extension
+from markdown.preprocessors import Preprocessor
+from markdown.blockprocessors import CodeBlockProcessor
+from markdown import util as md_util
+from . import highlight as hl
+import re
+
+SOH = '\u0001'
+EOT = '\u0004'
+
+PREFIX_CHARS = ('>', ' ', '\t')
+
+RE_NESTED_FENCE_START = re.compile(
+ r'''(?x)
+ (?P~{3,}|`{3,})[ \t]* # Fence opening
+ (\{? # Language opening
+ \.?(?P[\w#.+-]*))?[ \t]* # Language
+ (?:
+ (hl_lines=(?P"|')(?P\d+(?:[ \t]+\d+)*)(?P=quot))?[ \t]*| # highlight lines
+ (linenums=(?P"|') # Line numbers
+ (?P[\d]+) # Line number start
+ (?:[ \t]+(?P[\d]+))? # Line step
+ (?:[ \t]+(?P[\d]+))? # Line special
+ (?P=quot2))?[ \t]*
+ ){,2}
+ }?[ \t]*$ # Language closing
+ '''
+)
+
+NESTED_FENCE_END = r'%s[ \t]*$'
+
+
+def _escape(txt):
+ """Basic html escaping."""
+
+ txt = txt.replace('&', '&')
+ txt = txt.replace('<', '<')
+ txt = txt.replace('>', '>')
+ txt = txt.replace('"', '"')
+ return txt
+
+
+class CodeStash(object):
+ """
+ Stash code for later retrieval.
+
+ Store original fenced code here in case we were
+ too greedy and need to restore in an indented code
+ block.
+ """
+
+ def __init__(self):
+ """Initialize."""
+
+ self.stash = {}
+
+ def __len__(self): # pragma: no cover
+ """Length of stash."""
+
+ return len(self.stash)
+
+ def get(self, key, default=None):
+ """Get the code from the key."""
+
+ code = self.stash.get(key, default)
+ return code
+
+ def remove(self, key):
+ """Remove the stashed code."""
+
+ del self.stash[key]
+
+ def store(self, key, code, indent_level):
+ """Store the code in the stash."""
+
+ self.stash[key] = (code, indent_level)
+
+ def clear_stash(self):
+ """Clear the stash."""
+
+ self.stash = {}
+
+
+def fence_code_format(source, language, css_class):
+ """Format source as code blocks."""
+
+ return '
' % (css_class, _escape(source))
+
+
+class SuperFencesCodeExtension(Extension):
+ """SuperFences code block extension."""
+
+ def __init__(self, *args, **kwargs):
+ """Initialize."""
+
+ self.superfences = []
+ self.config = {
+ 'disable_indented_code_blocks': [False, "Disable indented code blocks - Default: False"],
+ 'custom_fences': [
+ [
+ {'name': 'flow', 'class': 'uml-flowchart'},
+ {'name': 'sequence', 'class': 'uml-sequence-diagram'}
+ ],
+ 'Specify custom fences. Default: See documentation.'
+ ],
+ 'highlight_code': [True, "Highlight code - Default: True"],
+ 'css_class': [
+ '',
+ "Set class name for wrapper element. The default of CodeHilite or Highlight will be used"
+ "if nothing is set. - "
+ "Default: ''"
+ ],
+ 'preserve_tabs': [False, "Preserve tabs in fences - Default: False"]
+ }
+ super(SuperFencesCodeExtension, self).__init__(*args, **kwargs)
+
+ def extend_super_fences(self, name, formatter):
+ """Extend SuperFences with the given name, language, and formatter."""
+
+ self.superfences.append(
+ {
+ "name": name,
+ "test": lambda l, language=name: language == l,
+ "formatter": formatter
+ }
+ )
+
+ def extendMarkdown(self, md, md_globals):
+ """Add fenced block preprocessor to the Markdown instance."""
+
+ # Not super yet, so let's make it super
+ md.registerExtension(self)
+ config = self.getConfigs()
+
+ # Default fenced blocks
+ self.superfences.insert(
+ 0,
+ {
+ "name": "superfences",
+ "test": lambda language: True,
+ "formatter": None
+ }
+ )
+
+ # UML blocks
+ custom_fences = config.get('custom_fences', [])
+ for custom in custom_fences:
+ name = custom.get('name')
+ class_name = custom.get('class')
+ fence_format = custom.get('format', fence_code_format)
+ if name is not None and class_name is not None:
+ self.extend_super_fences(
+ name,
+ lambda s, l, c=class_name, f=fence_format: f(s, l, c)
+ )
+
+ self.markdown = md
+ self.patch_fenced_rule()
+ for entry in self.superfences:
+ entry["stash"] = CodeStash()
+
+ def patch_fenced_rule(self):
+ """
+ Patch Python Markdown with our own fenced block extension.
+
+ We don't attempt to protect against a user loading the `fenced_code` extension with this.
+ Most likely they will have issues, but they shouldn't have loaded them together in the first place :).
+ """
+
+ config = self.getConfigs()
+ fenced = SuperFencesBlockPreprocessor(self.markdown)
+ indented_code = SuperFencesCodeBlockProcessor(self)
+ fenced.config = config
+ fenced.extension = self
+ indented_code.config = config
+ indented_code.markdown = self.markdown
+ indented_code.extension = self
+ self.superfences[0]["formatter"] = fenced.highlight
+ self.markdown.parser.blockprocessors['code'] = indented_code
+ if config["preserve_tabs"]:
+ self.markdown.preprocessors.add('fenced_code_block', fenced, "normalize_whitespace")
+ else:
+ self.markdown.preprocessors.add('fenced_code_block', fenced, ">normalize_whitespace")
+
+ def reset(self):
+ """Clear the stash."""
+
+ for entry in self.superfences:
+ entry["stash"].clear_stash()
+
+
+class SuperFencesBlockPostNormalizePreprocessor(Preprocessor):
+ """Preprocessor to clean up normalization bypass hack."""
+
+ TEMP_PLACEHOLDER_RE = re.compile(
+ r'^([\> ]*)%s(%s)%s$' % (
+ SOH,
+ md_util.HTML_PLACEHOLDER[1:-1] % r'([0-9]+)',
+ EOT
+ )
+ )
+
+ def run(self, lines):
+ """Search for fenced blocks."""
+
+ new_lines = []
+ for line in lines:
+ line = self.TEMP_PLACEHOLDER_RE.sub(r'\1' + md_util.STX + r'\2' + md_util.ETX, line)
+ new_lines.append(line)
+
+ return new_lines
+
+
+class SuperFencesBlockPreprocessor(Preprocessor):
+ """
+ Preprocessor to find fenced code blocks.
+
+ Because this is done as a preprocessor, it might be too greedy.
+ We will stash the blocks code and restore if we mistakenly processed
+ text from an indented code block.
+ """
+
+ CODE_WRAP = '
%s
'
+
+ def __init__(self, md):
+ """Initialize."""
+
+ super(SuperFencesBlockPreprocessor, self).__init__(md)
+ self.markdown = md
+ self.tab_len = self.markdown.tab_length
+ self.checked_hl_settings = False
+ self.codehilite_conf = {}
+
+ def normalize_ws(self, text):
+ """Normalize whitespace."""
+
+ return text.expandtabs(self.tab_len)
+
+ def rebuild_block(self, lines):
+ """Dedent the fenced block lines."""
+
+ return '\n'.join([line[self.ws_virtual_len:] for line in lines])
+
+ def get_hl_settings(self):
+ """Check for CodeHilite extension to get its config."""
+
+ if not self.checked_hl_settings:
+ self.checked_hl_settings = True
+ self.highlight_code = self.config['highlight_code']
+
+ config = hl.get_hl_settings(self.markdown)
+ css_class = self.config['css_class']
+ self.css_class = css_class if css_class else config['css_class']
+
+ self.extend_pygments_lang = config.get('extend_pygments_lang', None)
+ self.guess_lang = config['guess_lang']
+ self.pygments_style = config['pygments_style']
+ self.use_pygments = config['use_pygments']
+ self.noclasses = config['noclasses']
+ self.linenums = config['linenums']
+
+ def clear(self):
+ """Reset the class variables."""
+
+ self.ws = None
+ self.ws_len = 0
+ self.ws_virtual_len = 0
+ self.fence = None
+ self.lang = None
+ self.hl_lines = None
+ self.linestart = None
+ self.linestep = None
+ self.linespecial = None
+ self.quote_level = 0
+ self.code = []
+ self.empty_lines = 0
+ self.fence_end = None
+
+ def eval_fence(self, ws, content, start, end):
+ """Evaluate a normal fence."""
+
+ if (ws + content).strip() == '':
+ # Empty line is okay
+ self.empty_lines += 1
+ self.code.append(ws + content)
+ elif len(ws) != self.ws_virtual_len and content != '':
+ # Not indented enough
+ self.clear()
+ elif self.fence_end.match(content) is not None and not content.startswith((' ', '\t')):
+ # End of fence
+ self.process_nested_block(ws, content, start, end)
+ else:
+ # Content line
+ self.empty_lines = 0
+ self.code.append(ws + content)
+
+ def eval_quoted(self, ws, content, quote_level, start, end):
+ """Evaluate fence inside a blockquote."""
+
+ if quote_level > self.quote_level:
+ # Quote level exceeds the starting quote level
+ self.clear()
+ elif quote_level <= self.quote_level:
+ if content == '':
+ # Empty line is okay
+ self.code.append(ws + content)
+ self.empty_lines += 1
+ elif len(ws) < self.ws_len:
+ # Not indented enough
+ self.clear()
+ elif self.empty_lines and quote_level < self.quote_level:
+ # Quote levels don't match and we are signified
+ # the end of the block with an empty line
+ self.clear()
+ elif self.fence_end.match(content) is not None:
+ # End of fence
+ self.process_nested_block(ws, content, start, end)
+ else:
+ # Content line
+ self.empty_lines = 0
+ self.code.append(ws + content)
+
+ def process_nested_block(self, ws, content, start, end):
+ """Process the contents of the nested block."""
+
+ self.last = ws + self.normalize_ws(content)
+ code = None
+ for entry in reversed(self.extension.superfences):
+ if entry["test"](self.lang):
+ code = entry["formatter"](self.rebuild_block(self.code), self.lang)
+ break
+
+ if code is not None:
+ self._store(self.normalize_ws('\n'.join(self.code)) + '\n', code, start, end, entry)
+ self.clear()
+
+ def parse_hl_lines(self, hl_lines):
+ """Parse the lines to highlight."""
+
+ return list(map(int, hl_lines.strip().split())) if hl_lines else []
+
+ def parse_line_start(self, linestart):
+ """Parse line start."""
+
+ return int(linestart) if linestart else -1
+
+ def parse_line_step(self, linestep):
+ """Parse line start."""
+
+ step = int(linestep) if linestep else -1
+
+ return step if step > 1 else -1
+
+ def parse_line_special(self, linespecial):
+ """Parse line start."""
+
+ return int(linespecial) if linespecial else -1
+
+ def parse_fence_line(self, line):
+ """Parse fence line."""
+
+ ws_len = 0
+ ws_virtual_len = 0
+ ws = []
+ index = 0
+ for c in line:
+ if ws_virtual_len >= self.ws_virtual_len:
+ break
+ if c not in PREFIX_CHARS:
+ break
+ ws_len += 1
+ if c == '\t':
+ tab_size = self.tab_len - (index % self.tab_len)
+ ws_virtual_len += tab_size
+ ws.append(' ' * tab_size)
+ else:
+ tab_size = 1
+ ws_virtual_len += 1
+ ws.append(c)
+ index += tab_size
+
+ return ''.join(ws), line[ws_len:]
+
+ def parse_whitespace(self, line):
+ """Parse the whitespace (blockquote syntax is counted as well)."""
+
+ self.ws_len = 0
+ self.ws_virtual_len = 0
+ ws = []
+ for c in line:
+ if c not in PREFIX_CHARS:
+ break
+ self.ws_len += 1
+ ws.append(c)
+
+ ws = self.normalize_ws(''.join(ws))
+ self.ws_virtual_len = len(ws)
+
+ return ws
+
+ def search_nested(self, lines):
+ """Search for nested fenced blocks."""
+
+ count = 0
+ for line in lines:
+ if self.fence is None:
+ ws = self.parse_whitespace(line)
+
+ # Found the start of a fenced block.
+ m = RE_NESTED_FENCE_START.match(line, self.ws_len)
+ if m is not None:
+ start = count
+ self.first = ws + self.normalize_ws(m.group(0))
+ self.ws = ws
+ self.quote_level = self.ws.count(">")
+ self.empty_lines = 0
+ self.fence = m.group('fence')
+ self.lang = m.group('lang')
+ self.hl_lines = m.group('hl_lines')
+ self.linestart = m.group('linestart')
+ self.linestep = m.group('linestep')
+ self.linespecial = m.group('linespecial')
+ self.fence_end = re.compile(NESTED_FENCE_END % self.fence)
+ else:
+ # Evaluate lines
+ # - Determine if it is the ending line or content line
+ # - If is a content line, make sure it is all indentend
+ # with the opening and closing lines (lines with just
+ # whitespace will be stripped so those don't matter).
+ # - When content lines are inside blockquotes, make sure
+ # the nested block quote levels make sense according to
+ # blockquote rules.
+ ws, content = self.parse_fence_line(line)
+
+ end = count + 1
+ quote_level = ws.count(">")
+
+ if self.quote_level:
+ # Handle blockquotes
+ self.eval_quoted(ws, content, quote_level, start, end)
+ elif quote_level == 0:
+ # Handle all other cases
+ self.eval_fence(ws, content, start, end)
+ else:
+ # Looks like we got a blockquote line
+ # when not in a blockquote.
+ self.clear()
+
+ count += 1
+
+ # Now that we are done iterating the lines,
+ # let's replace the original content with the
+ # fenced blocks.
+ while len(self.stack):
+ fenced, start, end = self.stack.pop()
+ if self.preserve_tabs:
+ lines = lines[:start] + [fenced.replace(md_util.STX, SOH, 1)[:-1] + EOT] + lines[end:]
+ else:
+ lines = lines[:start] + [fenced] + lines[end:]
+ return lines
+
+ def highlight(self, src, language):
+ """
+ Syntax highlight the code block.
+
+ If config is not empty, then the CodeHilite extension
+ is enabled, so we call into it to highlight the code.
+ """
+
+ if self.highlight_code:
+ linestep = self.parse_line_step(self.linestep)
+ linestart = self.parse_line_start(self.linestart)
+ linespecial = self.parse_line_special(self.linespecial)
+ hl_lines = self.parse_hl_lines(self.hl_lines)
+
+ el = hl.Highlight(
+ guess_lang=self.guess_lang,
+ pygments_style=self.pygments_style,
+ use_pygments=self.use_pygments,
+ noclasses=self.noclasses,
+ linenums=self.linenums,
+ extend_pygments_lang=self.extend_pygments_lang
+ ).highlight(
+ src,
+ language,
+ self.css_class,
+ hl_lines=hl_lines,
+ linestart=linestart,
+ linestep=linestep,
+ linespecial=linespecial
+ )
+ else:
+ # Format as a code block.
+ el = self.CODE_WRAP % ('', '', _escape(src))
+ return el
+
+ def _store(self, source, code, start, end, obj):
+ """
+ Store the fenced blocks in the stack to be replaced when done iterating.
+
+ Store the original text in case we need to restore if we are too greedy.
+ """
+ # Save the fenced blocks to add once we are done iterating the lines
+ placeholder = self.markdown.htmlStash.store(code, safe=True)
+ self.stack.append(('%s%s' % (self.ws, placeholder), start, end))
+ if not self.disabled_indented:
+ # If an indented block consumes this placeholder,
+ # we can restore the original source
+ obj["stash"].store(
+ placeholder[1:-1],
+ "%s\n%s%s" % (self.first, self.normalize_ws(source), self.last),
+ self.ws_virtual_len
+ )
+
+ def run(self, lines):
+ """Search for fenced blocks."""
+
+ self.get_hl_settings()
+ self.clear()
+ self.stack = []
+ self.disabled_indented = self.config.get("disable_indented_code_blocks", False)
+ self.preserve_tabs = self.config.get("preserve_tabs", False)
+
+ lines = self.search_nested(lines)
+
+ return lines
+
+
+class SuperFencesCodeBlockProcessor(CodeBlockProcessor):
+ """Process indented code blocks to see if we accidentally processed its content as a fenced block."""
+
+ FENCED_BLOCK_RE = re.compile(
+ r'^([\> ]*)%s(%s)%s$' % (
+ md_util.HTML_PLACEHOLDER[0],
+ md_util.HTML_PLACEHOLDER[1:-1] % r'([0-9]+)',
+ md_util.HTML_PLACEHOLDER[-1]
+ )
+ )
+
+ def test(self, parent, block):
+ """Test method that is one day to be deprecated."""
+
+ return True
+
+ def reindent(self, text, pos, level):
+ """Reindent the code to where it is supposed to be."""
+
+ indented = []
+ for line in text.split('\n'):
+ index = pos - level
+ indented.append(line[index:])
+ return '\n'.join(indented)
+
+ def revert_greedy_fences(self, block):
+ """Revert a prematurely converted fenced block."""
+
+ new_block = []
+ for line in block.split('\n'):
+ m = self.FENCED_BLOCK_RE.match(line)
+ if m:
+ key = m.group(2)
+ indent_level = len(m.group(1))
+ original = None
+ for entry in self.extension.superfences:
+ stash = entry["stash"]
+ original, pos = stash.get(key)
+ if original is not None:
+ code = self.reindent(original, pos, indent_level)
+ new_block.append(code)
+ stash.remove(key)
+ break
+ if original is None: # pragma: no cover
+ # Too much work to test this. This is just a fall back in case
+ # we find a placeholder, and we went to revert it and it wasn't in our stash.
+ # Most likely this would be caused by someone else. We just want to put it
+ # back in the block if we can't revert it. Maybe we can do a more directed
+ # unit test in the future.
+ new_block.append(line)
+ else:
+ new_block.append(line)
+ return '\n'.join(new_block)
+
+ def run(self, parent, blocks):
+ """Look for and parse code block."""
+
+ handled = False
+
+ if not self.config.get("disable_indented_code_blocks", False):
+ handled = CodeBlockProcessor.test(self, parent, blocks[0])
+ if handled:
+ if self.config.get("nested", True):
+ blocks[0] = self.revert_greedy_fences(blocks[0])
+ handled = CodeBlockProcessor.run(self, parent, blocks) is not False
+ return handled
+
+
+def makeExtension(*args, **kwargs):
+ """Return extension."""
+
+ return SuperFencesCodeExtension(*args, **kwargs)
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/png.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/png.py
new file mode 100644
index 0000000..a2f144e
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/png.py
@@ -0,0 +1,3801 @@
+#!/usr/bin/env python
+
+# $URL$
+# $Rev$
+
+# png.py - PNG encoder/decoder in pure Python
+#
+# Copyright (C) 2006 Johann C. Rocholl
+# Portions Copyright (C) 2009 David Jones
+# And probably portions Copyright (C) 2006 Nicko van Someren
+#
+# Original concept by Johann C. Rocholl.
+#
+# LICENSE (The MIT License)
+#
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation files
+# (the "Software"), to deal in the Software without restriction,
+# including without limitation the rights to use, copy, modify, merge,
+# publish, distribute, sublicense, and/or sell copies of the Software,
+# and to permit persons to whom the Software is furnished to do so,
+# subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+#
+# Changelog (recent first):
+# 2009-03-11 David: interlaced bit depth < 8 (writing).
+# 2009-03-10 David: interlaced bit depth < 8 (reading).
+# 2009-03-04 David: Flat and Boxed pixel formats.
+# 2009-02-26 David: Palette support (writing).
+# 2009-02-23 David: Bit-depths < 8; better PNM support.
+# 2006-06-17 Nicko: Reworked into a class, faster interlacing.
+# 2006-06-17 Johann: Very simple prototype PNG decoder.
+# 2006-06-17 Nicko: Test suite with various image generators.
+# 2006-06-17 Nicko: Alpha-channel, grey-scale, 16-bit/plane support.
+# 2006-06-15 Johann: Scanline iterator interface for large input files.
+# 2006-06-09 Johann: Very simple prototype PNG encoder.
+
+# Incorporated into Bangai-O Development Tools by drj on 2009-02-11 from
+# http://trac.browsershots.org/browser/trunk/pypng/lib/png.py?rev=2885
+
+# Incorporated into pypng by drj on 2009-03-12 from
+# //depot/prj/bangaio/master/code/png.py#67
+
+
+"""
+Pure Python PNG Reader/Writer
+
+This Python module implements support for PNG images (see PNG
+specification at http://www.w3.org/TR/2003/REC-PNG-20031110/ ). It reads
+and writes PNG files with all allowable bit depths (1/2/4/8/16/24/32/48/64
+bits per pixel) and colour combinations: greyscale (1/2/4/8/16 bit); RGB,
+RGBA, LA (greyscale with alpha) with 8/16 bits per channel; colour mapped
+images (1/2/4/8 bit). Adam7 interlacing is supported for reading and
+writing. A number of optional chunks can be specified (when writing)
+and understood (when reading): ``tRNS``, ``bKGD``, ``gAMA``.
+
+For help, type ``import png; help(png)`` in your python interpreter.
+
+A good place to start is the :class:`Reader` and :class:`Writer` classes.
+
+Requires Python 2.3. Limited support is available for Python 2.2, but
+not everything works. Best with Python 2.4 and higher. Installation is
+trivial, but see the ``README.txt`` file (with the source distribution)
+for details.
+
+This file can also be used as a command-line utility to convert
+`Netpbm `_ PNM files to PNG, and the reverse conversion from PNG to
+PNM. The interface is similar to that of the ``pnmtopng`` program from
+Netpbm. Type ``python png.py --help`` at the shell prompt
+for usage and a list of options.
+
+A note on spelling and terminology
+----------------------------------
+
+Generally British English spelling is used in the documentation. So
+that's "greyscale" and "colour". This not only matches the author's
+native language, it's also used by the PNG specification.
+
+The major colour models supported by PNG (and hence by PyPNG) are:
+greyscale, RGB, greyscale--alpha, RGB--alpha. These are sometimes
+referred to using the abbreviations: L, RGB, LA, RGBA. In this case
+each letter abbreviates a single channel: *L* is for Luminance or Luma or
+Lightness which is the channel used in greyscale images; *R*, *G*, *B* stand
+for Red, Green, Blue, the components of a colour image; *A* stands for
+Alpha, the opacity channel (used for transparency effects, but higher
+values are more opaque, so it makes sense to call it opacity).
+
+A note on formats
+-----------------
+
+When getting pixel data out of this module (reading) and presenting
+data to this module (writing) there are a number of ways the data could
+be represented as a Python value. Generally this module uses one of
+three formats called "flat row flat pixel", "boxed row flat pixel", and
+"boxed row boxed pixel". Basically the concern is whether each pixel
+and each row comes in its own little tuple (box), or not.
+
+Consider an image that is 3 pixels wide by 2 pixels high, and each pixel
+has RGB components:
+
+Boxed row flat pixel::
+
+ list([R,G,B, R,G,B, R,G,B],
+ [R,G,B, R,G,B, R,G,B])
+
+Each row appears as its own list, but the pixels are flattened so that
+three values for one pixel simply follow the three values for the previous
+pixel. This is the most common format used, because it provides a good
+compromise between space and convenience. PyPNG regards itself as
+at liberty to replace any sequence type with any sufficiently compatible
+other sequence type; in practice each row is an array (from the array
+module), and the outer list is sometimes an iterator rather than an
+explicit list (so that streaming is possible).
+
+Flat row flat pixel::
+
+ [R,G,B, R,G,B, R,G,B,
+ R,G,B, R,G,B, R,G,B]
+
+The entire image is one single giant sequence of colour values.
+Generally an array will be used (to save space), not a list.
+
+Boxed row boxed pixel::
+
+ list([ (R,G,B), (R,G,B), (R,G,B) ],
+ [ (R,G,B), (R,G,B), (R,G,B) ])
+
+Each row appears in its own list, but each pixel also appears in its own
+tuple. A serious memory burn in Python.
+
+In all cases the top row comes first, and for each row the pixels are
+ordered from left-to-right. Within a pixel the values appear in the
+order, R-G-B-A (or L-A for greyscale--alpha).
+
+There is a fourth format, mentioned because it is used internally,
+is close to what lies inside a PNG file itself, and has some support
+from the public API. This format is called packed. When packed,
+each row is a sequence of bytes (integers from 0 to 255), just as
+it is before PNG scanline filtering is applied. When the bit depth
+is 8 this is essentially the same as boxed row flat pixel; when the
+bit depth is less than 8, several pixels are packed into each byte;
+when the bit depth is 16 (the only value more than 8 that is supported
+by the PNG image format) each pixel value is decomposed into 2 bytes
+(and `packed` is a misnomer). This format is used by the
+:meth:`Writer.write_packed` method. It isn't usually a convenient
+format, but may be just right if the source data for the PNG image
+comes from something that uses a similar format (for example, 1-bit
+BMPs, or another PNG file).
+
+And now, my famous members
+--------------------------
+"""
+
+# http://www.python.org/doc/2.2.3/whatsnew/node5.html
+
+
+__version__ = "$URL$ $Rev$"
+
+from array import array
+from functools import reduce
+try: # See :pyver:old
+ import itertools
+except:
+ pass
+import math
+# http://www.python.org/doc/2.4.4/lib/module-operator.html
+import operator
+import struct
+import sys
+import zlib
+# http://www.python.org/doc/2.4.4/lib/module-warnings.html
+import warnings
+
+
+__all__ = ['Image', 'Reader', 'Writer', 'write_chunks', 'from_array']
+
+
+# The PNG signature.
+# http://www.w3.org/TR/PNG/#5PNG-file-signature
+_signature = struct.pack('8B', 137, 80, 78, 71, 13, 10, 26, 10)
+
+_adam7 = ((0, 0, 8, 8),
+ (4, 0, 8, 8),
+ (0, 4, 4, 8),
+ (2, 0, 4, 4),
+ (0, 2, 2, 4),
+ (1, 0, 2, 2),
+ (0, 1, 1, 2))
+
+def group(s, n):
+ # See
+ # http://www.python.org/doc/2.6/library/functions.html#zip
+ return list(zip(*[iter(s)]*n))
+
+def isarray(x):
+ """Same as ``isinstance(x, array)`` except on Python 2.2, where it
+ always returns ``False``. This helps PyPNG work on Python 2.2.
+ """
+
+ try:
+ return isinstance(x, array)
+ except:
+ return False
+
+try: # see :pyver:old
+ array.tostring
+except:
+ def tostring(row):
+ l = len(row)
+ return struct.pack('%dB' % l, *row)
+else:
+ def tostring(row):
+ """Convert row of bytes to string. Expects `row` to be an
+ ``array``.
+ """
+ return row.tostring()
+
+# Conditionally convert to bytes. Works on Python 2 and Python 3.
+try:
+ bytes('', 'ascii')
+ def strtobytes(x): return bytes(x, 'iso8859-1')
+ def bytestostr(x): return str(x, 'iso8859-1')
+except:
+ strtobytes = str
+ bytestostr = str
+
+def interleave_planes(ipixels, apixels, ipsize, apsize):
+ """
+ Interleave (colour) planes, e.g. RGB + A = RGBA.
+
+ Return an array of pixels consisting of the `ipsize` elements of data
+ from each pixel in `ipixels` followed by the `apsize` elements of data
+ from each pixel in `apixels`. Conventionally `ipixels` and
+ `apixels` are byte arrays so the sizes are bytes, but it actually
+ works with any arrays of the same type. The returned array is the
+ same type as the input arrays which should be the same type as each other.
+ """
+
+ itotal = len(ipixels)
+ atotal = len(apixels)
+ newtotal = itotal + atotal
+ newpsize = ipsize + apsize
+ # Set up the output buffer
+ # See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356
+ out = array(ipixels.typecode)
+ # It's annoying that there is no cheap way to set the array size :-(
+ out.extend(ipixels)
+ out.extend(apixels)
+ # Interleave in the pixel data
+ for i in range(ipsize):
+ out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize]
+ for i in range(apsize):
+ out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize]
+ return out
+
+def check_palette(palette):
+ """Check a palette argument (to the :class:`Writer` class) for validity.
+ Returns the palette as a list if okay; raises an exception otherwise.
+ """
+
+ # None is the default and is allowed.
+ if palette is None:
+ return None
+
+ p = list(palette)
+ if not (0 < len(p) <= 256):
+ raise ValueError("a palette must have between 1 and 256 entries")
+ seen_triple = False
+ for i,t in enumerate(p):
+ if len(t) not in (3,4):
+ raise ValueError(
+ "palette entry %d: entries must be 3- or 4-tuples." % i)
+ if len(t) == 3:
+ seen_triple = True
+ if seen_triple and len(t) == 4:
+ raise ValueError(
+ "palette entry %d: all 4-tuples must precede all 3-tuples" % i)
+ for x in t:
+ if int(x) != x or not(0 <= x <= 255):
+ raise ValueError(
+ "palette entry %d: values must be integer: 0 <= x <= 255" % i)
+ return p
+
+class Error(Exception):
+ prefix = 'Error'
+ def __str__(self):
+ return self.prefix + ': ' + ' '.join(self.args)
+
+class FormatError(Error):
+ """Problem with input file format. In other words, PNG file does
+ not conform to the specification in some way and is invalid.
+ """
+
+ prefix = 'FormatError'
+
+class ChunkError(FormatError):
+ prefix = 'ChunkError'
+
+
+class Writer:
+ """
+ PNG encoder in pure Python.
+ """
+
+ def __init__(self, width=None, height=None,
+ size=None,
+ greyscale=False,
+ alpha=False,
+ bitdepth=8,
+ palette=None,
+ transparent=None,
+ background=None,
+ gamma=None,
+ compression=None,
+ interlace=False,
+ bytes_per_sample=None, # deprecated
+ planes=None,
+ colormap=None,
+ maxval=None,
+ chunk_limit=2**20):
+ """
+ Create a PNG encoder object.
+
+ Arguments:
+
+ width, height
+ Image size in pixels, as two separate arguments.
+ size
+ Image size (w,h) in pixels, as single argument.
+ greyscale
+ Input data is greyscale, not RGB.
+ alpha
+ Input data has alpha channel (RGBA or LA).
+ bitdepth
+ Bit depth: from 1 to 16.
+ palette
+ Create a palette for a colour mapped image (colour type 3).
+ transparent
+ Specify a transparent colour (create a ``tRNS`` chunk).
+ background
+ Specify a default background colour (create a ``bKGD`` chunk).
+ gamma
+ Specify a gamma value (create a ``gAMA`` chunk).
+ compression
+ zlib compression level (1-9).
+ interlace
+ Create an interlaced image.
+ chunk_limit
+ Write multiple ``IDAT`` chunks to save memory.
+
+ The image size (in pixels) can be specified either by using the
+ `width` and `height` arguments, or with the single `size`
+ argument. If `size` is used it should be a pair (*width*,
+ *height*).
+
+ `greyscale` and `alpha` are booleans that specify whether
+ an image is greyscale (or colour), and whether it has an
+ alpha channel (or not).
+
+ `bitdepth` specifies the bit depth of the source pixel values.
+ Each source pixel value must be an integer between 0 and
+ ``2**bitdepth-1``. For example, 8-bit images have values
+ between 0 and 255. PNG only stores images with bit depths of
+ 1,2,4,8, or 16. When `bitdepth` is not one of these values,
+ the next highest valid bit depth is selected, and an ``sBIT``
+ (significant bits) chunk is generated that specifies the original
+ precision of the source image. In this case the supplied pixel
+ values will be rescaled to fit the range of the selected bit depth.
+
+ The details of which bit depth / colour model combinations the
+ PNG file format supports directly, are somewhat arcane
+ (refer to the PNG specification for full details). Briefly:
+ "small" bit depths (1,2,4) are only allowed with greyscale and
+ colour mapped images; colour mapped images cannot have bit depth
+ 16.
+
+ For colour mapped images (in other words, when the `palette`
+ argument is specified) the `bitdepth` argument must match one of
+ the valid PNG bit depths: 1, 2, 4, or 8. (It is valid to have a
+ PNG image with a palette and an ``sBIT`` chunk, but the meaning
+ is slightly different; it would be awkward to press the
+ `bitdepth` argument into service for this.)
+
+ The `palette` option, when specified, causes a colour mapped image
+ to be created: the PNG colour type is set to 3; greyscale
+ must not be set; alpha must not be set; transparent must
+ not be set; the bit depth must be 1,2,4, or 8. When a colour
+ mapped image is created, the pixel values are palette indexes
+ and the `bitdepth` argument specifies the size of these indexes
+ (not the size of the colour values in the palette).
+
+ The palette argument value should be a sequence of 3- or
+ 4-tuples. 3-tuples specify RGB palette entries; 4-tuples
+ specify RGBA palette entries. If both 4-tuples and 3-tuples
+ appear in the sequence then all the 4-tuples must come
+ before all the 3-tuples. A ``PLTE`` chunk is created; if there
+ are 4-tuples then a ``tRNS`` chunk is created as well. The
+ ``PLTE`` chunk will contain all the RGB triples in the same
+ sequence; the ``tRNS`` chunk will contain the alpha channel for
+ all the 4-tuples, in the same sequence. Palette entries
+ are always 8-bit.
+
+ If specified, the `transparent` and `background` parameters must
+ be a tuple with three integer values for red, green, blue, or
+ a simple integer (or singleton tuple) for a greyscale image.
+
+ If specified, the `gamma` parameter must be a positive number
+ (generally, a float). A ``gAMA`` chunk will be created. Note that
+ this will not change the values of the pixels as they appear in
+ the PNG file, they are assumed to have already been converted
+ appropriately for the gamma specified.
+
+ The `compression` argument specifies the compression level
+ to be used by the ``zlib`` module. Higher values are likely
+ to compress better, but will be slower to compress. The
+ default for this argument is ``None``; this does not mean
+ no compression, rather it means that the default from the
+ ``zlib`` module is used (which is generally acceptable).
+
+ If `interlace` is true then an interlaced image is created
+ (using PNG's so far only interace method, *Adam7*). This does not
+ affect how the pixels should be presented to the encoder, rather
+ it changes how they are arranged into the PNG file. On slow
+ connexions interlaced images can be partially decoded by the
+ browser to give a rough view of the image that is successively
+ refined as more image data appears.
+
+ .. note ::
+
+ Enabling the `interlace` option requires the entire image
+ to be processed in working memory.
+
+ `chunk_limit` is used to limit the amount of memory used whilst
+ compressing the image. In order to avoid using large amounts of
+ memory, multiple ``IDAT`` chunks may be created.
+ """
+
+ # At the moment the `planes` argument is ignored;
+ # its purpose is to act as a dummy so that
+ # ``Writer(x, y, **info)`` works, where `info` is a dictionary
+ # returned by Reader.read and friends.
+ # Ditto for `colormap`.
+
+ # A couple of helper functions come first. Best skipped if you
+ # are reading through.
+
+ def isinteger(x):
+ try:
+ return int(x) == x
+ except:
+ return False
+
+ def check_color(c, which):
+ """Checks that a colour argument for transparent or
+ background options is the right form. Also "corrects" bare
+ integers to 1-tuples.
+ """
+
+ if c is None:
+ return c
+ if greyscale:
+ try:
+ l = len(c)
+ except TypeError:
+ c = (c,)
+ if len(c) != 1:
+ raise ValueError("%s for greyscale must be 1-tuple" %
+ which)
+ if not isinteger(c[0]):
+ raise ValueError(
+ "%s colour for greyscale must be integer" %
+ which)
+ else:
+ if not (len(c) == 3 and
+ isinteger(c[0]) and
+ isinteger(c[1]) and
+ isinteger(c[2])):
+ raise ValueError(
+ "%s colour must be a triple of integers" %
+ which)
+ return c
+
+ if size:
+ if len(size) != 2:
+ raise ValueError(
+ "size argument should be a pair (width, height)")
+ if width is not None and width != size[0]:
+ raise ValueError(
+ "size[0] (%r) and width (%r) should match when both are used."
+ % (size[0], width))
+ if height is not None and height != size[1]:
+ raise ValueError(
+ "size[1] (%r) and height (%r) should match when both are used."
+ % (size[1], height))
+ width,height = size
+ del size
+
+ if width <= 0 or height <= 0:
+ raise ValueError("width and height must be greater than zero")
+ if not isinteger(width) or not isinteger(height):
+ raise ValueError("width and height must be integers")
+ # http://www.w3.org/TR/PNG/#7Integers-and-byte-order
+ if width > 2**32-1 or height > 2**32-1:
+ raise ValueError("width and height cannot exceed 2**32-1")
+
+ if alpha and transparent is not None:
+ raise ValueError(
+ "transparent colour not allowed with alpha channel")
+
+ if bytes_per_sample is not None:
+ warnings.warn('please use bitdepth instead of bytes_per_sample',
+ DeprecationWarning)
+ if bytes_per_sample not in (0.125, 0.25, 0.5, 1, 2):
+ raise ValueError(
+ "bytes per sample must be .125, .25, .5, 1, or 2")
+ bitdepth = int(8*bytes_per_sample)
+ del bytes_per_sample
+ if not isinteger(bitdepth) or bitdepth < 1 or 16 < bitdepth:
+ raise ValueError("bitdepth (%r) must be a postive integer <= 16" %
+ bitdepth)
+
+ self.rescale = None
+ if palette:
+ if bitdepth not in (1,2,4,8):
+ raise ValueError("with palette, bitdepth must be 1, 2, 4, or 8")
+ if transparent is not None:
+ raise ValueError("transparent and palette not compatible")
+ if alpha:
+ raise ValueError("alpha and palette not compatible")
+ if greyscale:
+ raise ValueError("greyscale and palette not compatible")
+ else:
+ # No palette, check for sBIT chunk generation.
+ if alpha or not greyscale:
+ if bitdepth not in (8,16):
+ targetbitdepth = (8,16)[bitdepth > 8]
+ self.rescale = (bitdepth, targetbitdepth)
+ bitdepth = targetbitdepth
+ del targetbitdepth
+ else:
+ assert greyscale
+ assert not alpha
+ if bitdepth not in (1,2,4,8,16):
+ if bitdepth > 8:
+ targetbitdepth = 16
+ elif bitdepth == 3:
+ targetbitdepth = 4
+ else:
+ assert bitdepth in (5,6,7)
+ targetbitdepth = 8
+ self.rescale = (bitdepth, targetbitdepth)
+ bitdepth = targetbitdepth
+ del targetbitdepth
+
+ if bitdepth < 8 and (alpha or not greyscale and not palette):
+ raise ValueError(
+ "bitdepth < 8 only permitted with greyscale or palette")
+ if bitdepth > 8 and palette:
+ raise ValueError(
+ "bit depth must be 8 or less for images with palette")
+
+ transparent = check_color(transparent, 'transparent')
+ background = check_color(background, 'background')
+
+ # It's important that the true boolean values (greyscale, alpha,
+ # colormap, interlace) are converted to bool because Iverson's
+ # convention is relied upon later on.
+ self.width = width
+ self.height = height
+ self.transparent = transparent
+ self.background = background
+ self.gamma = gamma
+ self.greyscale = bool(greyscale)
+ self.alpha = bool(alpha)
+ self.colormap = bool(palette)
+ self.bitdepth = int(bitdepth)
+ self.compression = compression
+ self.chunk_limit = chunk_limit
+ self.interlace = bool(interlace)
+ self.palette = check_palette(palette)
+
+ self.color_type = 4*self.alpha + 2*(not greyscale) + 1*self.colormap
+ assert self.color_type in (0,2,3,4,6)
+
+ self.color_planes = (3,1)[self.greyscale or self.colormap]
+ self.planes = self.color_planes + self.alpha
+ # :todo: fix for bitdepth < 8
+ self.psize = (self.bitdepth/8) * self.planes
+
+ def make_palette(self):
+ """Create the byte sequences for a ``PLTE`` and if necessary a
+ ``tRNS`` chunk. Returned as a pair (*p*, *t*). *t* will be
+ ``None`` if no ``tRNS`` chunk is necessary.
+ """
+
+ p = array('B')
+ t = array('B')
+
+ for x in self.palette:
+ p.extend(x[0:3])
+ if len(x) > 3:
+ t.append(x[3])
+ p = tostring(p)
+ t = tostring(t)
+ if t:
+ return p,t
+ return p,None
+
+ def write(self, outfile, rows):
+ """Write a PNG image to the output file. `rows` should be
+ an iterable that yields each row in boxed row flat pixel format.
+ The rows should be the rows of the original image, so there
+ should be ``self.height`` rows of ``self.width * self.planes`` values.
+ If `interlace` is specified (when creating the instance), then
+ an interlaced PNG file will be written. Supply the rows in the
+ normal image order; the interlacing is carried out internally.
+
+ .. note ::
+
+ Interlacing will require the entire image to be in working memory.
+ """
+
+ if self.interlace:
+ fmt = 'BH'[self.bitdepth > 8]
+ a = array(fmt, itertools.chain(*rows))
+ return self.write_array(outfile, a)
+ else:
+ nrows = self.write_passes(outfile, rows)
+ if nrows != self.height:
+ raise ValueError(
+ "rows supplied (%d) does not match height (%d)" %
+ (nrows, self.height))
+
+ def write_passes(self, outfile, rows, packed=False):
+ """
+ Write a PNG image to the output file.
+
+ Most users are expected to find the :meth:`write` or
+ :meth:`write_array` method more convenient.
+
+ The rows should be given to this method in the order that
+ they appear in the output file. For straightlaced images,
+ this is the usual top to bottom ordering, but for interlaced
+ images the rows should have already been interlaced before
+ passing them to this function.
+
+ `rows` should be an iterable that yields each row. When
+ `packed` is ``False`` the rows should be in boxed row flat pixel
+ format; when `packed` is ``True`` each row should be a packed
+ sequence of bytes.
+
+ """
+
+ # http://www.w3.org/TR/PNG/#5PNG-file-signature
+ outfile.write(_signature)
+
+ # http://www.w3.org/TR/PNG/#11IHDR
+ write_chunk(outfile, 'IHDR',
+ struct.pack("!2I5B", self.width, self.height,
+ self.bitdepth, self.color_type,
+ 0, 0, self.interlace))
+
+ # See :chunk:order
+ # http://www.w3.org/TR/PNG/#11gAMA
+ if self.gamma is not None:
+ write_chunk(outfile, 'gAMA',
+ struct.pack("!L", int(round(self.gamma*1e5))))
+
+ # See :chunk:order
+ # http://www.w3.org/TR/PNG/#11sBIT
+ if self.rescale:
+ write_chunk(outfile, 'sBIT',
+ struct.pack('%dB' % self.planes,
+ *[self.rescale[0]]*self.planes))
+
+ # :chunk:order: Without a palette (PLTE chunk), ordering is
+ # relatively relaxed. With one, gAMA chunk must precede PLTE
+ # chunk which must precede tRNS and bKGD.
+ # See http://www.w3.org/TR/PNG/#5ChunkOrdering
+ if self.palette:
+ p,t = self.make_palette()
+ write_chunk(outfile, 'PLTE', p)
+ if t:
+ # tRNS chunk is optional. Only needed if palette entries
+ # have alpha.
+ write_chunk(outfile, 'tRNS', t)
+
+ # http://www.w3.org/TR/PNG/#11tRNS
+ if self.transparent is not None:
+ if self.greyscale:
+ write_chunk(outfile, 'tRNS',
+ struct.pack("!1H", *self.transparent))
+ else:
+ write_chunk(outfile, 'tRNS',
+ struct.pack("!3H", *self.transparent))
+
+ # http://www.w3.org/TR/PNG/#11bKGD
+ if self.background is not None:
+ if self.greyscale:
+ write_chunk(outfile, 'bKGD',
+ struct.pack("!1H", *self.background))
+ else:
+ write_chunk(outfile, 'bKGD',
+ struct.pack("!3H", *self.background))
+
+ # http://www.w3.org/TR/PNG/#11IDAT
+ if self.compression is not None:
+ compressor = zlib.compressobj(self.compression)
+ else:
+ compressor = zlib.compressobj()
+
+ # Choose an extend function based on the bitdepth. The extend
+ # function packs/decomposes the pixel values into bytes and
+ # stuffs them onto the data array.
+ data = array('B')
+ if self.bitdepth == 8 or packed:
+ extend = data.extend
+ elif self.bitdepth == 16:
+ # Decompose into bytes
+ def extend(sl):
+ fmt = '!%dH' % len(sl)
+ data.extend(array('B', struct.pack(fmt, *sl)))
+ else:
+ # Pack into bytes
+ assert self.bitdepth < 8
+ # samples per byte
+ spb = int(8/self.bitdepth)
+ def extend(sl):
+ a = array('B', sl)
+ # Adding padding bytes so we can group into a whole
+ # number of spb-tuples.
+ l = float(len(a))
+ extra = math.ceil(l / float(spb))*spb - l
+ a.extend([0]*int(extra))
+ # Pack into bytes
+ l = group(a, spb)
+ l = [reduce(lambda x,y:
+ (x << self.bitdepth) + y, e) for e in l]
+ data.extend(l)
+ if self.rescale:
+ oldextend = extend
+ factor = \
+ float(2**self.rescale[1]-1) / float(2**self.rescale[0]-1)
+ def extend(sl):
+ oldextend([int(round(factor*x)) for x in sl])
+
+ # Build the first row, testing mostly to see if we need to
+ # changed the extend function to cope with NumPy integer types
+ # (they cause our ordinary definition of extend to fail, so we
+ # wrap it). See
+ # http://code.google.com/p/pypng/issues/detail?id=44
+ enumrows = enumerate(rows)
+ del rows
+
+ # First row's filter type.
+ data.append(0)
+ # :todo: Certain exceptions in the call to ``.next()`` or the
+ # following try would indicate no row data supplied.
+ # Should catch.
+ i,row = next(enumrows)
+ try:
+ # If this fails...
+ extend(row)
+ except:
+ # ... try a version that converts the values to int first.
+ # Not only does this work for the (slightly broken) NumPy
+ # types, there are probably lots of other, unknown, "nearly"
+ # int types it works for.
+ def wrapmapint(f):
+ return lambda sl: f(list(map(int, sl)))
+ extend = wrapmapint(extend)
+ del wrapmapint
+ extend(row)
+
+ for i,row in enumrows:
+ # Add "None" filter type. Currently, it's essential that
+ # this filter type be used for every scanline as we do not
+ # mark the first row of a reduced pass image; that means we
+ # could accidentally compute the wrong filtered scanline if
+ # we used "up", "average", or "paeth" on such a line.
+ data.append(0)
+ extend(row)
+ if len(data) > self.chunk_limit:
+ compressed = compressor.compress(tostring(data))
+ if len(compressed):
+ # print >> sys.stderr, len(data), len(compressed)
+ write_chunk(outfile, 'IDAT', compressed)
+ # Because of our very witty definition of ``extend``,
+ # above, we must re-use the same ``data`` object. Hence
+ # we use ``del`` to empty this one, rather than create a
+ # fresh one (which would be my natural FP instinct).
+ del data[:]
+ if len(data):
+ compressed = compressor.compress(tostring(data))
+ else:
+ compressed = ''
+ flushed = compressor.flush()
+ if len(compressed) or len(flushed):
+ # print >> sys.stderr, len(data), len(compressed), len(flushed)
+ write_chunk(outfile, 'IDAT', compressed + flushed)
+ # http://www.w3.org/TR/PNG/#11IEND
+ write_chunk(outfile, 'IEND')
+ return i+1
+
+ def write_array(self, outfile, pixels):
+ """
+ Write an array in flat row flat pixel format as a PNG file on
+ the output file. See also :meth:`write` method.
+ """
+
+ if self.interlace:
+ self.write_passes(outfile, self.array_scanlines_interlace(pixels))
+ else:
+ self.write_passes(outfile, self.array_scanlines(pixels))
+
+ def write_packed(self, outfile, rows):
+ """
+ Write PNG file to `outfile`. The pixel data comes from `rows`
+ which should be in boxed row packed format. Each row should be
+ a sequence of packed bytes.
+
+ Technically, this method does work for interlaced images but it
+ is best avoided. For interlaced images, the rows should be
+ presented in the order that they appear in the file.
+
+ This method should not be used when the source image bit depth
+ is not one naturally supported by PNG; the bit depth should be
+ 1, 2, 4, 8, or 16.
+ """
+
+ if self.rescale:
+ raise Error("write_packed method not suitable for bit depth %d" %
+ self.rescale[0])
+ return self.write_passes(outfile, rows, packed=True)
+
+ def convert_pnm(self, infile, outfile):
+ """
+ Convert a PNM file containing raw pixel data into a PNG file
+ with the parameters set in the writer object. Works for
+ (binary) PGM, PPM, and PAM formats.
+ """
+
+ if self.interlace:
+ pixels = array('B')
+ pixels.fromfile(infile,
+ (self.bitdepth/8) * self.color_planes *
+ self.width * self.height)
+ self.write_passes(outfile, self.array_scanlines_interlace(pixels))
+ else:
+ self.write_passes(outfile, self.file_scanlines(infile))
+
+ def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile):
+ """
+ Convert a PPM and PGM file containing raw pixel data into a
+ PNG outfile with the parameters set in the writer object.
+ """
+ pixels = array('B')
+ pixels.fromfile(ppmfile,
+ (self.bitdepth/8) * self.color_planes *
+ self.width * self.height)
+ apixels = array('B')
+ apixels.fromfile(pgmfile,
+ (self.bitdepth/8) *
+ self.width * self.height)
+ pixels = interleave_planes(pixels, apixels,
+ (self.bitdepth/8) * self.color_planes,
+ (self.bitdepth/8))
+ if self.interlace:
+ self.write_passes(outfile, self.array_scanlines_interlace(pixels))
+ else:
+ self.write_passes(outfile, self.array_scanlines(pixels))
+
+ def file_scanlines(self, infile):
+ """
+ Generates boxed rows in flat pixel format, from the input file
+ `infile`. It assumes that the input file is in a "Netpbm-like"
+ binary format, and is positioned at the beginning of the first
+ pixel. The number of pixels to read is taken from the image
+ dimensions (`width`, `height`, `planes`) and the number of bytes
+ per value is implied by the image `bitdepth`.
+ """
+
+ # Values per row
+ vpr = self.width * self.planes
+ row_bytes = vpr
+ if self.bitdepth > 8:
+ assert self.bitdepth == 16
+ row_bytes *= 2
+ fmt = '>%dH' % vpr
+ def line():
+ return array('H', struct.unpack(fmt, infile.read(row_bytes)))
+ else:
+ def line():
+ scanline = array('B', infile.read(row_bytes))
+ return scanline
+ for y in range(self.height):
+ yield line()
+
+ def array_scanlines(self, pixels):
+ """
+ Generates boxed rows (flat pixels) from flat rows (flat pixels)
+ in an array.
+ """
+
+ # Values per row
+ vpr = self.width * self.planes
+ stop = 0
+ for y in range(self.height):
+ start = stop
+ stop = start + vpr
+ yield pixels[start:stop]
+
+ def array_scanlines_interlace(self, pixels):
+ """
+ Generator for interlaced scanlines from an array. `pixels` is
+ the full source image in flat row flat pixel format. The
+ generator yields each scanline of the reduced passes in turn, in
+ boxed row flat pixel format.
+ """
+
+ # http://www.w3.org/TR/PNG/#8InterlaceMethods
+ # Array type.
+ fmt = 'BH'[self.bitdepth > 8]
+ # Value per row
+ vpr = self.width * self.planes
+ for xstart, ystart, xstep, ystep in _adam7:
+ if xstart >= self.width:
+ continue
+ # Pixels per row (of reduced image)
+ ppr = int(math.ceil((self.width-xstart)/float(xstep)))
+ # number of values in reduced image row.
+ row_len = ppr*self.planes
+ for y in range(ystart, self.height, ystep):
+ if xstep == 1:
+ offset = y * vpr
+ yield pixels[offset:offset+vpr]
+ else:
+ row = array(fmt)
+ # There's no easier way to set the length of an array
+ row.extend(pixels[0:row_len])
+ offset = y * vpr + xstart * self.planes
+ end_offset = (y+1) * vpr
+ skip = self.planes * xstep
+ for i in range(self.planes):
+ row[i::self.planes] = \
+ pixels[offset+i:end_offset:skip]
+ yield row
+
+def write_chunk(outfile, tag, data=strtobytes('')):
+ """
+ Write a PNG chunk to the output file, including length and
+ checksum.
+ """
+
+ # http://www.w3.org/TR/PNG/#5Chunk-layout
+ outfile.write(struct.pack("!I", len(data)))
+ tag = strtobytes(tag)
+ outfile.write(tag)
+ outfile.write(data)
+ checksum = zlib.crc32(tag)
+ checksum = zlib.crc32(data, checksum)
+ checksum &= 2**32-1
+ outfile.write(struct.pack("!I", checksum))
+
+def write_chunks(out, chunks):
+ """Create a PNG file by writing out the chunks."""
+
+ out.write(_signature)
+ for chunk in chunks:
+ write_chunk(out, *chunk)
+
+def filter_scanline(type, line, fo, prev=None):
+ """Apply a scanline filter to a scanline. `type` specifies the
+ filter type (0 to 4); `line` specifies the current (unfiltered)
+ scanline as a sequence of bytes; `prev` specifies the previous
+ (unfiltered) scanline as a sequence of bytes. `fo` specifies the
+ filter offset; normally this is size of a pixel in bytes (the number
+ of bytes per sample times the number of channels), but when this is
+ < 1 (for bit depths < 8) then the filter offset is 1.
+ """
+
+ assert 0 <= type < 5
+
+ # The output array. Which, pathetically, we extend one-byte at a
+ # time (fortunately this is linear).
+ out = array('B', [type])
+
+ def sub():
+ ai = -fo
+ for x in line:
+ if ai >= 0:
+ x = (x - line[ai]) & 0xff
+ out.append(x)
+ ai += 1
+ def up():
+ for i,x in enumerate(line):
+ x = (x - prev[i]) & 0xff
+ out.append(x)
+ def average():
+ ai = -fo
+ for i,x in enumerate(line):
+ if ai >= 0:
+ x = (x - ((line[ai] + prev[i]) >> 1)) & 0xff
+ else:
+ x = (x - (prev[i] >> 1)) & 0xff
+ out.append(x)
+ ai += 1
+ def paeth():
+ # http://www.w3.org/TR/PNG/#9Filter-type-4-Paeth
+ ai = -fo # also used for ci
+ for i,x in enumerate(line):
+ a = 0
+ b = prev[i]
+ c = 0
+
+ if ai >= 0:
+ a = line[ai]
+ c = prev[ai]
+ p = a + b - c
+ pa = abs(p - a)
+ pb = abs(p - b)
+ pc = abs(p - c)
+ if pa <= pb and pa <= pc: Pr = a
+ elif pb <= pc: Pr = b
+ else: Pr = c
+
+ x = (x - Pr) & 0xff
+ out.append(x)
+ ai += 1
+
+ if not prev:
+ # We're on the first line. Some of the filters can be reduced
+ # to simpler cases which makes handling the line "off the top"
+ # of the image simpler. "up" becomes "none"; "paeth" becomes
+ # "left" (non-trivial, but true). "average" needs to be handled
+ # specially.
+ if type == 2: # "up"
+ return line # type = 0
+ elif type == 3:
+ prev = [0]*len(line)
+ elif type == 4: # "paeth"
+ type = 1
+ if type == 0:
+ out.extend(line)
+ elif type == 1:
+ sub()
+ elif type == 2:
+ up()
+ elif type == 3:
+ average()
+ else: # type == 4
+ paeth()
+ return out
+
+
+def from_array(a, mode=None, info={}):
+ """Create a PNG :class:`Image` object from a 2- or 3-dimensional array.
+ One application of this function is easy PIL-style saving:
+ ``png.from_array(pixels, 'L').save('foo.png')``.
+
+ .. note :
+
+ The use of the term *3-dimensional* is for marketing purposes
+ only. It doesn't actually work. Please bear with us. Meanwhile
+ enjoy the complimentary snacks (on request) and please use a
+ 2-dimensional array.
+
+ Unless they are specified using the *info* parameter, the PNG's
+ height and width are taken from the array size. For a 3 dimensional
+ array the first axis is the height; the second axis is the width;
+ and the third axis is the channel number. Thus an RGB image that is
+ 16 pixels high and 8 wide will use an array that is 16x8x3. For 2
+ dimensional arrays the first axis is the height, but the second axis
+ is ``width*channels``, so an RGB image that is 16 pixels high and 8
+ wide will use a 2-dimensional array that is 16x24 (each row will be
+ 8*3==24 sample values).
+
+ *mode* is a string that specifies the image colour format in a
+ PIL-style mode. It can be:
+
+ ``'L'``
+ greyscale (1 channel)
+ ``'LA'``
+ greyscale with alpha (2 channel)
+ ``'RGB'``
+ colour image (3 channel)
+ ``'RGBA'``
+ colour image with alpha (4 channel)
+
+ The mode string can also specify the bit depth (overriding how this
+ function normally derives the bit depth, see below). Appending
+ ``';16'`` to the mode will cause the PNG to be 16 bits per channel;
+ any decimal from 1 to 16 can be used to specify the bit depth.
+
+ When a 2-dimensional array is used *mode* determines how many
+ channels the image has, and so allows the width to be derived from
+ the second array dimension.
+
+ The array is expected to be a ``numpy`` array, but it can be any
+ suitable Python sequence. For example, a list of lists can be used:
+ ``png.from_array([[0, 255, 0], [255, 0, 255]], 'L')``. The exact
+ rules are: ``len(a)`` gives the first dimension, height;
+ ``len(a[0])`` gives the second dimension; ``len(a[0][0])`` gives the
+ third dimension, unless an exception is raised in which case a
+ 2-dimensional array is assumed. It's slightly more complicated than
+ that because an iterator of rows can be used, and it all still
+ works. Using an iterator allows data to be streamed efficiently.
+
+ The bit depth of the PNG is normally taken from the array element's
+ datatype (but if *mode* specifies a bitdepth then that is used
+ instead). The array element's datatype is determined in a way which
+ is supposed to work both for ``numpy`` arrays and for Python
+ ``array.array`` objects. A 1 byte datatype will give a bit depth of
+ 8, a 2 byte datatype will give a bit depth of 16. If the datatype
+ does not have an implicit size, for example it is a plain Python
+ list of lists, as above, then a default of 8 is used.
+
+ The *info* parameter is a dictionary that can be used to specify
+ metadata (in the same style as the arguments to the
+ :class:``png.Writer`` class). For this function the keys that are
+ useful are:
+
+ height
+ overrides the height derived from the array dimensions and allows
+ *a* to be an iterable.
+ width
+ overrides the width derived from the array dimensions.
+ bitdepth
+ overrides the bit depth derived from the element datatype (but
+ must match *mode* if that also specifies a bit depth).
+
+ Generally anything specified in the
+ *info* dictionary will override any implicit choices that this
+ function would otherwise make, but must match any explicit ones.
+ For example, if the *info* dictionary has a ``greyscale`` key then
+ this must be true when mode is ``'L'`` or ``'LA'`` and false when
+ mode is ``'RGB'`` or ``'RGBA'``.
+ """
+
+ # We abuse the *info* parameter by modifying it. Take a copy here.
+ # (Also typechecks *info* to some extent).
+ info = dict(info)
+
+ # Syntax check mode string.
+ bitdepth = None
+ try:
+ mode = mode.split(';')
+ if len(mode) not in (1,2):
+ raise Error()
+ if mode[0] not in ('L', 'LA', 'RGB', 'RGBA'):
+ raise Error()
+ if len(mode) == 2:
+ try:
+ bitdepth = int(mode[1])
+ except:
+ raise Error()
+ except Error:
+ raise Error("mode string should be 'RGB' or 'L;16' or similar.")
+ mode = mode[0]
+
+ # Get bitdepth from *mode* if possible.
+ if bitdepth:
+ if info.get('bitdepth') and bitdepth != info['bitdepth']:
+ raise Error("mode bitdepth (%d) should match info bitdepth (%d)." %
+ (bitdepth, info['bitdepth']))
+ info['bitdepth'] = bitdepth
+
+ # Fill in and/or check entries in *info*.
+ # Dimensions.
+ if 'size' in info:
+ # Check width, height, size all match where used.
+ for dimension,axis in [('width', 0), ('height', 1)]:
+ if dimension in info:
+ if info[dimension] != info['size'][axis]:
+ raise Error(
+ "info[%r] shhould match info['size'][%r]." %
+ (dimension, axis))
+ info['width'],info['height'] = info['size']
+ if 'height' not in info:
+ try:
+ l = len(a)
+ except:
+ raise Error(
+ "len(a) does not work, supply info['height'] instead.")
+ info['height'] = l
+ # Colour format.
+ if 'greyscale' in info:
+ if bool(info['greyscale']) != ('L' in mode):
+ raise Error("info['greyscale'] should match mode.")
+ info['greyscale'] = 'L' in mode
+ if 'alpha' in info:
+ if bool(info['alpha']) != ('A' in mode):
+ raise Error("info['alpha'] should match mode.")
+ info['alpha'] = 'A' in mode
+
+ planes = len(mode)
+ if 'planes' in info:
+ if info['planes'] != planes:
+ raise Error("info['planes'] should match mode.")
+
+ # In order to work out whether we the array is 2D or 3D we need its
+ # first row, which requires that we take a copy of its iterator.
+ # We may also need the first row to derive width and bitdepth.
+ a,t = itertools.tee(a)
+ row = next(t)
+ del t
+ try:
+ row[0][0]
+ threed = True
+ testelement = row[0]
+ except:
+ threed = False
+ testelement = row
+ if 'width' not in info:
+ if threed:
+ width = len(row)
+ else:
+ width = len(row) // planes
+ info['width'] = width
+
+ # Not implemented yet
+ assert not threed
+
+ if 'bitdepth' not in info:
+ try:
+ dtype = testelement.dtype
+ # goto the "else:" clause. Sorry.
+ except:
+ try:
+ # Try a Python array.array.
+ bitdepth = 8 * testelement.itemsize
+ except:
+ # We can't determine it from the array element's
+ # datatype, use a default of 8.
+ bitdepth = 8
+ else:
+ # If we got here without exception, we now assume that
+ # the array is a numpy array.
+ if dtype.kind == 'b':
+ bitdepth = 1
+ else:
+ bitdepth = 8 * dtype.itemsize
+ info['bitdepth'] = bitdepth
+
+ for thing in 'width height bitdepth greyscale alpha'.split():
+ assert thing in info
+ return Image(a, info)
+
+# So that refugee's from PIL feel more at home. Not documented.
+fromarray = from_array
+
+class Image:
+ """A PNG image.
+ You can create an :class:`Image` object from an array of pixels by calling
+ :meth:`png.from_array`. It can be saved to disk with the
+ :meth:`save` method."""
+ def __init__(self, rows, info):
+ """
+ .. note ::
+
+ The constructor is not public. Please do not call it.
+ """
+
+ self.rows = rows
+ self.info = info
+
+ def save(self, file):
+ """Save the image to *file*. If *file* looks like an open file
+ descriptor then it is used, otherwise it is treated as a
+ filename and a fresh file is opened.
+
+ In general, you can only call this method once; after it has
+ been called the first time and the PNG image has been saved, the
+ source data will have been streamed, and cannot be streamed
+ again.
+ """
+
+ w = Writer(**self.info)
+
+ try:
+ file.write
+ def close(): pass
+ except:
+ file = open(file, 'wb')
+ def close(): file.close()
+
+ try:
+ w.write(file, self.rows)
+ finally:
+ close()
+
+class _readable:
+ """
+ A simple file-like interface for strings and arrays.
+ """
+
+ def __init__(self, buf):
+ self.buf = buf
+ self.offset = 0
+
+ def read(self, n):
+ r = self.buf[self.offset:self.offset+n]
+ if isarray(r):
+ r = r.tostring()
+ self.offset += n
+ return r
+
+
+class Reader:
+ """
+ PNG decoder in pure Python.
+ """
+
+ def __init__(self, _guess=None, **kw):
+ """
+ Create a PNG decoder object.
+
+ The constructor expects exactly one keyword argument. If you
+ supply a positional argument instead, it will guess the input
+ type. You can choose among the following keyword arguments:
+
+ filename
+ Name of input file (a PNG file).
+ file
+ A file-like object (object with a read() method).
+ bytes
+ ``array`` or ``string`` with PNG data.
+
+ """
+ if ((_guess is not None and len(kw) != 0) or
+ (_guess is None and len(kw) != 1)):
+ raise TypeError("Reader() takes exactly 1 argument")
+
+ # Will be the first 8 bytes, later on. See validate_signature.
+ self.signature = None
+ self.transparent = None
+ # A pair of (len,type) if a chunk has been read but its data and
+ # checksum have not (in other words the file position is just
+ # past the 4 bytes that specify the chunk type). See preamble
+ # method for how this is used.
+ self.atchunk = None
+
+ if _guess is not None:
+ if isarray(_guess):
+ kw["bytes"] = _guess
+ elif isinstance(_guess, str):
+ kw["filename"] = _guess
+ elif isinstance(_guess, file):
+ kw["file"] = _guess
+
+ if "filename" in kw:
+ self.file = open(kw["filename"], "rb")
+ elif "file" in kw:
+ self.file = kw["file"]
+ elif "bytes" in kw:
+ self.file = _readable(kw["bytes"])
+ else:
+ raise TypeError("expecting filename, file or bytes array")
+
+ def chunk(self, seek=None):
+ """
+ Read the next PNG chunk from the input file; returns a
+ (*type*,*data*) tuple. *type* is the chunk's type as a string
+ (all PNG chunk types are 4 characters long). *data* is the
+ chunk's data content, as a string.
+
+ If the optional `seek` argument is
+ specified then it will keep reading chunks until it either runs
+ out of file or finds the type specified by the argument. Note
+ that in general the order of chunks in PNGs is unspecified, so
+ using `seek` can cause you to miss chunks.
+ """
+
+ self.validate_signature()
+
+ while True:
+ # http://www.w3.org/TR/PNG/#5Chunk-layout
+ if not self.atchunk:
+ self.atchunk = self.chunklentype()
+ length,type = self.atchunk
+ self.atchunk = None
+ data = self.file.read(length)
+ if len(data) != length:
+ raise ChunkError('Chunk %s too short for required %i octets.'
+ % (type, length))
+ checksum = self.file.read(4)
+ if len(checksum) != 4:
+ raise ValueError('Chunk %s too short for checksum.', tag)
+ if seek and type != seek:
+ continue
+ verify = zlib.crc32(strtobytes(type))
+ verify = zlib.crc32(data, verify)
+ # Whether the output from zlib.crc32 is signed or not varies
+ # according to hideous implementation details, see
+ # http://bugs.python.org/issue1202 .
+ # We coerce it to be positive here (in a way which works on
+ # Python 2.3 and older).
+ verify &= 2**32 - 1
+ verify = struct.pack('!I', verify)
+ if checksum != verify:
+ # print repr(checksum)
+ (a, ) = struct.unpack('!I', checksum)
+ (b, ) = struct.unpack('!I', verify)
+ raise ChunkError(
+ "Checksum error in %s chunk: 0x%08X != 0x%08X." %
+ (type, a, b))
+ return type, data
+
+ def chunks(self):
+ """Return an iterator that will yield each chunk as a
+ (*chunktype*, *content*) pair.
+ """
+
+ while True:
+ t,v = self.chunk()
+ yield t,v
+ if t == 'IEND':
+ break
+
+ def undo_filter(self, filter_type, scanline, previous):
+ """Undo the filter for a scanline. `scanline` is a sequence of
+ bytes that does not include the initial filter type byte.
+ `previous` is decoded previous scanline (for straightlaced
+ images this is the previous pixel row, but for interlaced
+ images, it is the previous scanline in the reduced image, which
+ in general is not the previous pixel row in the final image).
+ When there is no previous scanline (the first row of a
+ straightlaced image, or the first row in one of the passes in an
+ interlaced image), then this argument should be ``None``.
+
+ The scanline will have the effects of filtering removed, and the
+ result will be returned as a fresh sequence of bytes.
+ """
+
+ # :todo: Would it be better to update scanline in place?
+
+ # Create the result byte array. It seems that the best way to
+ # create the array to be the right size is to copy from an
+ # existing sequence. *sigh*
+ # If we fill the result with scanline, then this allows a
+ # micro-optimisation in the "null" and "sub" cases.
+ result = array('B', scanline)
+
+ if filter_type == 0:
+ # And here, we _rely_ on filling the result with scanline,
+ # above.
+ return result
+
+ if filter_type not in (1,2,3,4):
+ raise FormatError('Invalid PNG Filter Type.'
+ ' See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .')
+
+ # Filter unit. The stride from one pixel to the corresponding
+ # byte from the previous previous. Normally this is the pixel
+ # size in bytes, but when this is smaller than 1, the previous
+ # byte is used instead.
+ fu = max(1, self.psize)
+
+ # For the first line of a pass, synthesize a dummy previous
+ # line. An alternative approach would be to observe that on the
+ # first line 'up' is the same as 'null', 'paeth' is the same
+ # as 'sub', with only 'average' requiring any special case.
+ if not previous:
+ previous = array('B', [0]*len(scanline))
+
+ def sub():
+ """Undo sub filter."""
+
+ ai = 0
+ # Loops starts at index fu. Observe that the initial part
+ # of the result is already filled in correctly with
+ # scanline.
+ for i in range(fu, len(result)):
+ x = scanline[i]
+ a = result[ai]
+ result[i] = (x + a) & 0xff
+ ai += 1
+
+ def up():
+ """Undo up filter."""
+
+ for i in range(len(result)):
+ x = scanline[i]
+ b = previous[i]
+ result[i] = (x + b) & 0xff
+
+ def average():
+ """Undo average filter."""
+
+ ai = -fu
+ for i in range(len(result)):
+ x = scanline[i]
+ if ai < 0:
+ a = 0
+ else:
+ a = result[ai]
+ b = previous[i]
+ result[i] = (x + ((a + b) >> 1)) & 0xff
+ ai += 1
+
+ def paeth():
+ """Undo Paeth filter."""
+
+ # Also used for ci.
+ ai = -fu
+ for i in range(len(result)):
+ x = scanline[i]
+ if ai < 0:
+ a = c = 0
+ else:
+ a = result[ai]
+ c = previous[ai]
+ b = previous[i]
+ p = a + b - c
+ pa = abs(p - a)
+ pb = abs(p - b)
+ pc = abs(p - c)
+ if pa <= pb and pa <= pc:
+ pr = a
+ elif pb <= pc:
+ pr = b
+ else:
+ pr = c
+ result[i] = (x + pr) & 0xff
+ ai += 1
+
+ # Call appropriate filter algorithm. Note that 0 has already
+ # been dealt with.
+ (None, sub, up, average, paeth)[filter_type]()
+ return result
+
+ def deinterlace(self, raw):
+ """
+ Read raw pixel data, undo filters, deinterlace, and flatten.
+ Return in flat row flat pixel format.
+ """
+
+ # print >> sys.stderr, ("Reading interlaced, w=%s, r=%s, planes=%s," +
+ # " bpp=%s") % (self.width, self.height, self.planes, self.bps)
+ # Values per row (of the target image)
+ vpr = self.width * self.planes
+
+ # Make a result array, and make it big enough. Interleaving
+ # writes to the output array randomly (well, not quite), so the
+ # entire output array must be in memory.
+ fmt = 'BH'[self.bitdepth > 8]
+ a = array(fmt, [0]*vpr*self.height)
+ source_offset = 0
+
+ for xstart, ystart, xstep, ystep in _adam7:
+ # print >> sys.stderr, "Adam7: start=%s,%s step=%s,%s" % (
+ # xstart, ystart, xstep, ystep)
+ if xstart >= self.width:
+ continue
+ # The previous (reconstructed) scanline. None at the
+ # beginning of a pass to indicate that there is no previous
+ # line.
+ recon = None
+ # Pixels per row (reduced pass image)
+ ppr = int(math.ceil((self.width-xstart)/float(xstep)))
+ # Row size in bytes for this pass.
+ row_size = int(math.ceil(self.psize * ppr))
+ for y in range(ystart, self.height, ystep):
+ filter_type = raw[source_offset]
+ source_offset += 1
+ scanline = raw[source_offset:source_offset+row_size]
+ source_offset += row_size
+ recon = self.undo_filter(filter_type, scanline, recon)
+ # Convert so that there is one element per pixel value
+ flat = self.serialtoflat(recon, ppr)
+ if xstep == 1:
+ assert xstart == 0
+ offset = y * vpr
+ a[offset:offset+vpr] = flat
+ else:
+ offset = y * vpr + xstart * self.planes
+ end_offset = (y+1) * vpr
+ skip = self.planes * xstep
+ for i in range(self.planes):
+ a[offset+i:end_offset:skip] = \
+ flat[i::self.planes]
+ return a
+
+ def iterboxed(self, rows):
+ """Iterator that yields each scanline in boxed row flat pixel
+ format. `rows` should be an iterator that yields the bytes of
+ each row in turn.
+ """
+
+ def asvalues(raw):
+ """Convert a row of raw bytes into a flat row. Result may
+ or may not share with argument"""
+
+ if self.bitdepth == 8:
+ return raw
+ if self.bitdepth == 16:
+ raw = tostring(raw)
+ return array('H', struct.unpack('!%dH' % (len(raw)//2), raw))
+ assert self.bitdepth < 8
+ width = self.width
+ # Samples per byte
+ spb = 8//self.bitdepth
+ out = array('B')
+ mask = 2**self.bitdepth - 1
+ shifts = list(map(self.bitdepth.__mul__, reversed(list(range(spb)))))
+ for o in raw:
+ out.extend([mask&(o>>i) for i in shifts])
+ return out[:width]
+
+ return map(asvalues, rows)
+
+ def serialtoflat(self, bytes, width=None):
+ """Convert serial format (byte stream) pixel data to flat row
+ flat pixel.
+ """
+
+ if self.bitdepth == 8:
+ return bytes
+ if self.bitdepth == 16:
+ bytes = tostring(bytes)
+ return array('H',
+ struct.unpack('!%dH' % (len(bytes)//2), bytes))
+ assert self.bitdepth < 8
+ if width is None:
+ width = self.width
+ # Samples per byte
+ spb = 8//self.bitdepth
+ out = array('B')
+ mask = 2**self.bitdepth - 1
+ shifts = list(map(self.bitdepth.__mul__, reversed(list(range(spb)))))
+ l = width
+ for o in bytes:
+ out.extend([(mask&(o>>s)) for s in shifts][:l])
+ l -= spb
+ if l <= 0:
+ l = width
+ return out
+
+ def iterstraight(self, raw):
+ """Iterator that undoes the effect of filtering, and yields each
+ row in serialised format (as a sequence of bytes). Assumes input
+ is straightlaced. `raw` should be an iterable that yields the
+ raw bytes in chunks of arbitrary size."""
+
+ # length of row, in bytes
+ rb = self.row_bytes
+ a = array('B')
+ # The previous (reconstructed) scanline. None indicates first
+ # line of image.
+ recon = None
+ for some in raw:
+ a.extend(some)
+ while len(a) >= rb + 1:
+ filter_type = a[0]
+ scanline = a[1:rb+1]
+ del a[:rb+1]
+ recon = self.undo_filter(filter_type, scanline, recon)
+ yield recon
+ if len(a) != 0:
+ # :file:format We get here with a file format error: when the
+ # available bytes (after decompressing) do not pack into exact
+ # rows.
+ raise FormatError(
+ 'Wrong size for decompressed IDAT chunk.')
+ assert len(a) == 0
+
+ def validate_signature(self):
+ """If signature (header) has not been read then read and
+ validate it; otherwise do nothing.
+ """
+
+ if self.signature:
+ return
+ self.signature = self.file.read(8)
+ if self.signature != _signature:
+ raise FormatError("PNG file has invalid signature.")
+
+ def preamble(self):
+ """
+ Extract the image metadata by reading the initial part of the PNG
+ file up to the start of the ``IDAT`` chunk. All the chunks that
+ precede the ``IDAT`` chunk are read and either processed for
+ metadata or discarded.
+ """
+
+ self.validate_signature()
+
+ while True:
+ if not self.atchunk:
+ self.atchunk = self.chunklentype()
+ if self.atchunk is None:
+ raise FormatError(
+ 'This PNG file has no IDAT chunks.')
+ if self.atchunk[1] == 'IDAT':
+ return
+ self.process_chunk()
+
+ def chunklentype(self):
+ """Reads just enough of the input to determine the next
+ chunk's length and type, returned as a (*length*, *type*) pair
+ where *type* is a string. If there are no more chunks, ``None``
+ is returned.
+ """
+
+ x = self.file.read(8)
+ if not x:
+ return None
+ if len(x) != 8:
+ raise FormatError(
+ 'End of file whilst reading chunk length and type.')
+ length,type = struct.unpack('!I4s', x)
+ type = bytestostr(type)
+ if length > 2**31-1:
+ raise FormatError('Chunk %s is too large: %d.' % (type,length))
+ return length,type
+
+ def process_chunk(self):
+ """Process the next chunk and its data. This only processes the
+ following chunk types, all others are ignored: ``IHDR``,
+ ``PLTE``, ``bKGD``, ``tRNS``, ``gAMA``, ``sBIT``.
+ """
+
+ type, data = self.chunk()
+ if type == 'IHDR':
+ # http://www.w3.org/TR/PNG/#11IHDR
+ if len(data) != 13:
+ raise FormatError('IHDR chunk has incorrect length.')
+ (self.width, self.height, self.bitdepth, self.color_type,
+ self.compression, self.filter,
+ self.interlace) = struct.unpack("!2I5B", data)
+
+ # Check that the header specifies only valid combinations.
+ if self.bitdepth not in (1,2,4,8,16):
+ raise Error("invalid bit depth %d" % self.bitdepth)
+ if self.color_type not in (0,2,3,4,6):
+ raise Error("invalid colour type %d" % self.color_type)
+ # Check indexed (palettized) images have 8 or fewer bits
+ # per pixel; check only indexed or greyscale images have
+ # fewer than 8 bits per pixel.
+ if ((self.color_type & 1 and self.bitdepth > 8) or
+ (self.bitdepth < 8 and self.color_type not in (0,3))):
+ raise FormatError("Illegal combination of bit depth (%d)"
+ " and colour type (%d)."
+ " See http://www.w3.org/TR/2003/REC-PNG-20031110/#table111 ."
+ % (self.bitdepth, self.color_type))
+ if self.compression != 0:
+ raise Error("unknown compression method %d" % self.compression)
+ if self.filter != 0:
+ raise FormatError("Unknown filter method %d,"
+ " see http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters ."
+ % self.filter)
+ if self.interlace not in (0,1):
+ raise FormatError("Unknown interlace method %d,"
+ " see http://www.w3.org/TR/2003/REC-PNG-20031110/#8InterlaceMethods ."
+ % self.interlace)
+
+ # Derived values
+ # http://www.w3.org/TR/PNG/#6Colour-values
+ colormap = bool(self.color_type & 1)
+ greyscale = not (self.color_type & 2)
+ alpha = bool(self.color_type & 4)
+ color_planes = (3,1)[greyscale or colormap]
+ planes = color_planes + alpha
+
+ self.colormap = colormap
+ self.greyscale = greyscale
+ self.alpha = alpha
+ self.color_planes = color_planes
+ self.planes = planes
+ self.psize = float(self.bitdepth)/float(8) * planes
+ if int(self.psize) == self.psize:
+ self.psize = int(self.psize)
+ self.row_bytes = int(math.ceil(self.width * self.psize))
+ # Stores PLTE chunk if present, and is used to check
+ # chunk ordering constraints.
+ self.plte = None
+ # Stores tRNS chunk if present, and is used to check chunk
+ # ordering constraints.
+ self.trns = None
+ # Stores sbit chunk if present.
+ self.sbit = None
+ elif type == 'PLTE':
+ # http://www.w3.org/TR/PNG/#11PLTE
+ if self.plte:
+ warnings.warn("Multiple PLTE chunks present.")
+ self.plte = data
+ if len(data) % 3 != 0:
+ raise FormatError(
+ "PLTE chunk's length should be a multiple of 3.")
+ if len(data) > (2**self.bitdepth)*3:
+ raise FormatError("PLTE chunk is too long.")
+ if len(data) == 0:
+ raise FormatError("Empty PLTE is not allowed.")
+ elif type == 'bKGD':
+ try:
+ if self.colormap:
+ if not self.plte:
+ warnings.warn(
+ "PLTE chunk is required before bKGD chunk.")
+ self.background = struct.unpack('B', data)
+ else:
+ self.background = struct.unpack("!%dH" % self.color_planes,
+ data)
+ except struct.error:
+ raise FormatError("bKGD chunk has incorrect length.")
+ elif type == 'tRNS':
+ # http://www.w3.org/TR/PNG/#11tRNS
+ self.trns = data
+ if self.colormap:
+ if not self.plte:
+ warnings.warn("PLTE chunk is required before tRNS chunk.")
+ else:
+ if len(data) > len(self.plte)/3:
+ # Was warning, but promoted to Error as it
+ # would otherwise cause pain later on.
+ raise FormatError("tRNS chunk is too long.")
+ else:
+ if self.alpha:
+ raise FormatError(
+ "tRNS chunk is not valid with colour type %d." %
+ self.color_type)
+ try:
+ self.transparent = \
+ struct.unpack("!%dH" % self.color_planes, data)
+ except struct.error:
+ raise FormatError("tRNS chunk has incorrect length.")
+ elif type == 'gAMA':
+ try:
+ self.gamma = struct.unpack("!L", data)[0] / 100000.0
+ except struct.error:
+ raise FormatError("gAMA chunk has incorrect length.")
+ elif type == 'sBIT':
+ self.sbit = data
+ if (self.colormap and len(data) != 3 or
+ not self.colormap and len(data) != self.planes):
+ raise FormatError("sBIT chunk has incorrect length.")
+
+ def read(self):
+ """
+ Read the PNG file and decode it. Returns (`width`, `height`,
+ `pixels`, `metadata`).
+
+ May use excessive memory.
+
+ `pixels` are returned in boxed row flat pixel format.
+ """
+
+ def iteridat():
+ """Iterator that yields all the ``IDAT`` chunks as strings."""
+ while True:
+ try:
+ type, data = self.chunk()
+ except ValueError as e:
+ raise ChunkError(e.args[0])
+ if type == 'IEND':
+ # http://www.w3.org/TR/PNG/#11IEND
+ break
+ if type != 'IDAT':
+ continue
+ # type == 'IDAT'
+ # http://www.w3.org/TR/PNG/#11IDAT
+ if self.colormap and not self.plte:
+ warnings.warn("PLTE chunk is required before IDAT chunk")
+ yield data
+
+ def iterdecomp(idat):
+ """Iterator that yields decompressed strings. `idat` should
+ be an iterator that yields the ``IDAT`` chunk data.
+ """
+
+ # Currently, with no max_length paramter to decompress, this
+ # routine will do one yield per IDAT chunk. So not very
+ # incremental.
+ d = zlib.decompressobj()
+ # Each IDAT chunk is passed to the decompressor, then any
+ # remaining state is decompressed out.
+ for data in idat:
+ # :todo: add a max_length argument here to limit output
+ # size.
+ yield array('B', d.decompress(data))
+ yield array('B', d.flush())
+
+ self.preamble()
+ raw = iterdecomp(iteridat())
+
+ if self.interlace:
+ raw = array('B', itertools.chain(*raw))
+ arraycode = 'BH'[self.bitdepth>8]
+ # Like :meth:`group` but producing an array.array object for
+ # each row.
+ pixels = map(lambda *row: array(arraycode, row),
+ *[iter(self.deinterlace(raw))]*self.width*self.planes)
+ else:
+ pixels = self.iterboxed(self.iterstraight(raw))
+ meta = dict()
+ for attr in 'greyscale alpha planes bitdepth interlace'.split():
+ meta[attr] = getattr(self, attr)
+ meta['size'] = (self.width, self.height)
+ for attr in 'gamma transparent background'.split():
+ a = getattr(self, attr, None)
+ if a is not None:
+ meta[attr] = a
+ return self.width, self.height, pixels, meta
+
+
+ def read_flat(self):
+ """
+ Read a PNG file and decode it into flat row flat pixel format.
+ Returns (*width*, *height*, *pixels*, *metadata*).
+
+ May use excessive memory.
+
+ `pixels` are returned in flat row flat pixel format.
+
+ See also the :meth:`read` method which returns pixels in the
+ more stream-friendly boxed row flat pixel format.
+ """
+
+ x, y, pixel, meta = self.read()
+ arraycode = 'BH'[meta['bitdepth']>8]
+ pixel = array(arraycode, itertools.chain(*pixel))
+ return x, y, pixel, meta
+
+ def palette(self, alpha='natural'):
+ """Returns a palette that is a sequence of 3-tuples or 4-tuples,
+ synthesizing it from the ``PLTE`` and ``tRNS`` chunks. These
+ chunks should have already been processed (for example, by
+ calling the :meth:`preamble` method). All the tuples are the
+ same size: 3-tuples if there is no ``tRNS`` chunk, 4-tuples when
+ there is a ``tRNS`` chunk. Assumes that the image is colour type
+ 3 and therefore a ``PLTE`` chunk is required.
+
+ If the `alpha` argument is ``'force'`` then an alpha channel is
+ always added, forcing the result to be a sequence of 4-tuples.
+ """
+
+ if not self.plte:
+ raise FormatError(
+ "Required PLTE chunk is missing in colour type 3 image.")
+ plte = group(array('B', self.plte), 3)
+ if self.trns or alpha == 'force':
+ trns = array('B', self.trns or '')
+ trns.extend([255]*(len(plte)-len(trns)))
+ plte = list(map(operator.add, plte, group(trns, 1)))
+ return plte
+
+ def asDirect(self):
+ """Returns the image data as a direct representation of an
+ ``x * y * planes`` array. This method is intended to remove the
+ need for callers to deal with palettes and transparency
+ themselves. Images with a palette (colour type 3)
+ are converted to RGB or RGBA; images with transparency (a
+ ``tRNS`` chunk) are converted to LA or RGBA as appropriate.
+ When returned in this format the pixel values represent the
+ colour value directly without needing to refer to palettes or
+ transparency information.
+
+ Like the :meth:`read` method this method returns a 4-tuple:
+
+ (*width*, *height*, *pixels*, *meta*)
+
+ This method normally returns pixel values with the bit depth
+ they have in the source image, but when the source PNG has an
+ ``sBIT`` chunk it is inspected and can reduce the bit depth of
+ the result pixels; pixel values will be reduced according to
+ the bit depth specified in the ``sBIT`` chunk (PNG nerds should
+ note a single result bit depth is used for all channels; the
+ maximum of the ones specified in the ``sBIT`` chunk. An RGB565
+ image will be rescaled to 6-bit RGB666).
+
+ The *meta* dictionary that is returned reflects the `direct`
+ format and not the original source image. For example, an RGB
+ source image with a ``tRNS`` chunk to represent a transparent
+ colour, will have ``planes=3`` and ``alpha=False`` for the
+ source image, but the *meta* dictionary returned by this method
+ will have ``planes=4`` and ``alpha=True`` because an alpha
+ channel is synthesized and added.
+
+ *pixels* is the pixel data in boxed row flat pixel format (just
+ like the :meth:`read` method).
+
+ All the other aspects of the image data are not changed.
+ """
+
+ self.preamble()
+
+ # Simple case, no conversion necessary.
+ if not self.colormap and not self.trns and not self.sbit:
+ return self.read()
+
+ x,y,pixels,meta = self.read()
+
+ if self.colormap:
+ meta['colormap'] = False
+ meta['alpha'] = bool(self.trns)
+ meta['bitdepth'] = 8
+ meta['planes'] = 3 + bool(self.trns)
+ plte = self.palette()
+ def iterpal(pixels):
+ for row in pixels:
+ row = list(map(plte.__getitem__, row))
+ yield array('B', itertools.chain(*row))
+ pixels = iterpal(pixels)
+ elif self.trns:
+ # It would be nice if there was some reasonable way of doing
+ # this without generating a whole load of intermediate tuples.
+ # But tuples does seem like the easiest way, with no other way
+ # clearly much simpler or much faster. (Actually, the L to LA
+ # conversion could perhaps go faster (all those 1-tuples!), but
+ # I still wonder whether the code proliferation is worth it)
+ it = self.transparent
+ maxval = 2**meta['bitdepth']-1
+ planes = meta['planes']
+ meta['alpha'] = True
+ meta['planes'] += 1
+ typecode = 'BH'[meta['bitdepth']>8]
+ def itertrns(pixels):
+ for row in pixels:
+ # For each row we group it into pixels, then form a
+ # characterisation vector that says whether each pixel
+ # is opaque or not. Then we convert True/False to
+ # 0/maxval (by multiplication), and add it as the extra
+ # channel.
+ row = group(row, planes)
+ opa = list(map(it.__ne__, row))
+ opa = list(map(maxval.__mul__, opa))
+ opa = list(zip(opa)) # convert to 1-tuples
+ yield array(typecode,
+ itertools.chain(*list(map(operator.add, row, opa))))
+ pixels = itertrns(pixels)
+ targetbitdepth = None
+ if self.sbit:
+ sbit = struct.unpack('%dB' % len(self.sbit), self.sbit)
+ targetbitdepth = max(sbit)
+ if targetbitdepth > meta['bitdepth']:
+ raise Error('sBIT chunk %r exceeds bitdepth %d' %
+ (sbit,self.bitdepth))
+ if min(sbit) <= 0:
+ raise Error('sBIT chunk %r has a 0-entry' % sbit)
+ if targetbitdepth == meta['bitdepth']:
+ targetbitdepth = None
+ if targetbitdepth:
+ shift = meta['bitdepth'] - targetbitdepth
+ meta['bitdepth'] = targetbitdepth
+ def itershift(pixels):
+ for row in pixels:
+ yield list(map(shift.__rrshift__, row))
+ pixels = itershift(pixels)
+ return x,y,pixels,meta
+
+ def asFloat(self, maxval=1.0):
+ """Return image pixels as per :meth:`asDirect` method, but scale
+ all pixel values to be floating point values between 0.0 and
+ *maxval*.
+ """
+
+ x,y,pixels,info = self.asDirect()
+ sourcemaxval = 2**info['bitdepth']-1
+ del info['bitdepth']
+ info['maxval'] = float(maxval)
+ factor = float(maxval)/float(sourcemaxval)
+ def iterfloat():
+ for row in pixels:
+ yield list(map(factor.__mul__, row))
+ return x,y,iterfloat(),info
+
+ def _as_rescale(self, get, targetbitdepth):
+ """Helper used by :meth:`asRGB8` and :meth:`asRGBA8`."""
+
+ width,height,pixels,meta = get()
+ maxval = 2**meta['bitdepth'] - 1
+ targetmaxval = 2**targetbitdepth - 1
+ factor = float(targetmaxval) / float(maxval)
+ meta['bitdepth'] = targetbitdepth
+ def iterscale():
+ for row in pixels:
+ yield [int(round(x*factor)) for x in row]
+ return width, height, iterscale(), meta
+
+ def asRGB8(self):
+ """Return the image data as an RGB pixels with 8-bits per
+ sample. This is like the :meth:`asRGB` method except that
+ this method additionally rescales the values so that they
+ are all between 0 and 255 (8-bit). In the case where the
+ source image has a bit depth < 8 the transformation preserves
+ all the information; where the source image has bit depth
+ > 8, then rescaling to 8-bit values loses precision. No
+ dithering is performed. Like :meth:`asRGB`, an alpha channel
+ in the source image will raise an exception.
+
+ This function returns a 4-tuple:
+ (*width*, *height*, *pixels*, *metadata*).
+ *width*, *height*, *metadata* are as per the :meth:`read` method.
+
+ *pixels* is the pixel data in boxed row flat pixel format.
+ """
+
+ return self._as_rescale(self.asRGB, 8)
+
+ def asRGBA8(self):
+ """Return the image data as RGBA pixels with 8-bits per
+ sample. This method is similar to :meth:`asRGB8` and
+ :meth:`asRGBA`: The result pixels have an alpha channel, *and*
+ values are rescaled to the range 0 to 255. The alpha channel is
+ synthesized if necessary (with a small speed penalty).
+ """
+
+ return self._as_rescale(self.asRGBA, 8)
+
+ def asRGB(self):
+ """Return image as RGB pixels. RGB colour images are passed
+ through unchanged; greyscales are expanded into RGB
+ triplets (there is a small speed overhead for doing this).
+
+ An alpha channel in the source image will raise an
+ exception.
+
+ The return values are as for the :meth:`read` method
+ except that the *metadata* reflect the returned pixels, not the
+ source image. In particular, for this method
+ ``metadata['greyscale']`` will be ``False``.
+ """
+
+ width,height,pixels,meta = self.asDirect()
+ if meta['alpha']:
+ raise Error("will not convert image with alpha channel to RGB")
+ if not meta['greyscale']:
+ return width,height,pixels,meta
+ meta['greyscale'] = False
+ typecode = 'BH'[meta['bitdepth'] > 8]
+ def iterrgb():
+ for row in pixels:
+ a = array(typecode, [0]) * 3 * width
+ for i in range(3):
+ a[i::3] = row
+ yield a
+ return width,height,iterrgb(),meta
+
+ def asRGBA(self):
+ """Return image as RGBA pixels. Greyscales are expanded into
+ RGB triplets; an alpha channel is synthesized if necessary.
+ The return values are as for the :meth:`read` method
+ except that the *metadata* reflect the returned pixels, not the
+ source image. In particular, for this method
+ ``metadata['greyscale']`` will be ``False``, and
+ ``metadata['alpha']`` will be ``True``.
+ """
+
+ width,height,pixels,meta = self.asDirect()
+ if meta['alpha'] and not meta['greyscale']:
+ return width,height,pixels,meta
+ typecode = 'BH'[meta['bitdepth'] > 8]
+ maxval = 2**meta['bitdepth'] - 1
+ def newarray():
+ return array(typecode, [0]) * 4 * width
+ if meta['alpha'] and meta['greyscale']:
+ # LA to RGBA
+ def convert():
+ for row in pixels:
+ # Create a fresh target row, then copy L channel
+ # into first three target channels, and A channel
+ # into fourth channel.
+ a = newarray()
+ for i in range(3):
+ a[i::4] = row[0::2]
+ a[3::4] = row[1::2]
+ yield a
+ elif meta['greyscale']:
+ # L to RGBA
+ def convert():
+ for row in pixels:
+ a = newarray()
+ for i in range(3):
+ a[i::4] = row
+ a[3::4] = array(typecode, [maxval]) * width
+ yield a
+ else:
+ assert not meta['alpha'] and not meta['greyscale']
+ # RGB to RGBA
+ def convert():
+ for row in pixels:
+ a = newarray()
+ for i in range(3):
+ a[i::4] = row[i::3]
+ a[3::4] = array(typecode, [maxval]) * width
+ yield a
+ meta['alpha'] = True
+ meta['greyscale'] = False
+ return width,height,convert(),meta
+
+
+# === Legacy Version Support ===
+
+# :pyver:old: PyPNG works on Python versions 2.3 and 2.2, but not
+# without some awkward problems. Really PyPNG works on Python 2.4 (and
+# above); it works on Pythons 2.3 and 2.2 by virtue of fixing up
+# problems here. It's a bit ugly (which is why it's hidden down here).
+#
+# Generally the strategy is one of pretending that we're running on
+# Python 2.4 (or above), and patching up the library support on earlier
+# versions so that it looks enough like Python 2.4. When it comes to
+# Python 2.2 there is one thing we cannot patch: extended slices
+# http://www.python.org/doc/2.3/whatsnew/section-slices.html.
+# Instead we simply declare that features that are implemented using
+# extended slices will not work on Python 2.2.
+#
+# In order to work on Python 2.3 we fix up a recurring annoyance involving
+# the array type. In Python 2.3 an array cannot be initialised with an
+# array, and it cannot be extended with a list (or other sequence).
+# Both of those are repeated issues in the code. Whilst I would not
+# normally tolerate this sort of behaviour, here we "shim" a replacement
+# for array into place (and hope no-ones notices). You never read this.
+#
+# In an amusing case of warty hacks on top of warty hacks... the array
+# shimming we try and do only works on Python 2.3 and above (you can't
+# subclass array.array in Python 2.2). So to get it working on Python
+# 2.2 we go for something much simpler and (probably) way slower.
+try:
+ array('B').extend([])
+ array('B', array('B'))
+except:
+ # Expect to get here on Python 2.3
+ try:
+ class _array_shim(array):
+ true_array = array
+ def __new__(cls, typecode, init=None):
+ super_new = super(_array_shim, cls).__new__
+ it = super_new(cls, typecode)
+ if init is None:
+ return it
+ it.extend(init)
+ return it
+ def extend(self, extension):
+ super_extend = super(_array_shim, self).extend
+ if isinstance(extension, self.true_array):
+ return super_extend(extension)
+ if not isinstance(extension, (list, str)):
+ # Convert to list. Allows iterators to work.
+ extension = list(extension)
+ return super_extend(self.true_array(self.typecode, extension))
+ array = _array_shim
+ except:
+ # Expect to get here on Python 2.2
+ def array(typecode, init=()):
+ if type(init) == str:
+ return list(map(ord, init))
+ return list(init)
+
+# Further hacks to get it limping along on Python 2.2
+try:
+ enumerate
+except:
+ def enumerate(seq):
+ i=0
+ for x in seq:
+ yield i,x
+ i += 1
+
+try:
+ reversed
+except:
+ def reversed(l):
+ l = list(l)
+ l.reverse()
+ for x in l:
+ yield x
+
+try:
+ itertools
+except:
+ class _dummy_itertools:
+ pass
+ itertools = _dummy_itertools()
+ def _itertools_imap(f, seq):
+ for x in seq:
+ yield f(x)
+ itertools.imap = _itertools_imap
+ def _itertools_chain(*iterables):
+ for it in iterables:
+ for element in it:
+ yield element
+ itertools.chain = _itertools_chain
+
+
+
+# === Internal Test Support ===
+
+# This section comprises the tests that are internally validated (as
+# opposed to tests which produce output files that are externally
+# validated). Primarily they are unittests.
+
+# Note that it is difficult to internally validate the results of
+# writing a PNG file. The only thing we can do is read it back in
+# again, which merely checks consistency, not that the PNG file we
+# produce is valid.
+
+# Run the tests from the command line:
+# python -c 'import png;png.test()'
+
+# (For an in-memory binary file IO object) We use BytesIO where
+# available, otherwise we use StringIO, but name it BytesIO.
+try:
+ from io import BytesIO
+except:
+ from io import StringIO as BytesIO
+import tempfile
+# http://www.python.org/doc/2.4.4/lib/module-unittest.html
+import unittest
+
+
+def test():
+ unittest.main(__name__)
+
+def topngbytes(name, rows, x, y, **k):
+ """Convenience function for creating a PNG file "in memory" as a
+ string. Creates a :class:`Writer` instance using the keyword arguments,
+ then passes `rows` to its :meth:`Writer.write` method. The resulting
+ PNG file is returned as a string. `name` is used to identify the file for
+ debugging.
+ """
+
+ import os
+
+ print(name)
+ f = BytesIO()
+ w = Writer(x, y, **k)
+ w.write(f, rows)
+ if os.environ.get('PYPNG_TEST_TMP'):
+ w = open(name, 'wb')
+ w.write(f.getvalue())
+ w.close()
+ return f.getvalue()
+
+def testWithIO(inp, out, f):
+ """Calls the function `f` with ``sys.stdin`` changed to `inp`
+ and ``sys.stdout`` changed to `out`. They are restored when `f`
+ returns. This function returns whatever `f` returns.
+ """
+
+ import os
+
+ try:
+ oldin,sys.stdin = sys.stdin,inp
+ oldout,sys.stdout = sys.stdout,out
+ x = f()
+ finally:
+ sys.stdin = oldin
+ sys.stdout = oldout
+ if os.environ.get('PYPNG_TEST_TMP') and hasattr(out,'getvalue'):
+ name = mycallersname()
+ if name:
+ w = open(name+'.png', 'wb')
+ w.write(out.getvalue())
+ w.close()
+ return x
+
+def mycallersname():
+ """Returns the name of the caller of the caller of this function
+ (hence the name of the caller of the function in which
+ "mycallersname()" textually appears). Returns None if this cannot
+ be determined."""
+
+ # http://docs.python.org/library/inspect.html#the-interpreter-stack
+ import inspect
+
+ frame = inspect.currentframe()
+ if not frame:
+ return None
+ frame_,filename_,lineno_,funname,linelist_,listi_ = (
+ inspect.getouterframes(frame)[2])
+ return funname
+
+def seqtobytes(s):
+ """Convert a sequence of integers to a *bytes* instance. Good for
+ plastering over Python 2 / Python 3 cracks.
+ """
+
+ return strtobytes(''.join(chr(x) for x in s))
+
+class Test(unittest.TestCase):
+ # This member is used by the superclass. If we don't define a new
+ # class here then when we use self.assertRaises() and the PyPNG code
+ # raises an assertion then we get no proper traceback. I can't work
+ # out why, but defining a new class here means we get a proper
+ # traceback.
+ class failureException(Exception):
+ pass
+
+ def helperLN(self, n):
+ mask = (1 << n) - 1
+ # Use small chunk_limit so that multiple chunk writing is
+ # tested. Making it a test for Issue 20.
+ w = Writer(15, 17, greyscale=True, bitdepth=n, chunk_limit=99)
+ f = BytesIO()
+ w.write_array(f, array('B', list(map(mask.__and__, list(range(1, 256))))))
+ r = Reader(bytes=f.getvalue())
+ x,y,pixels,meta = r.read()
+ self.assertEqual(x, 15)
+ self.assertEqual(y, 17)
+ self.assertEqual(list(itertools.chain(*pixels)),
+ list(map(mask.__and__, list(range(1,256)))))
+ def testL8(self):
+ return self.helperLN(8)
+ def testL4(self):
+ return self.helperLN(4)
+ def testL2(self):
+ "Also tests asRGB8."
+ w = Writer(1, 4, greyscale=True, bitdepth=2)
+ f = BytesIO()
+ w.write_array(f, array('B', list(range(4))))
+ r = Reader(bytes=f.getvalue())
+ x,y,pixels,meta = r.asRGB8()
+ self.assertEqual(x, 1)
+ self.assertEqual(y, 4)
+ for i,row in enumerate(pixels):
+ self.assertEqual(len(row), 3)
+ self.assertEqual(list(row), [0x55*i]*3)
+ def testP2(self):
+ "2-bit palette."
+ a = (255,255,255)
+ b = (200,120,120)
+ c = (50,99,50)
+ w = Writer(1, 4, bitdepth=2, palette=[a,b,c])
+ f = BytesIO()
+ w.write_array(f, array('B', (0,1,1,2)))
+ r = Reader(bytes=f.getvalue())
+ x,y,pixels,meta = r.asRGB8()
+ self.assertEqual(x, 1)
+ self.assertEqual(y, 4)
+ self.assertEqual(list(pixels), list(map(list, [a, b, b, c])))
+ def testPtrns(self):
+ "Test colour type 3 and tRNS chunk (and 4-bit palette)."
+ a = (50,99,50,50)
+ b = (200,120,120,80)
+ c = (255,255,255)
+ d = (200,120,120)
+ e = (50,99,50)
+ w = Writer(3, 3, bitdepth=4, palette=[a,b,c,d,e])
+ f = BytesIO()
+ w.write_array(f, array('B', (4, 3, 2, 3, 2, 0, 2, 0, 1)))
+ r = Reader(bytes=f.getvalue())
+ x,y,pixels,meta = r.asRGBA8()
+ self.assertEqual(x, 3)
+ self.assertEqual(y, 3)
+ c = c+(255,)
+ d = d+(255,)
+ e = e+(255,)
+ boxed = [(e,d,c),(d,c,a),(c,a,b)]
+ flat = [itertools.chain(*row) for row in boxed]
+ self.assertEqual(list(map(list, pixels)), list(map(list, flat)))
+ def testRGBtoRGBA(self):
+ "asRGBA8() on colour type 2 source."""
+ # Test for Issue 26
+ r = Reader(bytes=_pngsuite['basn2c08'])
+ x,y,pixels,meta = r.asRGBA8()
+ # Test the pixels at row 9 columns 0 and 1.
+ row9 = list(pixels)[9]
+ self.assertEqual(row9[0:8],
+ [0xff, 0xdf, 0xff, 0xff, 0xff, 0xde, 0xff, 0xff])
+ def testLtoRGBA(self):
+ "asRGBA() on grey source."""
+ # Test for Issue 60
+ r = Reader(bytes=_pngsuite['basi0g08'])
+ x,y,pixels,meta = r.asRGBA()
+ row9 = list(list(pixels)[9])
+ self.assertEqual(row9[0:8],
+ [222, 222, 222, 255, 221, 221, 221, 255])
+ def testCtrns(self):
+ "Test colour type 2 and tRNS chunk."
+ # Test for Issue 25
+ r = Reader(bytes=_pngsuite['tbrn2c08'])
+ x,y,pixels,meta = r.asRGBA8()
+ # I just happen to know that the first pixel is transparent.
+ # In particular it should be #7f7f7f00
+ row0 = list(pixels)[0]
+ self.assertEqual(tuple(row0[0:4]), (0x7f, 0x7f, 0x7f, 0x00))
+ def testAdam7read(self):
+ """Adam7 interlace reading.
+ Specifically, test that for images in the PngSuite that
+ have both an interlaced and straightlaced pair that both
+ images from the pair produce the same array of pixels."""
+ for candidate in _pngsuite:
+ if not candidate.startswith('basn'):
+ continue
+ candi = candidate.replace('n', 'i')
+ if candi not in _pngsuite:
+ continue
+ print('adam7 read', candidate)
+ straight = Reader(bytes=_pngsuite[candidate])
+ adam7 = Reader(bytes=_pngsuite[candi])
+ # Just compare the pixels. Ignore x,y (because they're
+ # likely to be correct?); metadata is ignored because the
+ # "interlace" member differs. Lame.
+ straight = straight.read()[2]
+ adam7 = adam7.read()[2]
+ self.assertEqual(list(map(list, straight)), list(map(list, adam7)))
+ def testAdam7write(self):
+ """Adam7 interlace writing.
+ For each test image in the PngSuite, write an interlaced
+ and a straightlaced version. Decode both, and compare results.
+ """
+ # Not such a great test, because the only way we can check what
+ # we have written is to read it back again.
+
+ for name,bytes in list(_pngsuite.items()):
+ # Only certain colour types supported for this test.
+ if name[3:5] not in ['n0', 'n2', 'n4', 'n6']:
+ continue
+ it = Reader(bytes=bytes)
+ x,y,pixels,meta = it.read()
+ pngi = topngbytes('adam7wn'+name+'.png', pixels,
+ x=x, y=y, bitdepth=it.bitdepth,
+ greyscale=it.greyscale, alpha=it.alpha,
+ transparent=it.transparent,
+ interlace=False)
+ x,y,ps,meta = Reader(bytes=pngi).read()
+ it = Reader(bytes=bytes)
+ x,y,pixels,meta = it.read()
+ pngs = topngbytes('adam7wi'+name+'.png', pixels,
+ x=x, y=y, bitdepth=it.bitdepth,
+ greyscale=it.greyscale, alpha=it.alpha,
+ transparent=it.transparent,
+ interlace=True)
+ x,y,pi,meta = Reader(bytes=pngs).read()
+ self.assertEqual(list(map(list, ps)), list(map(list, pi)))
+ def testPGMin(self):
+ """Test that the command line tool can read PGM files."""
+ def do():
+ return _main(['testPGMin'])
+ s = BytesIO()
+ s.write(strtobytes('P5 2 2 3\n'))
+ s.write(strtobytes('\x00\x01\x02\x03'))
+ s.flush()
+ s.seek(0)
+ o = BytesIO()
+ testWithIO(s, o, do)
+ r = Reader(bytes=o.getvalue())
+ x,y,pixels,meta = r.read()
+ self.assertTrue(r.greyscale)
+ self.assertEqual(r.bitdepth, 2)
+ def testPAMin(self):
+ """Test that the command line tool can read PAM file."""
+ def do():
+ return _main(['testPAMin'])
+ s = BytesIO()
+ s.write(strtobytes('P7\nWIDTH 3\nHEIGHT 1\nDEPTH 4\nMAXVAL 255\n'
+ 'TUPLTYPE RGB_ALPHA\nENDHDR\n'))
+ # The pixels in flat row flat pixel format
+ flat = [255,0,0,255, 0,255,0,120, 0,0,255,30]
+ asbytes = seqtobytes(flat)
+ s.write(asbytes)
+ s.flush()
+ s.seek(0)
+ o = BytesIO()
+ testWithIO(s, o, do)
+ r = Reader(bytes=o.getvalue())
+ x,y,pixels,meta = r.read()
+ self.assertTrue(r.alpha)
+ self.assertTrue(not r.greyscale)
+ self.assertEqual(list(itertools.chain(*pixels)), flat)
+ def testLA4(self):
+ """Create an LA image with bitdepth 4."""
+ bytes = topngbytes('la4.png', [[5, 12]], 1, 1,
+ greyscale=True, alpha=True, bitdepth=4)
+ sbit = Reader(bytes=bytes).chunk('sBIT')[1]
+ self.assertEqual(sbit, strtobytes('\x04\x04'))
+ def testPNMsbit(self):
+ """Test that PNM files can generates sBIT chunk."""
+ def do():
+ return _main(['testPNMsbit'])
+ s = BytesIO()
+ s.write(strtobytes('P6 8 1 1\n'))
+ for pixel in range(8):
+ s.write(struct.pack(' 255:
+ a = array('H')
+ else:
+ a = array('B')
+ fw = float(width)
+ fh = float(height)
+ pfun = test_patterns[pattern]
+ for y in range(height):
+ fy = float(y)/fh
+ for x in range(width):
+ a.append(int(round(pfun(float(x)/fw, fy) * maxval)))
+ return a
+
+ def test_rgba(size=(256,256), bitdepth=8,
+ red="GTB", green="GLR", blue="RTL", alpha=None):
+ """
+ Create a test image. Each channel is generated from the
+ specified pattern; any channel apart from red can be set to
+ None, which will cause it not to be in the image. It
+ is possible to create all PNG channel types (L, RGB, LA, RGBA),
+ as well as non PNG channel types (RGA, and so on).
+ *size* is a pair: (*width*,*height).
+ """
+
+ i = test_pattern(size[0], size[1], bitdepth, red)
+ psize = 1
+ for channel in (green, blue, alpha):
+ if channel:
+ c = test_pattern(size[0], size[1], bitdepth, channel)
+ i = interleave_planes(i, c, psize, 1)
+ psize += 1
+ return i
+
+ def pngsuite_image(name):
+ """
+ Create a test image by reading an internal copy of the files
+ from the PngSuite. Returned in flat row flat pixel format.
+ """
+
+ if name not in _pngsuite:
+ raise NotImplementedError("cannot find PngSuite file %s (use -L for a list)" % name)
+ r = Reader(bytes=_pngsuite[name])
+ w,h,pixels,meta = r.asDirect()
+ # LAn for n < 8 is a special case for which we need to rescale
+ # the data.
+ if meta['greyscale'] and meta['alpha'] and meta['bitdepth'] < 8:
+ factor = 255 // (2**meta['bitdepth']-1)
+ def rescale(data):
+ for row in data:
+ yield list(map(factor.__mul__, row))
+ pixels = rescale(pixels)
+ meta['bitdepth'] = 8
+ arraycode = 'BH'[meta['bitdepth']>8]
+ return w, h, array(arraycode, itertools.chain(*pixels)), meta
+
+ # The body of test_suite()
+
+ size = (256,256)
+ # Expect option of the form '64,40'.
+ if options.test_size:
+ size = re.findall(r'\d+', options.test_size)
+ if len(size) not in [1,2]:
+ raise ValueError(
+ 'size should be one or two numbers, separated by punctuation')
+ if len(size) == 1:
+ size *= 2
+ assert len(size) == 2
+ size = list(map(int, size))
+ options.bitdepth = options.test_depth
+ options.greyscale=bool(options.test_black)
+
+ kwargs = {}
+ if options.test_red:
+ kwargs["red"] = options.test_red
+ if options.test_green:
+ kwargs["green"] = options.test_green
+ if options.test_blue:
+ kwargs["blue"] = options.test_blue
+ if options.test_alpha:
+ kwargs["alpha"] = options.test_alpha
+ if options.greyscale:
+ if options.test_red or options.test_green or options.test_blue:
+ raise ValueError("cannot specify colours (R, G, B) when greyscale image (black channel, K) is specified")
+ kwargs["red"] = options.test_black
+ kwargs["green"] = None
+ kwargs["blue"] = None
+ options.alpha = bool(options.test_alpha)
+ if not args:
+ pixels = test_rgba(size, options.bitdepth, **kwargs)
+ else:
+ w,h,pixels,meta = pngsuite_image(args[0])
+ size = (w,h)
+ for k in ['bitdepth', 'alpha', 'greyscale']:
+ setattr(options, k, meta[k])
+
+ writer = Writer(size[0], size[1],
+ bitdepth=options.bitdepth,
+ transparent=options.transparent,
+ background=options.background,
+ gamma=options.gamma,
+ greyscale=options.greyscale,
+ alpha=options.alpha,
+ compression=options.compression,
+ interlace=options.interlace)
+ writer.write_array(sys.stdout, pixels)
+
+def read_pam_header(infile):
+ """
+ Read (the rest of a) PAM header. `infile` should be positioned
+ immediately after the initial 'P7' line (at the beginning of the
+ second line). Returns are as for `read_pnm_header`.
+ """
+
+ # Unlike PBM, PGM, and PPM, we can read the header a line at a time.
+ header = dict()
+ while True:
+ l = infile.readline().strip()
+ if l == strtobytes('ENDHDR'):
+ break
+ if not l:
+ raise EOFError('PAM ended prematurely')
+ if l[0] == strtobytes('#'):
+ continue
+ l = l.split(None, 1)
+ if l[0] not in header:
+ header[l[0]] = l[1]
+ else:
+ header[l[0]] += strtobytes(' ') + l[1]
+
+ required = ['WIDTH', 'HEIGHT', 'DEPTH', 'MAXVAL']
+ required = [strtobytes(x) for x in required]
+ WIDTH,HEIGHT,DEPTH,MAXVAL = required
+ present = [x for x in required if x in header]
+ if len(present) != len(required):
+ raise Error('PAM file must specify WIDTH, HEIGHT, DEPTH, and MAXVAL')
+ width = int(header[WIDTH])
+ height = int(header[HEIGHT])
+ depth = int(header[DEPTH])
+ maxval = int(header[MAXVAL])
+ if (width <= 0 or
+ height <= 0 or
+ depth <= 0 or
+ maxval <= 0):
+ raise Error(
+ 'WIDTH, HEIGHT, DEPTH, MAXVAL must all be positive integers')
+ return 'P7', width, height, depth, maxval
+
+def read_pnm_header(infile, supported=('P5','P6')):
+ """
+ Read a PNM header, returning (format,width,height,depth,maxval).
+ `width` and `height` are in pixels. `depth` is the number of
+ channels in the image; for PBM and PGM it is synthesized as 1, for
+ PPM as 3; for PAM images it is read from the header. `maxval` is
+ synthesized (as 1) for PBM images.
+ """
+
+ # Generally, see http://netpbm.sourceforge.net/doc/ppm.html
+ # and http://netpbm.sourceforge.net/doc/pam.html
+
+ supported = [strtobytes(x) for x in supported]
+
+ # Technically 'P7' must be followed by a newline, so by using
+ # rstrip() we are being liberal in what we accept. I think this
+ # is acceptable.
+ type = infile.read(3).rstrip()
+ if type not in supported:
+ raise NotImplementedError('file format %s not supported' % type)
+ if type == strtobytes('P7'):
+ # PAM header parsing is completely different.
+ return read_pam_header(infile)
+ # Expected number of tokens in header (3 for P4, 4 for P6)
+ expected = 4
+ pbm = ('P1', 'P4')
+ if type in pbm:
+ expected = 3
+ header = [type]
+
+ # We have to read the rest of the header byte by byte because the
+ # final whitespace character (immediately following the MAXVAL in
+ # the case of P6) may not be a newline. Of course all PNM files in
+ # the wild use a newline at this point, so it's tempting to use
+ # readline; but it would be wrong.
+ def getc():
+ c = infile.read(1)
+ if not c:
+ raise Error('premature EOF reading PNM header')
+ return c
+
+ c = getc()
+ while True:
+ # Skip whitespace that precedes a token.
+ while c.isspace():
+ c = getc()
+ # Skip comments.
+ while c == '#':
+ while c not in '\n\r':
+ c = getc()
+ if not c.isdigit():
+ raise Error('unexpected character %s found in header' % c)
+ # According to the specification it is legal to have comments
+ # that appear in the middle of a token.
+ # This is bonkers; I've never seen it; and it's a bit awkward to
+ # code good lexers in Python (no goto). So we break on such
+ # cases.
+ token = strtobytes('')
+ while c.isdigit():
+ token += c
+ c = getc()
+ # Slight hack. All "tokens" are decimal integers, so convert
+ # them here.
+ header.append(int(token))
+ if len(header) == expected:
+ break
+ # Skip comments (again)
+ while c == '#':
+ while c not in '\n\r':
+ c = getc()
+ if not c.isspace():
+ raise Error('expected header to end with whitespace, not %s' % c)
+
+ if type in pbm:
+ # synthesize a MAXVAL
+ header.append(1)
+ depth = (1,3)[type == strtobytes('P6')]
+ return header[0], header[1], header[2], depth, header[3]
+
+def write_pnm(file, width, height, pixels, meta):
+ """Write a Netpbm PNM/PAM file."""
+
+ bitdepth = meta['bitdepth']
+ maxval = 2**bitdepth - 1
+ # Rudely, the number of image planes can be used to determine
+ # whether we are L (PGM), LA (PAM), RGB (PPM), or RGBA (PAM).
+ planes = meta['planes']
+ # Can be an assert as long as we assume that pixels and meta came
+ # from a PNG file.
+ assert planes in (1,2,3,4)
+ if planes in (1,3):
+ if 1 == planes:
+ # PGM
+ # Could generate PBM if maxval is 1, but we don't (for one
+ # thing, we'd have to convert the data, not just blat it
+ # out).
+ fmt = 'P5'
+ else:
+ # PPM
+ fmt = 'P6'
+ file.write('%s %d %d %d\n' % (fmt, width, height, maxval))
+ if planes in (2,4):
+ # PAM
+ # See http://netpbm.sourceforge.net/doc/pam.html
+ if 2 == planes:
+ tupltype = 'GRAYSCALE_ALPHA'
+ else:
+ tupltype = 'RGB_ALPHA'
+ file.write('P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\n'
+ 'TUPLTYPE %s\nENDHDR\n' %
+ (width, height, planes, maxval, tupltype))
+ # Values per row
+ vpr = planes * width
+ # struct format
+ fmt = '>%d' % vpr
+ if maxval > 0xff:
+ fmt = fmt + 'H'
+ else:
+ fmt = fmt + 'B'
+ for row in pixels:
+ file.write(struct.pack(fmt, *row))
+ file.flush()
+
+def color_triple(color):
+ """
+ Convert a command line colour value to a RGB triple of integers.
+ FIXME: Somewhere we need support for greyscale backgrounds etc.
+ """
+ if color.startswith('#') and len(color) == 4:
+ return (int(color[1], 16),
+ int(color[2], 16),
+ int(color[3], 16))
+ if color.startswith('#') and len(color) == 7:
+ return (int(color[1:3], 16),
+ int(color[3:5], 16),
+ int(color[5:7], 16))
+ elif color.startswith('#') and len(color) == 13:
+ return (int(color[1:5], 16),
+ int(color[5:9], 16),
+ int(color[9:13], 16))
+
+
+def _main(argv):
+ """
+ Run the PNG encoder with options from the command line.
+ """
+
+ # Parse command line arguments
+ from optparse import OptionParser
+ import re
+ version = '%prog ' + re.sub(r'( ?\$|URL: |Rev:)', '', __version__)
+ parser = OptionParser(version=version)
+ parser.set_usage("%prog [options] [imagefile]")
+ parser.add_option('-r', '--read-png', default=False,
+ action='store_true',
+ help='Read PNG, write PNM')
+ parser.add_option("-i", "--interlace",
+ default=False, action="store_true",
+ help="create an interlaced PNG file (Adam7)")
+ parser.add_option("-t", "--transparent",
+ action="store", type="string", metavar="color",
+ help="mark the specified colour (#RRGGBB) as transparent")
+ parser.add_option("-b", "--background",
+ action="store", type="string", metavar="color",
+ help="save the specified background colour")
+ parser.add_option("-a", "--alpha",
+ action="store", type="string", metavar="pgmfile",
+ help="alpha channel transparency (RGBA)")
+ parser.add_option("-g", "--gamma",
+ action="store", type="float", metavar="value",
+ help="save the specified gamma value")
+ parser.add_option("-c", "--compression",
+ action="store", type="int", metavar="level",
+ help="zlib compression level (0-9)")
+ parser.add_option("-T", "--test",
+ default=False, action="store_true",
+ help="create a test image (a named PngSuite image if an argument is supplied)")
+ parser.add_option('-L', '--list',
+ default=False, action='store_true',
+ help="print list of named test images")
+ parser.add_option("-R", "--test-red",
+ action="store", type="string", metavar="pattern",
+ help="test pattern for the red image layer")
+ parser.add_option("-G", "--test-green",
+ action="store", type="string", metavar="pattern",
+ help="test pattern for the green image layer")
+ parser.add_option("-B", "--test-blue",
+ action="store", type="string", metavar="pattern",
+ help="test pattern for the blue image layer")
+ parser.add_option("-A", "--test-alpha",
+ action="store", type="string", metavar="pattern",
+ help="test pattern for the alpha image layer")
+ parser.add_option("-K", "--test-black",
+ action="store", type="string", metavar="pattern",
+ help="test pattern for greyscale image")
+ parser.add_option("-d", "--test-depth",
+ default=8, action="store", type="int",
+ metavar='NBITS',
+ help="create test PNGs that are NBITS bits per channel")
+ parser.add_option("-S", "--test-size",
+ action="store", type="string", metavar="w[,h]",
+ help="width and height of the test image")
+ (options, args) = parser.parse_args(args=argv[1:])
+
+ # Convert options
+ if options.transparent is not None:
+ options.transparent = color_triple(options.transparent)
+ if options.background is not None:
+ options.background = color_triple(options.background)
+
+ if options.list:
+ names = list(_pngsuite)
+ names.sort()
+ for name in names:
+ print(name)
+ return
+
+ # Run regression tests
+ if options.test:
+ return test_suite(options, args)
+
+ # Prepare input and output files
+ if len(args) == 0:
+ infilename = '-'
+ infile = sys.stdin
+ elif len(args) == 1:
+ infilename = args[0]
+ infile = open(infilename, 'rb')
+ else:
+ parser.error("more than one input file")
+ outfile = sys.stdout
+ if sys.platform == "win32":
+ import msvcrt, os
+ msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
+
+ if options.read_png:
+ # Encode PNG to PPM
+ png = Reader(file=infile)
+ width,height,pixels,meta = png.asDirect()
+ write_pnm(outfile, width, height, pixels, meta)
+ else:
+ # Encode PNM to PNG
+ format, width, height, depth, maxval = \
+ read_pnm_header(infile, ('P5','P6','P7'))
+ # When it comes to the variety of input formats, we do something
+ # rather rude. Observe that L, LA, RGB, RGBA are the 4 colour
+ # types supported by PNG and that they correspond to 1, 2, 3, 4
+ # channels respectively. So we use the number of channels in
+ # the source image to determine which one we have. We do not
+ # care about TUPLTYPE.
+ greyscale = depth <= 2
+ pamalpha = depth in (2,4)
+ supported = [2**x-1 for x in range(1,17)]
+ try:
+ mi = supported.index(maxval)
+ except ValueError:
+ raise NotImplementedError(
+ 'your maxval (%s) not in supported list %s' %
+ (maxval, str(supported)))
+ bitdepth = mi+1
+ writer = Writer(width, height,
+ greyscale=greyscale,
+ bitdepth=bitdepth,
+ interlace=options.interlace,
+ transparent=options.transparent,
+ background=options.background,
+ alpha=bool(pamalpha or options.alpha),
+ gamma=options.gamma,
+ compression=options.compression)
+ if options.alpha:
+ pgmfile = open(options.alpha, 'rb')
+ format, awidth, aheight, adepth, amaxval = \
+ read_pnm_header(pgmfile, 'P5')
+ if amaxval != '255':
+ raise NotImplementedError(
+ 'maxval %s not supported for alpha channel' % amaxval)
+ if (awidth, aheight) != (width, height):
+ raise ValueError("alpha channel image size mismatch"
+ " (%s has %sx%s but %s has %sx%s)"
+ % (infilename, width, height,
+ options.alpha, awidth, aheight))
+ writer.convert_ppm_and_pgm(infile, pgmfile, outfile)
+ else:
+ writer.convert_pnm(infile, outfile)
+
+
+if __name__ == '__main__':
+ try:
+ _main(sys.argv)
+ except Error as e:
+ print(e, file=sys.stderr)
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/rgba.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/rgba.py
new file mode 100644
index 0000000..b17f03f
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/rgba.py
@@ -0,0 +1,340 @@
+"""
+RGBA.
+
+Licensed under MIT
+Copyright (c) 2012 - 2016 Isaac Muse
+"""
+import re
+from colorsys import rgb_to_hls, hls_to_rgb, rgb_to_hsv, hsv_to_rgb
+import decimal
+
+RGB_CHANNEL_SCALE = 1.0 / 255.0
+HUE_SCALE = 1.0 / 360.0
+PERCENT_TO_CHANNEL = 255.0 / 100.0
+CHANNEL_TO_PERCENT = 100.0 / 255.0
+SCALE_PERCENT = 1 / 100.0
+SCALE_HALF_PERCENT = 1 / 50.0
+
+
+def mix_channel(cf, af, cb, ab):
+ """
+ Mix the color channel.
+
+ cf: Channel foreground
+ af: Alpha foreground
+ cb: Channel background
+ ab: Alpha background
+
+ The foreground is overlayed on the secondary color it is to be mixed with.
+ The alpha channels are applied and the colors mix.
+ """
+
+ return clamp(
+ round_int(
+ abs(
+ cf * (af * RGB_CHANNEL_SCALE) + cb * (ab * RGB_CHANNEL_SCALE) * (1 - (af * RGB_CHANNEL_SCALE))
+ )
+ ),
+ 0, 255
+ )
+
+
+def clamp(value, mn, mx):
+ """Clamp the value to the the given minimum and maximum."""
+
+ return max(min(value, mx), mn)
+
+
+def round_int(dec):
+ """Round float to nearest int using expected rounding."""
+
+ return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_DOWN))
+
+
+class RGBA(object):
+ """RGBA object for converting between color formats or applying filters to the color."""
+
+ r = None
+ g = None
+ b = None
+ a = None
+ color_pattern = re.compile(r"^#(?:([A-Fa-f\d]{6})([A-Fa-f\d]{2})?|([A-Fa-f\d]{3}))")
+
+ def __init__(self, s=None):
+ """Initialize."""
+
+ if s is None:
+ s = "#000000FF"
+ self.r, self.g, self.b, self.a = self._split_channels(s)
+
+ def _split_channels(self, s):
+ """Split the color into color channels: red, green, blue, alpha."""
+
+ def alpha_channel(alpha):
+ """Get alpha channel."""
+ return int(alpha, 16) if alpha else 0xFF
+
+ m = self.color_pattern.match(s)
+ assert(m is not None)
+ if m.group(1):
+ return int(s[1:3], 16), int(s[3:5], 16), int(s[5:7], 16), alpha_channel(m.group(2))
+ else:
+ return int(s[1] * 2, 16), int(s[2] * 2, 16), int(s[3] * 2, 16), 0xFF
+
+ def get_rgba(self):
+ """Get the RGB color with the alpha channel."""
+
+ return "#%02X%02X%02X%02X" % (self.r, self.g, self.b, self.a)
+
+ def get_rgb(self):
+ """Get the RGB valuie."""
+
+ return "#%02X%02X%02X" % (self.r, self.g, self.b)
+
+ def apply_alpha(self, background="#000000FF"):
+ """
+ Apply the given transparency with the given background.
+
+ This gives a color that represents what the eye sees with
+ the transparent color against the given background.
+ """
+
+ if self.a < 0xFF:
+ r, g, b, a = self._split_channels(background)
+
+ self.r = mix_channel(self.r, self.a, r, a)
+ self.g = mix_channel(self.g, self.a, g, a)
+ self.b = mix_channel(self.b, self.a, b, a)
+
+ return self.get_rgb()
+
+ def get_luminance(self):
+ """Get percieved luminance."""
+
+ return clamp(round_int(0.299 * self.r + 0.587 * self.g + 0.114 * self.b), 0, 255)
+
+ def get_true_luminance(self):
+ """Get true liminance."""
+
+ l = self.tohls()[1]
+ return clamp(round_int(l * 255.0), 0, 255)
+
+ def alpha(self, factor):
+ """Adjust alpha."""
+
+ self.a = round_int(clamp(self.a + (255.0 * factor) - 255.0, 0.0, 255.0))
+
+ def red(self, factor):
+ """Adjust red."""
+
+ self.r = round_int(clamp(self.r + (255.0 * factor) - 255.0, 0.0, 255.0))
+
+ def green(self, factor):
+ """Adjust green."""
+
+ self.g = round_int(clamp(self.g + (255.0 * factor) - 255.0, 0.0, 255.0))
+
+ def blue(self, factor):
+ """Adjust blue."""
+
+ self.b = round_int(clamp(self.b + (255.0 * factor) - 255.0, 0.0, 255.0))
+
+ def blend(self, color, percent, alpha=False):
+ """Blend color."""
+
+ factor = clamp(round_int(clamp(float(percent), 0.0, 100.0) * PERCENT_TO_CHANNEL), 0, 255)
+ r, g, b, a = self._split_channels(color)
+
+ self.r = mix_channel(self.r, factor, r, 255)
+ self.g = mix_channel(self.g, factor, g, 255)
+ self.b = mix_channel(self.b, factor, b, 255)
+ if alpha:
+ self.a = mix_channel(self.a, factor, a, 255)
+
+ def luminance(self, factor):
+ """Get true luminance."""
+
+ h, l, s = self.tohls()
+ l = clamp(l + factor - 1.0, 0.0, 1.0)
+ self.fromhls(h, l, s)
+
+ def tohsv(self):
+ """Convert to HSV color format."""
+
+ return rgb_to_hsv(self.r * RGB_CHANNEL_SCALE, self.g * RGB_CHANNEL_SCALE, self.b * RGB_CHANNEL_SCALE)
+
+ def fromhsv(self, h, s, v):
+ """Convert to RGB from HSV."""
+
+ r, g, b = hsv_to_rgb(h, s, v)
+ self.r = clamp(round_int(r * 255.0), 0, 255)
+ self.g = clamp(round_int(g * 255.0), 0, 255)
+ self.b = clamp(round_int(b * 255.0), 0, 255)
+
+ def tohls(self):
+ """Convert to HLS color format."""
+
+ return rgb_to_hls(self.r * RGB_CHANNEL_SCALE, self.g * RGB_CHANNEL_SCALE, self.b * RGB_CHANNEL_SCALE)
+
+ def fromhls(self, h, l, s):
+ """Convert to RGB from HSL."""
+
+ r, g, b = hls_to_rgb(h, l, s)
+ self.r = clamp(round_int(r * 255.0), 0, 255)
+ self.g = clamp(round_int(g * 255.0), 0, 255)
+ self.b = clamp(round_int(b * 255.0), 0, 255)
+
+ def tohwb(self):
+ """Convert to HWB from RGB."""
+
+ h, s, v = self.tohsv()
+ w = (1.0 - s) * v
+ b = 1.0 - v
+ return h, w, b
+
+ def fromhwb(self, h, w, b):
+ """Convert to RGB from HWB."""
+
+ # Normalize white and black
+ # w + b <= 1.0
+ if w + b > 1.0:
+ norm_factor = 1.0 / (w + b)
+ w *= norm_factor
+ b *= norm_factor
+
+ # Convert to HSV and then to RGB
+ s = 1.0 - (w / (1.0 - b))
+ v = 1.0 - b
+ r, g, b = hsv_to_rgb(h, s, v)
+ self.r = clamp(round_int(r * 255.0), 0, 255)
+ self.g = clamp(round_int(g * 255.0), 0, 255)
+ self.b = clamp(round_int(b * 255.0), 0, 255)
+
+ def colorize(self, deg):
+ """Colorize the color with the given hue."""
+
+ h, l, s = self.tohls()
+ h = clamp(deg * HUE_SCALE, 0.0, 1.0)
+ self.fromhls(h, l, s)
+
+ def hue(self, deg):
+ """Shift the hue."""
+
+ d = deg * HUE_SCALE
+ h, l, s = self.tohls()
+ h = h + d
+ while h > 1.0:
+ h -= 1.0
+ while h < 0.0:
+ h += 1.0
+ self.fromhls(h, l, s)
+
+ def contrast(self, factor):
+ """Adjust contrast."""
+
+ # Algorithm can't handle any thing beyond +/-255 (or a factor from 0 - 2)
+ # Convert factor between (-255, 255)
+ f = (clamp(factor, 0.0, 2.0) - 1.0) * 255.0
+ f = (259 * (f + 255)) / (255 * (259 - f))
+
+ # Increase/decrease contrast accordingly.
+ self.r = clamp(round_int((f * (self.r - 128)) + 128), 0, 255)
+ self.g = clamp(round_int((f * (self.g - 128)) + 128), 0, 255)
+ self.b = clamp(round_int((f * (self.b - 128)) + 128), 0, 255)
+
+ def invert(self):
+ """Invert the color."""
+
+ self.r ^= 0xFF
+ self.g ^= 0xFF
+ self.b ^= 0xFF
+
+ def saturation(self, factor):
+ """Saturate or unsaturate the color by the given factor."""
+
+ h, l, s = self.tohls()
+ s = clamp(s + factor - 1.0, 0.0, 1.0)
+ self.fromhls(h, l, s)
+
+ def grayscale(self):
+ """Convert the color with a grayscale filter."""
+
+ luminance = self.get_luminance()
+ self.r = luminance
+ self.g = luminance
+ self.b = luminance
+
+ def sepia(self):
+ """Apply a sepia filter to the color."""
+
+ r = clamp(round_int((self.r * .393) + (self.g * .769) + (self.b * .189)), 0, 255)
+ g = clamp(round_int((self.r * .349) + (self.g * .686) + (self.b * .168)), 0, 255)
+ b = clamp(round_int((self.r * .272) + (self.g * .534) + (self.b * .131)), 0, 255)
+ self.r, self.g, self.b = r, g, b
+
+ def _get_overage(self, c):
+ """Get overage."""
+
+ if c < 0.0:
+ o = 0.0 + c
+ c = 0.0
+ elif c > 255.0:
+ o = c - 255.0
+ c = 255.0
+ else:
+ o = 0.0
+ return o, c
+
+ def _distribute_overage(self, c, o, s):
+ """Distribute overage."""
+
+ channels = len(s)
+ if channels == 0:
+ return c
+ parts = o / len(s)
+ if "r" in s and "g" in s:
+ c = c[0] + parts, c[1] + parts, c[2]
+ elif "r" in s and "b" in s:
+ c = c[0] + parts, c[1], c[2] + parts
+ elif "g" in s and "b" in s:
+ c = c[0], c[1] + parts, c[2] + parts
+ elif "r" in s:
+ c = c[0] + parts, c[1], c[2]
+ elif "g" in s:
+ c = c[0], c[1] + parts, c[2]
+ else: # "b" in s:
+ c = c[0], c[1], c[2] + parts
+ return c
+
+ def brightness(self, factor):
+ """
+ Adjust the brightness by the given factor.
+
+ Brightness is determined by percieved luminance.
+ """
+
+ channels = ["r", "g", "b"]
+ total_lumes = clamp(self.get_luminance() + (255.0 * factor) - 255.0, 0.0, 255.0)
+
+ if total_lumes == 255.0:
+ # white
+ self.r, self.g, self.b = 0xFF, 0xFF, 0xFF
+ elif total_lumes == 0.0:
+ # black
+ self.r, self.g, self.b = 0x00, 0x00, 0x00
+ else:
+ # Adjust Brightness
+ pts = (total_lumes - 0.299 * self.r - 0.587 * self.g - 0.114 * self.b)
+ slots = set(channels)
+ components = [float(self.r) + pts, float(self.g) + pts, float(self.b) + pts]
+ count = 0
+ for c in channels:
+ overage, components[count] = self._get_overage(components[count])
+ if overage:
+ slots.remove(c)
+ components = list(self._distribute_overage(components, overage, slots))
+ count += 1
+
+ self.r = clamp(round_int(components[0]), 0, 255)
+ self.g = clamp(round_int(components[1]), 0, 255)
+ self.b = clamp(round_int(components[2]), 0, 255)
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_clean_css.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_clean_css.py
new file mode 100644
index 0000000..5016d9e
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_clean_css.py
@@ -0,0 +1,39 @@
+"""
+File Strip.
+
+Licensed under MIT
+Copyright (c) 2012 - 2016 Isaac Muse
+"""
+import re
+
+LINE_PRESERVE = re.compile(r"\r?\n", re.MULTILINE)
+CSS_PATTERN = re.compile(
+ r'''(?x)
+ (?P
+ /\*[^*]*\*+(?:[^/*][^*]*\*+)*/ # multi-line comments
+ )
+ | (?P
+ "(?:\\.|[^"\\])*" # double quotes
+ | '(?:\\.|[^'\\])*' # single quotes
+ | .[^/"']* # everything else
+ )
+ ''',
+ re.DOTALL
+)
+
+
+def clean_css(text, preserve_lines=False):
+ """Clean css."""
+
+ def remove_comments(group, preserve_lines=False):
+ """Remove comments."""
+
+ return ''.join([x[0] for x in LINE_PRESERVE.findall(group)]) if preserve_lines else ''
+
+ def evaluate(m, preserve_lines):
+ """Search for comments."""
+
+ g = m.groupdict()
+ return g["code"] if g["code"] is not None else remove_comments(g["comments"], preserve_lines)
+
+ return ''.join(map(lambda m: evaluate(m, preserve_lines), CSS_PATTERN.finditer(text.replace('\r', ''))))
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_code_highlight.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_code_highlight.py
new file mode 100644
index 0000000..aa32ebb
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_code_highlight.py
@@ -0,0 +1,279 @@
+"""
+SublimeHighlight.
+
+Licensed under MIT.
+
+Copyright (C) 2012 Andrew Gibson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
+to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of
+the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------
+
+Original code has been heavily modifed by Isaac Muse for the ExportHtml project.
+"""
+import sublime
+import re
+from .st_color_scheme_matcher import ColorSchemeMatcher
+from .st_mapping import lang_map
+
+NEW_SCHEMES = int(sublime.version()) >= 3150
+
+INLINE_BODY_START = ''
+BODY_START = '
\n'
+INLINE_BODY_END = ''
+ST_LANGUAGES = ('.sublime-syntax', '.tmLanguage')
+
+
+class SublimeHighlight(object):
+ """SublimeHighlight."""
+
+ def __init__(self, scheme):
+ """Initialization."""
+
+ self.view = None
+
+ if not NEW_SCHEMES:
+ self.csm = ColorSchemeMatcher(scheme)
+
+ self.fground = self.csm.get_special_color('foreground', simulate_transparency=True)
+ self.bground = self.csm.get_special_color('background', simulate_transparency=True)
+
+ def setup(self, **kwargs):
+ """Get get general document preferences from sublime preferences."""
+
+ self.tab_size = 4
+ self.size = self.view.size()
+ self.pt = 0
+ self.end = 0
+ self.curr_row = 0
+ # self.ebground = self.bground
+
+ def setup_print_block(self, curr_sel, multi=False):
+ """Determine start and end points and whether to parse whole file or selection."""
+
+ self.size = self.view.size()
+ self.pt = 0
+ self.end = 1
+ self.curr_row = 1
+ self.start_line = self.curr_row
+
+ def print_line(self, line, num):
+ """Print the line."""
+
+ html_line = (INLINE_LINE if self.inline else LINE) % {
+ "code": line,
+ }
+
+ return html_line
+
+ def convert_view_to_html(self):
+ """Begin conversion of the view to HTML."""
+
+ for line in self.view.split_by_newlines(sublime.Region(self.pt, self.size)):
+ self.char_count = 0
+ self.size = line.end()
+ empty = not bool(line.size())
+ line = self.convert_line_to_html(empty)
+ self.html.append(self.print_line(line, self.curr_row))
+ self.curr_row += 1
+
+ def html_encode(self, text):
+ """Format text to HTML."""
+
+ new_text = []
+ for c in text:
+ if c == '\t':
+ tab_size = self.tab_size - self.char_count % self.tab_size
+ new_text.append(' ' * tab_size)
+ self.char_count += tab_size
+ elif c == '&':
+ new_text.append('&')
+ self.char_count += 1
+ elif c == '>':
+ new_text.append('>')
+ self.char_count += 1
+ elif c == '<':
+ new_text.append('<')
+ self.char_count += 1
+ elif c != '\n':
+ new_text.append(c)
+ self.char_count += 1
+
+ return re.sub(
+ (r'(?!\s($|\S))\s' if self.inline or self.code_wrap else r'\s'),
+ ' ',
+ ''.join(new_text)
+ )
+
+ def format_text(self, line, text, color, bgcolor, style, empty, annotate=False):
+ """Format the text."""
+
+ if empty:
+ text = ' '
+
+ css_style = ''
+ if style and 'bold' in style:
+ css_style += ' font-weight: bold;'
+ if style and 'italic' in style:
+ css_style += ' font-style: italic;'
+
+ if bgcolor is None:
+ code = CODE % {
+ "color": color, "content": text, "style": css_style
+ }
+ else:
+ code = CODEBG % {
+ "highlight": bgcolor, "color": color, "content": text, "style": css_style
+ }
+
+ line.append(code)
+
+ def convert_line_to_html(self, empty):
+ """Convert the line to its HTML representation."""
+
+ line = []
+ do_highlight = self.curr_row in self.hl_lines
+
+ while self.end <= self.size:
+ # Get text of like scope
+ scope_name = self.view.scope_name(self.pt)
+ while self.view.scope_name(self.end) == scope_name and self.end < self.size:
+ self.end += 1
+ if NEW_SCHEMES:
+ color_match = self.view.style_for_scope(scope_name)
+ color = color_match.get('foreground', self.fground)
+ bgcolor = color_match.get('background')
+ style = []
+ if color_match['bold']:
+ style.append('bold')
+ if color_match['italic']:
+ style.append('italic')
+ if do_highlight:
+ sfg = color_match.get('selection_forground', self.defaults.get('selection_forground'))
+ if sfg:
+ color = sfg
+ bgcolor = color_match.get('selection', '#0000FF')
+ else:
+ color_match = self.csm.guess_color(scope_name, selected=do_highlight, explicit_background=True)
+ color = color_match.fg_simulated
+ bgcolor = color_match.bg_simulated
+ style = color_match.style.split(' ')
+
+ region = sublime.Region(self.pt, self.end)
+ # Normal text formatting
+ tidied_text = self.html_encode(self.view.substr(region))
+ self.format_text(line, tidied_text, color, bgcolor, style, empty)
+
+ # Continue walking through line
+ self.pt = self.end
+ self.end = self.pt + 1
+
+ # # Get the color for the space at the end of a line
+ # if self.end < self.view.size():
+ # end_key = self.view.scope_name(self.pt)
+ # if NEW_SCHEMES:
+ # color_match = self.view.style_for_scope(end_key)
+ # self.ebground = color_match.get('background')
+ # else:
+ # color_match = self.csm.guess_color(end_key, explicit_background=True)
+ # self.ebground = color_match.bg_simulated
+
+ # Join line segments
+ return ''.join(line)
+
+ def write_body(self):
+ """Write the body of the HTML."""
+
+ processed_rows = ""
+ if not self.no_wrap:
+ self.html.append(INLINE_BODY_START if self.inline else BODY_START)
+
+ # Convert view to HTML
+ self.setup_print_block(self.view.sel()[0])
+ processed_rows += "[" + str(self.curr_row) + ","
+ self.convert_view_to_html()
+ processed_rows += str(self.curr_row) + "],"
+
+ # Write empty line to allow copying of last line and line number without issue
+ if not self.no_wrap:
+ self.html.append(INLINE_BODY_END if self.inline else BODY_END)
+
+ def set_view(self, src, lang):
+ """Setup view for conversion."""
+
+ # Get the output panel
+ self.view = sublime.active_window().create_output_panel('mdpopups', unlisted=True)
+ # Let all plugins no to leave this view alone
+ self.view.settings().set('is_widget', True)
+ # Don't translate anything.
+ self.view.settings().set("translate_tabs_to_spaces", False)
+ # Don't mess with my indenting Sublime!
+ self.view.settings().set("auto_indent", False)
+ # Insert into the view
+ self.view.run_command('insert', {'characters': src})
+ # Setup the proper syntax
+ lang = lang.lower()
+ user_map = sublime.load_settings('Preferences.sublime-settings').get('mdpopups.sublime_user_lang_map', {})
+ keys = set(list(user_map.keys()) + list(lang_map.keys()))
+ loaded = False
+ for key in keys:
+ v = lang_map.get(key, (tuple(), tuple()))
+ user_v = user_map.get(key, (tuple(), tuple()))
+ if lang in (tuple(user_v[0]) + v[0]):
+ for l in (tuple(user_v[1]) + v[1]):
+ for ext in ST_LANGUAGES:
+ sytnax_file = 'Packages/%s%s' % (l, ext)
+ try:
+ sublime.load_binary_resource(sytnax_file)
+ except Exception:
+ continue
+ self.view.set_syntax_file(sytnax_file)
+ loaded = True
+ break
+ if loaded:
+ break
+ if loaded:
+ break
+ if not loaded:
+ # Default to plain text
+ for ext in ST_LANGUAGES:
+ # Just in case text one day switches to 'sublime-syntax'
+ sytnax_file = 'Packages/Plain text%s' % ext
+ try:
+ sublime.load_binary_resource(sytnax_file)
+ except Exception:
+ continue
+ self.view.set_syntax_file(sytnax_file)
+
+ def syntax_highlight(self, src, lang, hl_lines=[], inline=False, no_wrap=False, code_wrap=False):
+ """Syntax Highlight."""
+
+ self.set_view(src, 'text' if not lang else lang)
+ if NEW_SCHEMES:
+ self.defaults = self.view.style()
+ self.fground = self.defaults.get('foreground', '#000000')
+ self.bground = self.defaults.get('background', '#FFFFFF')
+ self.inline = inline
+ self.hl_lines = hl_lines
+ self.no_wrap = no_wrap
+ self.code_wrap = code_wrap
+ self.setup()
+ self.html = []
+ self.write_body()
+ return ''.join(self.html)
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_color_scheme_matcher.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_color_scheme_matcher.py
new file mode 100644
index 0000000..ddbaf8a
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_color_scheme_matcher.py
@@ -0,0 +1,806 @@
+"""
+color_scheme_matcher.
+
+Licensed under MIT.
+
+Copyright (C) 2012 Andrew Gibson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
+to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of
+the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+---------------------
+
+Original code has been heavily modifed by Isaac Muse for the ExportHtml project.
+Algorithm has been split out into a separate library and been enhanced with a number of features.
+"""
+from __future__ import absolute_import
+import sublime
+import codecs
+import re
+from .file_strip.json import sanitize_json
+from .rgba import RGBA, clamp, round_int
+from . import x11colors
+from os import path
+from collections import namedtuple
+from plistlib import readPlistFromBytes
+import decimal
+
+NEW_SCHEMES = int(sublime.version()) >= 3150
+FONT_STYLE = "font_style" if int(sublime.version()) >= 3151 else "fontStyle"
+GLOBAL_OPTIONS = "globals" if int(sublime.version()) >= 3152 else "defaults"
+
+# XML
+XML_COMMENT_RE = re.compile(br"^[\r\n\s]*[\s\r\n]*|")
+
+# For new Sublime format
+FLOAT_TRIM_RE = re.compile(r'^(?P\d+)(?P\.0+|(?P\.\d*[1-9])0+)$')
+
+COLOR_PARTS = {
+ "percent": r"[+\-]?(?:(?:\d*\.\d+)|\d+)%",
+ "float": r"[+\-]?(?:(?:\d*\.\d+)|\d+)"
+}
+
+RGB_COLORS = r"""(?x)
+ (?P\#(?P[\dA-Fa-f]{8}))\b |
+ (?P\#(?P[\dA-Fa-f]{6}))\b |
+ (?P\#(?P[\dA-Fa-f]{4}))\b |
+ (?P\#(?P[\dA-Fa-f]{3}))\b |
+ \b(?Prgb\(\s*(?P(?:%(float)s\s*,\s*){2}%(float)s | (?:%(percent)s\s*,\s*){2}%(percent)s)\s*\)) |
+ \b(?Prgba\(\s*(?P
+ (?:%(float)s\s*,\s*){3}(?:%(percent)s|%(float)s) | (?:%(percent)s\s*,\s*){3}(?:%(percent)s|%(float)s)
+ )\s*\))
+""" % COLOR_PARTS
+
+HSL_COLORS = r"""(?x)
+ \b(?Phsl\(\s*(?P%(float)s\s*,\s*%(percent)s\s*,\s*%(percent)s)\s*\)) |
+ \b(?Phsla\(\s*(?P%(float)s\s*,\s*(?:%(percent)s\s*,\s*){2}(?:%(percent)s|%(float)s))\s*\))
+""" % COLOR_PARTS
+
+VARIABLES = r"""(?x)
+ \b(?Pvar\(\s*(?P[-\w][-\w\d]*)\s*\))
+"""
+
+COLOR_MOD = r"""(?x)
+ \b(?Pcolor\((?P.*)\))
+"""
+
+COLOR_NAMES = r'\b(?P%s)\b(?!\()' % '|'.join([name for name in x11colors.name2hex_map.keys()])
+
+COLOR_RE = re.compile(
+ r'(?x)(?i)(?:%s|%s|%s|%s|%s)' % (
+ RGB_COLORS,
+ HSL_COLORS,
+ VARIABLES,
+ COLOR_MOD,
+ COLOR_NAMES
+ )
+)
+
+COLOR_RGB_SPACE_RE = re.compile(
+ r'(?x)(?i)(?:%s|%s|%s)' % (
+ RGB_COLORS,
+ VARIABLES,
+ COLOR_NAMES
+ )
+)
+
+COLOR_MOD_RE = re.compile(
+ r'''(?x)
+ color\(\s*
+ (?P\#[\dA-Fa-f]{8}|\#[\dA-Fa-f]{6})
+ \s+(?Pblenda?)\(
+ (?P\#[\dA-Fa-f]{8}|\#[\dA-Fa-f]{6})
+ \s+(?P%(percent)s)
+ \)
+ (?P
+ (?:\s+blenda?\((?:\#[\dA-Fa-f]{8}|\#[\dA-Fa-f]{6})\s+%(percent)s\))+
+ )?
+ \s*\)
+ ''' % COLOR_PARTS
+)
+
+RE_CAMEL_CASE = re.compile('[A-Z]')
+
+
+def packages_path(pth):
+ """Get packages path."""
+
+ return path.join(path.dirname(sublime.packages_path()), path.normpath(pth))
+
+
+def to_snake(m):
+ """Convert to snake case."""
+
+ return '_' + m.group(0).lower()
+
+
+def fmt_float(f, p=0):
+ """Set float precision and trim precision zeros."""
+
+ string = str(
+ decimal.Decimal(f).quantize(decimal.Decimal('0.' + ('0' * p) if p > 0 else '0'), decimal.ROUND_HALF_UP)
+ )
+
+ m = FLOAT_TRIM_RE.match(string)
+ if m:
+ string = m.group('keep')
+ if m.group('keep2'):
+ string += m.group('keep2')
+ return string
+
+
+def alpha_dec_normalize(dec):
+ """Normailze a deciaml alpha value."""
+
+ temp = float(dec)
+ if temp < 0.0 or temp > 1.0:
+ dec = fmt_float(clamp(float(temp), 0.0, 1.0), 3)
+ alpha = "%02x" % round_int(float(dec) * 255.0)
+ return alpha
+
+
+def alpha_percent_normalize(perc):
+ """Normailze a percent alpha value."""
+
+ alpha_float = clamp(float(perc.strip('%')), 0.0, 100.0) / 100.0
+ alpha = "%02x" % round_int(alpha_float * 255.0)
+ return alpha
+
+
+def blend(m):
+ """Blend colors."""
+
+ base = m.group('base')
+ color = m.group('color')
+ blend_type = m.group('type')
+ percent = m.group('percent')
+ if percent.endswith('%'):
+ percent = float(percent.strip('%'))
+ else:
+ percent = int(alpha_dec_normalize(percent), 16) * (100.0 / 255.0)
+ rgba = RGBA(base)
+ rgba.blend(color, percent, alpha=(blend_type == 'blenda'))
+ color = rgba.get_rgb() if rgba.a == 255 else rgba.get_rgba()
+ if m.group('other'):
+ color = "color(%s %s)" % (color, m.group('other'))
+ return color
+
+
+def translate_color(m, var, var_src):
+ """Translate the match object to a color w/ alpha."""
+
+ color = None
+ alpha = None
+ if m is not None:
+ groups = m.groupdict()
+ if groups.get('hex_compressed'):
+ content = m.group('hex_compressed_content')
+ color = "#%02x%02x%02x" % (
+ int(content[0:1] * 2, 16), int(content[1:2] * 2, 16), int(content[2:3] * 2, 16)
+ )
+ elif groups.get('hexa_compressed'):
+ content = m.group('hexa_compressed_content')
+ color = "#%02x%02x%02x" % (
+ int(content[0:1] * 2, 16), int(content[1:2] * 2, 16), int(content[2:3] * 2, 16)
+ )
+ alpha = content[3:]
+ elif groups.get('hex'):
+ content = m.group('hex_content')
+ if len(content) == 6:
+ color = "#%02x%02x%02x" % (
+ int(content[0:2], 16), int(content[2:4], 16), int(content[4:6], 16)
+ )
+ else:
+ color = "#%02x%02x%02x" % (
+ int(content[0:1] * 2, 16), int(content[1:2] * 2, 16), int(content[2:3] * 2, 16)
+ )
+ elif groups.get('hexa'):
+ content = m.group('hexa_content')
+ if len(content) == 8:
+ color = "#%02x%02x%02x" % (
+ int(content[0:2], 16), int(content[2:4], 16), int(content[4:6], 16)
+ )
+ alpha = content[6:]
+ else:
+ color = "#%02x%02x%02x" % (
+ int(content[0:1] * 2, 16), int(content[1:2] * 2, 16), int(content[2:3] * 2, 16)
+ )
+ alpha = content[3:]
+ elif groups.get('rgb'):
+ content = [x.strip() for x in m.group('rgb_content').split(',')]
+ if content[0].endswith('%'):
+ r = round_int(clamp(float(content[0].strip('%')), 0.0, 255.0) * (255.0 / 100.0))
+ g = round_int(clamp(float(content[1].strip('%')), 0.0, 255.0) * (255.0 / 100.0))
+ b = round_int(clamp(float(content[2].strip('%')), 0.0, 255.0) * (255.0 / 100.0))
+ color = "#%02x%02x%02x" % (r, g, b)
+ else:
+ color = "#%02x%02x%02x" % (
+ clamp(round_int(float(content[0])), 0, 255),
+ clamp(round_int(float(content[1])), 0, 255),
+ clamp(round_int(float(content[2])), 0, 255)
+ )
+ elif groups.get('rgba'):
+ content = [x.strip() for x in m.group('rgba_content').split(',')]
+ if content[0].endswith('%'):
+ r = round_int(clamp(float(content[0].strip('%')), 0.0, 255.0) * (255.0 / 100.0))
+ g = round_int(clamp(float(content[1].strip('%')), 0.0, 255.0) * (255.0 / 100.0))
+ b = round_int(clamp(float(content[2].strip('%')), 0.0, 255.0) * (255.0 / 100.0))
+ color = "#%02x%02x%02x" % (r, g, b)
+ else:
+ color = "#%02x%02x%02x" % (
+ clamp(round_int(float(content[0])), 0, 255),
+ clamp(round_int(float(content[1])), 0, 255),
+ clamp(round_int(float(content[2])), 0, 255)
+ )
+ if content[3].endswith('%'):
+ alpha = alpha_percent_normalize(content[3])
+ else:
+ alpha = alpha_dec_normalize(content[3])
+ elif groups.get('hsl'):
+ content = [x.strip() for x in m.group('hsl_content').split(',')]
+ rgba = RGBA()
+ hue = float(content[0])
+ if hue < 0.0 or hue > 360.0:
+ hue = hue % 360.0
+ h = hue / 360.0
+ s = clamp(float(content[1].strip('%')), 0.0, 100.0) / 100.0
+ l = clamp(float(content[2].strip('%')), 0.0, 100.0) / 100.0
+ rgba.fromhls(h, l, s)
+ color = rgba.get_rgb()
+ elif groups.get('hsla'):
+ content = [x.strip() for x in m.group('hsla_content').split(',')]
+ rgba = RGBA()
+ hue = float(content[0])
+ if hue < 0.0 or hue > 360.0:
+ hue = hue % 360.0
+ h = hue / 360.0
+ s = clamp(float(content[1].strip('%')), 0.0, 100.0) / 100.0
+ l = clamp(float(content[2].strip('%')), 0.0, 100.0) / 100.0
+ rgba.fromhls(h, l, s)
+ color = rgba.get_rgb()
+ if content[3].endswith('%'):
+ alpha = alpha_percent_normalize(content[3])
+ else:
+ alpha = alpha_dec_normalize(content[3])
+ elif groups.get('var'):
+ content = m.group('var_content')
+ if content in var:
+ color = var[content]
+ else:
+ v = var_src[content]
+ m = COLOR_RE.match(v.strip())
+ color = translate_color(m, var, var_src)
+ elif groups.get('x11colors'):
+ try:
+ color = x11colors.name2hex(m.group('x11colors')).lower()
+ except Exception:
+ pass
+ elif groups.get('color'):
+ content = m.group('color')
+ try:
+ content = COLOR_RGB_SPACE_RE.sub(
+ (lambda match, v=var, vs=var_src: translate_color(match, v, vs)), content
+ )
+ n = -1
+ while n:
+ content, n = COLOR_MOD_RE.subn(blend, content)
+ color = content
+ except Exception:
+ pass
+
+ if color is not None and alpha is not None:
+ color += alpha
+
+ return color
+
+
+def sublime_format_path(pth):
+ """Format path for sublime internal use."""
+
+ m = re.match(r"^([A-Za-z]{1}):(?:/|\\)(.*)", pth)
+ if sublime.platform() == "windows" and m is not None:
+ pth = m.group(1) + "/" + m.group(2)
+ return pth.replace("\\", "/")
+
+
+class SchemeColors(
+ namedtuple(
+ 'SchemeColors',
+ [
+ 'fg', 'fg_simulated', 'bg', "bg_simulated", "style", "color_gradient",
+ "fg_selector", "bg_selector", "style_selectors", "color_gradient_selector"
+ ],
+ verbose=False
+ )
+):
+ """SchemeColors."""
+
+
+class SchemeSelectors(namedtuple('SchemeSelectors', ['name', 'scope'], verbose=False)):
+ """SchemeSelectors."""
+
+
+class ColorSchemeMatcher(object):
+ """Determine color scheme colors and style for text in a Sublime view buffer."""
+
+ def __init__(self, scheme_file, color_filter=None):
+ """Initialize."""
+ if color_filter is None:
+ color_filter = self.filter
+ self.color_scheme = scheme_file.replace('\\', '/')
+ self.scheme_file = path.basename(self.color_scheme)
+
+ if NEW_SCHEMES and scheme_file.endswith(('.sublime-color-scheme', '.hidden-color-scheme')):
+ self.legacy = False
+ self.scheme_obj = {
+ 'variables': {},
+ GLOBAL_OPTIONS: {},
+ 'rules': []
+ }
+ else:
+ try:
+ content = sublime.load_binary_resource(sublime_format_path(self.color_scheme))
+ except IOError:
+ # Fallback if file was created manually and not yet found in resources
+ with open(packages_path(self.color_scheme), 'rb') as f:
+ content = f.read()
+ self.legacy = True
+ self.convert_format(readPlistFromBytes(XML_COMMENT_RE.sub(b'', content)))
+ self.overrides = []
+ if NEW_SCHEMES:
+ self.merge_overrides()
+ self.scheme_file = scheme_file
+ self.matched = {}
+ self.variables = {}
+ self.parse_scheme()
+ self.scheme_obj = color_filter(self.scheme_obj)
+ self.setup_matcher()
+
+ def convert_format(self, obj):
+ """Convert tmTheme object to new format."""
+
+ self.scheme_obj = {
+ "variables": {},
+ GLOBAL_OPTIONS: {},
+ "rules": []
+ }
+
+ for k, v in obj.items():
+ if k == "settings":
+ continue
+ self.scheme_obj[k] = v
+
+ for item in obj["settings"]:
+ if item.get('scope', None) is None and item.get('name', None) is None:
+ for k, v in item["settings"].items():
+ self.scheme_obj[GLOBAL_OPTIONS][RE_CAMEL_CASE.sub(to_snake, k)] = v
+ if 'settings' in item and item.get('scope') is not None:
+ rule = {}
+ name = item.get('name')
+ if name is not None:
+ rule['name'] = name
+ scope = item.get('scope')
+ if scope is not None:
+ rule["scope"] = scope
+ fg = item['settings'].get('foreground')
+ if fg is not None:
+ rule['foreground'] = item['settings'].get('foreground')
+ bg = item['settings'].get('background')
+ if bg is not None:
+ rule['background'] = bg
+ selfg = item["settings"].get("selectionForeground")
+ if selfg is not None:
+ rule["selection_foreground"] = selfg
+ font_style = item["settings"].get('fontStyle')
+ if font_style is not None:
+ rule[FONT_STYLE] = font_style
+ self.scheme_obj['rules'].append(rule)
+
+ def merge_overrides(self):
+ """Merge override schemes."""
+
+ package_overrides = []
+ user_overrides = []
+ if self.scheme_file.endswith('.hidden-color-scheme'):
+ pattern = '%s.hidden-color-scheme'
+ else:
+ pattern = '%s.sublime-color-scheme'
+ for override in sublime.find_resources(pattern % path.splitext(self.scheme_file)[0]):
+ if override.startswith('Packages/User/'):
+ user_overrides.append(override)
+ else:
+ package_overrides.append(override)
+ for override in (package_overrides + user_overrides):
+ try:
+ ojson = sublime.decode_value(sublime.load_resource(override))
+ except IOError:
+ # Fallback if file was created manually and not yet found in resources
+ # Though it is unlikely this would ever get executed as `find_resources`
+ # probably wouldn't have seen it either.
+ with codecs.open(packages_path(override), 'r', encoding='utf-8') as f:
+ ojson = sublime.decode_value(sanitize_json(f.read()))
+
+ for k, v in ojson.get('variables', {}).items():
+ self.scheme_obj['variables'][k] = v
+
+ for k, v in ojson.get(GLOBAL_OPTIONS, {}).items():
+ self.scheme_obj[GLOBAL_OPTIONS][k] = v
+
+ for item in ojson.get('rules', []):
+ self.scheme_obj['rules'].append(item)
+
+ self.overrides.append(override)
+
+ # Rare case of being given a file but sublime hasn't indexed the files and can't find it
+ if (
+ not self.overrides and
+ self.color_scheme.endswith(('.sublime-color-scheme', '.hidden-color-scheme')) and
+ self.color_scheme.startswith('Packages/')
+ ):
+ with codecs.open(packages_path(self.color_scheme), 'r', encoding='utf-8') as f:
+ ojson = sublime.decode_value(sanitize_json(f.read()))
+
+ for k, v in ojson.get('variables', {}).items():
+ self.scheme_obj['variables'][k] = v
+
+ for k, v in ojson.get(GLOBAL_OPTIONS, {}).items():
+ self.scheme_obj[GLOBAL_OPTIONS][k] = v
+
+ for item in ojson.get('rules', []):
+ self.scheme_obj['rules'].append(item)
+
+ self.overrides.append(self.color_scheme)
+
+ def filter(self, scheme): # noqa A003
+ """Dummy filter call that does nothing."""
+
+ return scheme
+
+ def parse_scheme(self):
+ """Parse the color scheme."""
+
+ variables = self.scheme_obj.get('variables', {})
+ for k, v in variables.items():
+ m = COLOR_RE.match(v.strip())
+ var = translate_color(m, self.variables, self.scheme_obj.get('variables')) if m is not None else ""
+ if var is None:
+ var = ""
+ self.variables[k] = var
+ variables[k] = var
+
+ global_options = self.scheme_obj[GLOBAL_OPTIONS]
+ for k, v in global_options.items():
+ m = COLOR_RE.match(v.strip())
+ if m is not None:
+ global_color = translate_color(m, self.variables, {})
+ if global_color is not None:
+ global_options[k] = global_color
+
+ # Create scope colors mapping from color scheme file
+ for item in self.scheme_obj["rules"]:
+ if item.get('scope', None) is not None:
+ # Foreground color
+ color = item.get('foreground', None)
+ if isinstance(color, list):
+ # Hashed Syntax Highlighting
+ for index, c in enumerate(color):
+ color[index] = translate_color(COLOR_RE.match(c.strip()), self.variables, {})
+ elif isinstance(color, str):
+ item['foreground'] = translate_color(COLOR_RE.match(color.strip()), self.variables, {})
+ # Background color
+ bgcolor = item.get('background', None)
+ if isinstance(bgcolor, str):
+ item['background'] = translate_color(COLOR_RE.match(bgcolor.strip()), self.variables, {})
+ # Selection foreground color
+ scolor = item.get('selection_foreground', None)
+ if isinstance(scolor, str):
+ item['selection_foreground'] = translate_color(COLOR_RE.match(scolor.strip()), self.variables, {})
+
+ def setup_matcher(self):
+ """Setup colors for color matcher."""
+
+ color_settings = {}
+ global_options = self.scheme_obj[GLOBAL_OPTIONS]
+ for k, v in global_options.items():
+ if v.startswith('#'):
+ color_settings[k] = v
+
+ # Get general theme colors from color scheme file
+ bground, bground_sim = self.process_color(
+ color_settings.get("background", '#FFFFFF'), simple_strip=True
+ )
+
+ # Need to set background so other colors can simulate their transparency.
+ self.special_colors = {
+ "background": {'color': bground, 'color_simulated': bground_sim}
+ }
+
+ fground, fground_sim = self.process_color(color_settings.get("foreground", '#000000'))
+ sbground, sbground_sim = self.process_color(color_settings.get("selection", "#0000FF"))
+ sfground, sfground_sim = self.process_color(color_settings.get("selection_foreground", None))
+ gbground = self.process_color(color_settings.get("gutter", bground))[0]
+ gbground_sim = self.process_color(color_settings.get("gutter", bground_sim))[1]
+ gfground = self.process_color(color_settings.get("gutter_foreground", fground))[0]
+ gfground_sim = self.process_color(color_settings.get("gutter_foreground", fground_sim))[1]
+
+ self.special_colors["foreground"] = {'color': fground, 'color_simulated': fground_sim}
+ self.special_colors["background"] = {'color': bground, 'color_simulated': bground_sim}
+ self.special_colors["selection_foreground"] = {'color': sfground, 'color_simulated': sfground_sim}
+ self.special_colors["selection"] = {'color': sbground, 'color_simulated': sbground_sim}
+ self.special_colors["gutter"] = {'color': gbground, 'color_simulated': gbground_sim}
+ self.special_colors["gutter_foreground"] = {'color': gfground, 'color_simulated': gfground_sim}
+ self.colors = {}
+ # Create scope colors mapping from color scheme file
+ for item in self.scheme_obj["rules"]:
+ name = item.get('name', '')
+ scope = item.get('scope', None)
+ color = None
+ bgcolor = None
+ scolor = None
+ style = []
+ if scope is not None:
+ # Foreground color
+ color = item.get('foreground', None)
+ # Background color
+ bgcolor = item.get('background', None)
+ # Selection foreground color
+ scolor = item.get('selection_foreground', None)
+ # Font style
+ if FONT_STYLE in item:
+ for s in item.get(FONT_STYLE, '').split(' '):
+ if s == "bold" or s == "italic": # or s == "underline":
+ style.append(s)
+
+ self.add_entry(name, scope, color, bgcolor, scolor, style)
+
+ def add_entry(self, name, scope, color, bgcolor, scolor, style):
+ """Add color entry."""
+
+ color_gradient = None
+ if isinstance(color, list):
+ fg, fg_sim, color_gradient = self.process_color_gradient(color)
+ elif color is not None:
+ fg, fg_sim = self.process_color(color)
+ else:
+ fg, fg_sim = None, None
+ if bgcolor is not None:
+ bg, bg_sim = self.process_color(bgcolor)
+ else:
+ bg, bg_sim = None, None
+ if scolor is not None:
+ sfg, sfg_sim = self.process_color(
+ scolor, bground=self.special_colors["selection"]['color_simulated']
+ )
+ else:
+ sfg, sfg_sim = None, None
+ self.colors[scope] = {
+ "name": name,
+ "scope": scope,
+ "color": fg,
+ "color_simulated": fg_sim,
+ "color_gradient": color_gradient,
+ "bgcolor": bg,
+ "bgcolor_simulated": bg_sim,
+ "selection_color": sfg,
+ "selection_color_simulated": sfg_sim,
+ "style": style
+ }
+
+ def process_color_gradient(self, colors, simple_strip=False, bground=None):
+ """
+ Strip transparency from the color gradient list.
+
+ Transparency can be stripped in one of two ways:
+ - Simply mask off the alpha channel.
+ - Apply the alpha channel to the color essential getting the color seen by the eye.
+ """
+
+ gradient = []
+
+ for color in colors:
+ if color is None or color.strip() == "":
+ continue
+
+ if not color.startswith('#'):
+ continue
+
+ rgba = RGBA(color.replace(" ", ""))
+ if not simple_strip:
+ if bground is None:
+ bground = self.special_colors['background']['color_simulated']
+ rgba.apply_alpha(bground if bground != "" else "#FFFFFF")
+
+ gradient.append((color, rgba.get_rgb()))
+ if gradient:
+ color, color_sim = gradient[0]
+ return color, color_sim, gradient
+ else:
+ return None, None, None
+
+ def process_color(self, color, simple_strip=False, bground=None):
+ """
+ Strip transparency from the color value.
+
+ Transparency can be stripped in one of two ways:
+ - Simply mask off the alpha channel.
+ - Apply the alpha channel to the color essential getting the color seen by the eye.
+ """
+
+ if color is None or color.strip() == "":
+ return None, None
+
+ if not color.startswith('#'):
+ return None, None
+
+ rgba = RGBA(color.replace(" ", ""))
+ if not simple_strip:
+ if bground is None:
+ bground = self.special_colors['background']['color_simulated']
+ rgba.apply_alpha(bground if bground != "" else "#FFFFFF")
+
+ return color, rgba.get_rgb()
+
+ def get_special_color(self, name, simulate_transparency=False):
+ """
+ Get the core colors (background, foreground) for the view and gutter.
+
+ Get the visible look of the color by simulated transparency if requrested.
+ """
+
+ name = RE_CAMEL_CASE.sub(to_snake, name)
+ return self.special_colors.get(name, {}).get('color_simulated' if simulate_transparency else 'color')
+
+ def get_scheme_obj(self):
+ """Get the scheme file used during the process."""
+
+ return self.scheme_obj
+
+ def get_scheme_file(self):
+ """Get the scheme file used during the process."""
+
+ return self.scheme_file
+
+ def guess_color(self, scope_key, selected=False, explicit_background=False):
+ """
+ Guess the colors and style of the text for the given Sublime scope.
+
+ By default, we always fall back to the schemes default background,
+ but if desired, we can show that no background was explicitly
+ specified by returning None. This is done by enabling explicit_background.
+ This will only show backgrounds that were explicitly specified.
+
+ This was orginially introduced for mdpopups so that it would
+ know when a background was not needed. This allowed mdpopups
+ to generate syntax highlighted code that could be overlayed on
+ block elements with different background colors and allow that
+ background would show through.
+ """
+
+ color = self.special_colors['foreground']['color']
+ color_sim = self.special_colors['foreground']['color_simulated']
+ color_gradient = None
+ color_gradient_selector = None
+ bgcolor = self.special_colors['background']['color'] if not explicit_background else None
+ bgcolor_sim = self.special_colors['background']['color_simulated'] if not explicit_background else None
+ scolor = self.special_colors['selection_foreground']['color']
+ scolor_sim = self.special_colors['selection_foreground']['color_simulated']
+ style = set([])
+ color_selector = SchemeSelectors("foreground", "foreground")
+ bg_selector = SchemeSelectors("background", "background")
+ scolor_selector = SchemeSelectors("selection_foreground", "selection_foreground")
+ style_selectors = {"bold": SchemeSelectors("", ""), "italic": SchemeSelectors("", "")}
+ if scope_key in self.matched:
+ color = self.matched[scope_key]["color"]
+ color_sim = self.matched[scope_key]["color_simulated"]
+ color_gradient = self.matched[scope_key]["color_gradient"]
+ style = self.matched[scope_key]["style"]
+ bgcolor = self.matched[scope_key]["bgcolor"]
+ bgcolor_sim = self.matched[scope_key]["bgcolor_simulated"]
+ scolor = self.matched[scope_key]["scolor"]
+ scolor_sim = self.matched[scope_key]["scolor_simulated"]
+ selectors = self.matched[scope_key]["selectors"]
+ color_selector = selectors["color"]
+ bg_selector = selectors["background"]
+ scolor_selector = selectors["scolor"]
+ style_selectors = selectors["style"]
+ color_gradient_selector = selectors['color_gradient']
+ else:
+ best_match_bg = 0
+ best_match_fg = 0
+ best_match_style = 0
+ best_match_sfg = 0
+ best_match_fg_gradient = 0
+ for key in self.colors:
+ match = sublime.score_selector(scope_key, key)
+ if (
+ not self.colors[key]['color_gradient'] and
+ self.colors[key]["color"] is not None and
+ match > best_match_fg
+ ):
+ best_match_fg = match
+ color = self.colors[key]["color"]
+ color_sim = self.colors[key]["color_simulated"]
+ color_selector = SchemeSelectors(self.colors[key]["name"], self.colors[key]["scope"])
+ if (
+ self.colors[key]["color"] is not None and
+ match > best_match_fg_gradient
+ ):
+ best_match_fg_gradient = match
+ color_gradient = self.colors[key]["color_gradient"]
+ color_gradient_selector = SchemeSelectors(self.colors[key]["name"], self.colors[key]["scope"])
+ if self.colors[key]["selection_color"] is not None and match > best_match_sfg:
+ best_match_sfg = match
+ scolor = self.colors[key]["selection_color"]
+ scolor_sim = self.colors[key]["selection_color_simulated"]
+ scolor_selector = SchemeSelectors(self.colors[key]["name"], self.colors[key]["scope"])
+ if self.colors[key]["style"] is not None and match > best_match_style:
+ best_match_style = match
+ for s in self.colors[key]["style"]:
+ style.add(s)
+ if s == "bold":
+ style_selectors["bold"] = SchemeSelectors(
+ self.colors[key]["name"], self.colors[key]["scope"]
+ )
+ elif s == "italic":
+ style_selectors["italic"] = SchemeSelectors(
+ self.colors[key]["name"], self.colors[key]["scope"]
+ )
+ if self.colors[key]["bgcolor"] is not None and match > best_match_bg:
+ best_match_bg = match
+ bgcolor = self.colors[key]["bgcolor"]
+ bgcolor_sim = self.colors[key]["bgcolor_simulated"]
+ bg_selector = SchemeSelectors(self.colors[key]["name"], self.colors[key]["scope"])
+
+ if len(style) == 0:
+ style = ""
+ else:
+ style = ' '.join(style)
+
+ if not isinstance(color_gradient, list):
+ color_gradient = None
+ color_gradient_selector = None
+
+ self.matched[scope_key] = {
+ "color": color,
+ "bgcolor": bgcolor,
+ "scolor": scolor,
+ "color_simulated": color_sim,
+ "bgcolor_simulated": bgcolor_sim,
+ "scolor_simulated": scolor_sim,
+ "color_gradient": color_gradient,
+ "style": style,
+ "selectors": {
+ "color": color_selector,
+ "background": bg_selector,
+ "scolor": scolor_selector,
+ "style": style_selectors,
+ "color_gradient": color_gradient_selector
+ }
+ }
+
+ if selected:
+ if scolor:
+ color = scolor
+ color_sim = scolor_sim
+ color_selector = scolor_selector
+ color_gradient = None
+ color_gradient_selector = None
+ if self.special_colors['selection']['color']:
+ bgcolor = self.special_colors['selection']['color']
+ bgcolor_sim = self.special_colors['selection']['color_simulated']
+ bg_selector = SchemeSelectors("selection", "selection")
+
+ return SchemeColors(
+ color, color_sim, bgcolor, bgcolor_sim, style, color_gradient,
+ color_selector, bg_selector, style_selectors, color_gradient_selector
+ )
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_mapping.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_mapping.py
new file mode 100644
index 0000000..cedca12
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_mapping.py
@@ -0,0 +1,55 @@
+"""Sublime Text language mapping."""
+
+lang_map = {
+ # 'name': (('mapping_alias',), ('tmLanguage_or_sublime-syntax file',))
+ 'actionscript': (('as', 'actionscript',), ('ActionScript/ActionScript',)),
+ 'applescript': (('applescript',), ('AppleScript/AppleScript',)),
+ 'asp': (('asp',), ('ASP/ASP',)),
+ 'bash': (('bash', 'sh', 'ksh', 'shell'), ('ShellScript/Shell-Unix-Generic',)),
+ 'batch': (('batch', 'bat', 'dosbatch', 'winbatch'), ('Batch File/Batch File',)),
+ 'c': (('c',), ('C++/C',)),
+ 'c++': (('c++', 'cpp'), ('C++/C++',)),
+ 'c#': (('csharp', 'c#'), ('C#/C#',)),
+ 'clojure': (('clojure', 'clj'), ('Clojure/Clojure',)),
+ 'cmake': (('cmake',), ('CMake/CMake',)),
+ 'css': (('css',), ('CSS/CSS',)),
+ 'd': (('d',), ('D/D',)),
+ 'diff': (('diff',), ('Diff/Diff',)),
+ 'erlang': (('erlang',), ('Erlang/Erlang',)),
+ 'go': (('go',), ('Go/Go',)),
+ 'groovy': (('groovy',), ('Groovy/Groovy',)),
+ 'haskell': (('haskell', 'hs'), ('Haskell/Haskell',)),
+ 'html': (('html',), ('HTML/HTML',)),
+ 'java': (('java',), ('Java/Java',)),
+ 'javascript': (('javascript', 'js'), ('JavaScript/JavaScript', 'JavaScriptNext - ES6 Syntax/JavaScriptNext')),
+ 'json': (('json',), ('JavaScript/JSON', 'JavaScriptNext - ES6 Syntax/JSON (JavaScriptNext)')),
+ 'jsp': (('jsp',), ('Java/Java Server Pages (JSP)',)),
+ 'less': (('less',), ('LESS/LESS', 'LessImproved/LESS')),
+ 'lisp': (('common-lisp', 'cl', 'lisp', 'emacs', 'elisp'), ('Lisp/Lisp',)),
+ 'lua': (('lua',), ('Lua/Lua',)),
+ 'markdown': (('markdown', 'md'), ('Markdown/Markdown',)),
+ 'makefile': (('makefile', 'make', 'mf', 'bsdmake'), ('Makefile/Makefile',)),
+ 'matlab': (('matlab', 'octave'), ('Matlab/Matlab',)),
+ 'objective-c': (('objective-c', 'objectivec', 'obj-c', 'objc'), ('Objective-C/Objective-C',)),
+ 'objective-c++': (('objective-c++', 'objectivec++', 'obj-c++', 'objc++'), ('Objective-C/Objective-C++',)),
+ 'ocaml': (('ocaml',), ('OCaml/OCaml',)),
+ 'pascal': (('delphi', 'pas', 'pascal', 'objectpascal'), ('Pascal/Pascal',)),
+ 'perl': (('perl', 'pl'), ('Perl/Perl', 'ModernPerl/ModernPerl')),
+ 'php': (('php', 'php3', 'php4', 'php5'), ('PHP/PHP',)),
+ 'python': (('python', 'py'), ('Python/Python', 'MagicPython/grammars/MagicPython')),
+ 's': (('splus', 's', 'r'), ('R/R',)),
+ 'sql': (('sql',), ('SQL/SQL',)),
+ 'tcl': (('tcl',), ('TCL/Tcl',)),
+ 'regex': (('regex', 'regexp'), ('Regular Expressions/RegExp',)),
+ 'railshtml': (('rhtml', 'html+erb', 'html+ruby'), ('Rails/HTML (Rails)',)),
+ 'railsjs': (('js+erb', 'javascript+erb', 'js+ruby', 'javascript+ruby'), ('Rails/JavaScript (Rails)',)),
+ 'rst': (('rst', 'rest', 'restructuredtext'), ('RestructuredText/reStructuredText',)),
+ 'ruby': (('rb', 'ruby'), ('Ruby/Ruby',)),
+ 'scala': (('scala',), ('Scala/Scala',)),
+ 'tex': (('tex', 'latex'), ('LaTeX/LaTeX',)),
+ 'text': (('text',), ('Text/Plain text',)),
+ 'textile': (('textile',), ('Textile/Textile',)),
+ 'typescript': (('typescript', 'ts'), ('TypeScript/TypeScript', 'TypeScriptSyntax/TypeScript')),
+ 'xml': (('xml',), ('XML/XML',)),
+ 'yaml': (('yaml',), ('YAML/YAML',))
+}
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_pygments_highlight.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_pygments_highlight.py
new file mode 100644
index 0000000..24b0cdf
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_pygments_highlight.py
@@ -0,0 +1,187 @@
+"""
+Sublime code highlighting for tooltips.
+
+Licensed under MIT
+Copyright (c) 2015 - 2016 Isaac Muse
+"""
+import re
+from pygments import highlight
+from pygments.lexers import get_lexer_by_name, guess_lexer
+from pygments.formatters import find_formatter_class
+HtmlFormatter = find_formatter_class('html')
+pygments = True
+
+html_re = re.compile(
+ r'''(?x)
+ (?P]+>)|(?P[^<>]+)|(?P)
+ '''
+)
+
+multi_space = re.compile(r'(?<= ) {2,}')
+
+
+def replace_nbsp(m):
+ """Replace spaces with nbsp."""
+
+ return ' ' * len(m.group(0))
+
+
+class SublimeWrapBlockFormatter(HtmlFormatter):
+ """Format the code blocks."""
+
+ def wrap(self, source, outfile):
+ """Overload wrap."""
+
+ return self._wrap_code(source)
+
+ def _wrap_code(self, source):
+ """
+ Wrap the pygmented code.
+
+ Sublime popups don't really support 'pre', but since it doesn't
+ hurt anything, we leave it in for the possiblity of future support.
+ We get around the lack of proper 'pre' suppurt by converting any
+ spaces after the intial space to nbsp. We go ahead and convert tabs
+ to 4 spaces as well. We also manually inject line breaks.
+ """
+
+ yield 0, '
' % self.cssclass
+ for i, t in source:
+ text = ''
+ matched = False
+ for m in html_re.finditer(t):
+ matched = True
+ if m.group(1):
+ text += m.group(1)
+ elif m.group(3):
+ text += m.group(3)
+ else:
+ text += multi_space.sub(
+ replace_nbsp, m.group(2).replace('\t', ' ' * 4)
+ ).replace(''', '\'').replace('"', '"')
+ if not matched:
+ text = multi_space.sub(
+ replace_nbsp, t.replace('\t', ' ' * 4)
+ ).replace(''', '\'').replace('"', '"')
+ if i == 1:
+ # it's a line of formatted code
+ text += ' '
+ yield i, text
+ yield 0, '
'
+
+
+class SublimeBlockFormatter(HtmlFormatter):
+ """Format the code blocks with wrapping."""
+
+ def wrap(self, source, outfile):
+ """Overload wrap."""
+
+ return self._wrap_code(source)
+
+ def _wrap_code(self, source):
+ """
+ Wrap the pygmented code.
+
+ Sublime popups don't really support 'pre', but since it doesn't
+ hurt anything, we leave it in for the possiblity of future support.
+ We get around the lack of proper 'pre' suppurt by converting any
+ spaces after the intial space to nbsp. We go ahead and convert tabs
+ to 4 spaces as well. We also manually inject line breaks.
+ """
+
+ yield 0, '
' % self.cssclass
+ for i, t in source:
+ text = ''
+ matched = False
+ for m in html_re.finditer(t):
+ matched = True
+ if m.group(1):
+ text += m.group(1)
+ elif m.group(3):
+ text += m.group(3)
+ else:
+ text += m.group(2).replace(
+ '\t', ' ' * 4
+ ).replace(' ', ' ').replace(''', '\'').replace('"', '"')
+ if not matched:
+ text = t.replace('\t', ' ' * 4).replace(
+ ' ', ' '
+ ).replace(''', '\'').replace('"', '"')
+ if i == 1:
+ # it's a line of formatted code
+ text += ' '
+ yield i, text
+ yield 0, '
'
+
+
+class SublimeInlineHtmlFormatter(HtmlFormatter):
+ """Format the code blocks."""
+
+ def wrap(self, source, outfile):
+ """Overload wrap."""
+
+ return self._wrap_code(source)
+
+ def _wrap_code(self, source):
+ """
+ Wrap the pygmented code.
+
+ Sublime popups don't really support 'code', but since it doesn't
+ hurt anything, we leave it in for the possiblity of future support.
+ We get around the lack of proper 'code' support by converting any
+ spaces after the intial space to nbsp. We go ahead and convert tabs
+ to 4 spaces as well.
+ """
+
+ yield 0, '' % self.cssclass
+ for i, t in source:
+ text = ''
+ matched = False
+ for m in html_re.finditer(t):
+ matched = True
+ if m.group(1):
+ text += m.group(1)
+ elif m.group(3):
+ text += m.group(3)
+ else:
+ text += multi_space.sub(
+ replace_nbsp, m.group(2).replace('\t', ' ' * 4)
+ ).replace(''', '\'').replace('"', '"')
+ if not matched:
+ text = multi_space.sub(
+ replace_nbsp, t.replace('\t', ' ' * 4)
+ ).replace(''', '\'').replace('"', '"')
+ yield i, text
+ yield 0, ''
+
+
+def syntax_hl(src, lang=None, guess_lang=False, inline=False, code_wrap=False):
+ """Highlight."""
+
+ css_class = 'highlight'
+
+ src = src.strip('\n')
+
+ try:
+ lexer = get_lexer_by_name(lang)
+ except ValueError:
+ try:
+ if guess_lang:
+ lexer = guess_lexer(src)
+ else:
+ lexer = get_lexer_by_name('text')
+ except ValueError:
+ lexer = get_lexer_by_name('text')
+ if inline:
+ formatter = SublimeInlineHtmlFormatter(
+ cssclass=css_class
+ )
+ elif code_wrap:
+ formatter = SublimeWrapBlockFormatter(
+ cssclass=css_class
+ )
+ else:
+ formatter = SublimeBlockFormatter(
+ cssclass=css_class
+ )
+ return highlight(src, lexer, formatter)
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_scheme_template.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_scheme_template.py
new file mode 100644
index 0000000..fb6d09c
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/st_scheme_template.py
@@ -0,0 +1,469 @@
+"""
+Sublime Text Scheme template.
+
+Converts scheme to css provides templating for
+additonal so that they can access the colors.
+
+Licensed under MIT
+Copyright (c) 2015 - 2016 Isaac Muse
+
+----------------------
+
+TextMate theme to CSS.
+
+https://manual.macromates.com/en/language_grammars#naming_conventions
+"""
+import sublime
+import re
+from . import version as ver
+from .rgba import RGBA
+from .st_color_scheme_matcher import ColorSchemeMatcher
+import jinja2
+from pygments.formatters import HtmlFormatter
+from collections import OrderedDict
+from .st_clean_css import clean_css
+import copy
+import decimal
+
+NEW_SCHEMES = int(sublime.version()) >= 3150
+
+INVALID = -1
+POPUP = 0
+PHANTOM = 1
+LUM_MIDPOINT = 127
+
+re_float_trim = re.compile(r'^(?P\d+)(?P\.0+|(?P\.\d*[1-9])0+)$')
+re_valid_custom_scopes = re.compile(r'[a-zA-Z\d]+[a-zA-Z\d._\-]*')
+re_missing_semi_colon = re.compile(r'(? 0 else '0'), decimal.ROUND_HALF_UP)
+ )
+
+ m = re_float_trim.match(string)
+ if m:
+ string = m.group('keep')
+ if m.group('keep2'):
+ string += m.group('keep2')
+ return string
+
+
+class SchemeTemplate(object):
+ """Determine color scheme colors and style for text in a Sublime view buffer."""
+
+ def __init__(self, scheme_file):
+ """Initialize."""
+
+ self.scheme_file = scheme_file
+ self.css_type = INVALID
+ self.variable = {}
+ self.view = None
+ self.setup()
+
+ def guess_style(self, view, scope, selected=False, explicit_background=False):
+ """Guess color."""
+
+ # Remove leading '.' to account for old style CSS class scopes.
+ if not NEW_SCHEMES:
+ return self.csm.guess_color(scope.lstrip('.'), selected, explicit_background)
+ else:
+ scope_style = view.style_for_scope(scope.lstrip('.'))
+ style = {}
+ style['foreground'] = scope_style['foreground']
+ style['background'] = scope_style.get('background')
+ style['bold'] = scope_style['bold']
+ style['italic'] = scope_style['italic']
+
+ defaults = view.style()
+ if not explicit_background and not style.get('background'):
+ style['background'] = defaults.get('background', '#FFFFFF')
+ if selected:
+ sfg = scope_style.get('selection_forground', defaults.get('selection_forground'))
+ if sfg:
+ style['foreground'] = sfg
+ style['background'] = scope_style.get('selection', '#0000FF')
+ return style
+
+ def legacy_parse_global(self):
+ """
+ Parse global settings.
+
+ LEGACY.
+ """
+
+ self.csm = ColorSchemeMatcher(self.scheme_file)
+
+ # Get general theme colors from color scheme file
+ self.bground = self.csm.special_colors['background']['color_simulated']
+ rgba = RGBA(self.bground)
+ self.lums = rgba.get_true_luminance()
+ is_dark = self.lums <= LUM_MIDPOINT
+ self._variables = {
+ "is_dark": is_dark,
+ "is_light": not is_dark,
+ "sublime_version": int(sublime.version()),
+ "mdpopups_version": ver.version(),
+ "color_scheme": self.scheme_file,
+ "use_pygments": self.use_pygments,
+ "default_style": self.default_style
+ }
+ self.html_border = rgba.get_rgb()
+ self.fground = self.csm.special_colors['foreground']['color_simulated']
+
+ def get_variables(self):
+ """Get variables."""
+
+ if NEW_SCHEMES:
+ is_dark = self.is_dark()
+ return {
+ "is_dark": is_dark,
+ "is_light": not is_dark,
+ "sublime_version": int(sublime.version()),
+ "mdpopups_version": ver.version(),
+ "color_scheme": self.scheme_file,
+ "use_pygments": self.use_pygments,
+ "default_style": self.default_style
+ }
+ else:
+ return self._variables
+
+ def get_html_border(self):
+ """Get html border."""
+
+ return self.get_bg() if NEW_SCHEMES else self.html_border
+
+ def is_dark(self):
+ """Check if scheme is dark."""
+
+ return self.get_lums() <= LUM_MIDPOINT
+
+ def get_lums(self):
+ """Get luminance."""
+
+ if NEW_SCHEMES:
+ bg = self.get_bg()
+ rgba = RGBA(bg)
+ return rgba.get_true_luminance()
+ else:
+ return self.lums
+
+ def get_fg(self):
+ """Get foreground."""
+
+ return self.view.style().get('foreground', '#000000') if NEW_SCHEMES else self.fground
+
+ def get_bg(self):
+ """Get backtround."""
+
+ return self.view.style().get('background', '#FFFFFF') if NEW_SCHEMES else self.bground
+
+ def setup(self):
+ """Setup the template environment."""
+
+ settings = sublime.load_settings("Preferences.sublime-settings")
+ self.use_pygments = not settings.get('mdpopups.use_sublime_highlighter', True)
+ self.default_style = settings.get('mdpopups.default_style', True)
+
+ if not NEW_SCHEMES:
+ self.legacy_parse_global()
+
+ # Create Jinja template
+ self.env = jinja2.Environment()
+ self.env.filters['css'] = self.retrieve_selector
+ self.env.filters['pygments'] = self.pygments
+ self.env.filters['foreground'] = self.to_fg
+ self.env.filters['background'] = self.to_bg
+ self.env.filters['brightness'] = self.brightness
+ self.env.filters['colorize'] = self.colorize
+ self.env.filters['hue'] = self.hue
+ self.env.filters['invert'] = self.invert
+ self.env.filters['saturation'] = self.saturation
+ self.env.filters['contrast'] = self.contrast
+ self.env.filters['grayscale'] = self.grayscale
+ self.env.filters['sepia'] = self.sepia
+ self.env.filters['fade'] = self.fade
+ self.env.filters['getcss'] = self.read_css
+
+ def read_css(self, css):
+ """Read the CSS file."""
+
+ try:
+ var = copy.copy(self.variables)
+ var.update(
+ {
+ 'is_phantom': self.css_type == PHANTOM,
+ 'is_popup': self.css_type == POPUP
+ }
+ )
+
+ return self.env.from_string(
+ clean_css(sublime.load_resource(css))
+ ).render(var=var, plugin=self.plugin_vars)
+ except Exception:
+ return ''
+
+ def fade(self, css, factor):
+ """
+ Apply a fake transparency to color.
+
+ Fake transparency is preformed on top of the background color.
+ """
+ try:
+ parts = [c.strip('; ') for c in css.split(':')]
+ if len(parts) == 2 and parts[0] in ('background-color', 'color'):
+ rgba = RGBA(parts[1] + "%02f" % int(255.0 * max(min(float(factor), 1.0), 0.0)))
+ rgba.apply_alpha(self.get_bg())
+ return '%s: %s; ' % (parts[0], rgba.get_rgb())
+ except Exception:
+ pass
+ return css
+
+ def colorize(self, css, degree):
+ """Colorize to the given hue."""
+
+ parts = [c.strip('; ') for c in css.split(':')]
+ if len(parts) == 2 and parts[0] in ('background-color', 'color'):
+ rgba = RGBA(parts[1])
+ rgba.colorize(degree)
+ parts[1] = "%s; " % rgba.get_rgb()
+ return '%s: %s ' % (parts[0], parts[1])
+ return css
+
+ def hue(self, css, degree):
+ """Shift hue."""
+
+ parts = [c.strip('; ') for c in css.split(':')]
+ if len(parts) == 2 and parts[0] in ('background-color', 'color'):
+ rgba = RGBA(parts[1])
+ rgba.hue(degree)
+ parts[1] = "%s; " % rgba.get_rgb()
+ return '%s: %s ' % (parts[0], parts[1])
+ return css
+
+ def invert(self, css):
+ """Invert color."""
+
+ parts = [c.strip('; ') for c in css.split(':')]
+ if len(parts) == 2 and parts[0] in ('background-color', 'color'):
+ rgba = RGBA(parts[1])
+ rgba.invert()
+ parts[1] = "%s; " % rgba.get_rgb()
+ return '%s: %s ' % (parts[0], parts[1])
+ return css
+
+ def contrast(self, css, factor):
+ """Apply contrast filter."""
+
+ parts = [c.strip('; ') for c in css.split(':')]
+ if len(parts) == 2 and parts[0] in ('background-color', 'color'):
+ rgba = RGBA(parts[1])
+ rgba.contrast(factor)
+ parts[1] = "%s; " % rgba.get_rgb()
+ return '%s: %s ' % (parts[0], parts[1])
+ return css
+
+ def saturation(self, css, factor):
+ """Apply saturation filter."""
+
+ parts = [c.strip('; ') for c in css.split(':')]
+ if len(parts) == 2 and parts[0] in ('background-color', 'color'):
+ rgba = RGBA(parts[1])
+ rgba.saturation(factor)
+ parts[1] = "%s; " % rgba.get_rgb()
+ return '%s: %s ' % (parts[0], parts[1])
+ return css
+
+ def grayscale(self, css):
+ """Apply grayscale filter."""
+
+ parts = [c.strip('; ') for c in css.split(':')]
+ if len(parts) == 2 and parts[0] in ('background-color', 'color'):
+ rgba = RGBA(parts[1])
+ rgba.grayscale()
+ parts[1] = "%s; " % rgba.get_rgb()
+ return '%s: %s ' % (parts[0], parts[1])
+ return css
+
+ def sepia(self, css):
+ """Apply sepia filter."""
+
+ parts = [c.strip('; ') for c in css.split(':')]
+ if len(parts) == 2 and parts[0] in ('background-color', 'color'):
+ rgba = RGBA(parts[1])
+ rgba.sepia()
+ parts[1] = "%s; " % rgba.get_rgb()
+ return '%s: %s ' % (parts[0], parts[1])
+ return css
+
+ def brightness(self, css, factor):
+ """Adjust brightness."""
+
+ parts = [c.strip('; ') for c in css.split(':')]
+ if len(parts) == 2 and parts[0] in ('background-color', 'color'):
+ rgba = RGBA(parts[1])
+ rgba.brightness(factor)
+ parts[1] = "%s; " % rgba.get_rgb()
+ return '%s: %s ' % (parts[0], parts[1])
+ return css
+
+ def to_fg(self, css):
+ """Rename a CSS key value pair."""
+
+ parts = [c.strip('; ') for c in css.split(':')]
+ if len(parts) == 2 and parts[0] == 'background-color':
+ parts[0] = 'color'
+ return '%s: %s; ' % (parts[0], parts[1])
+ return css
+
+ def to_bg(self, css):
+ """Rename a CSS key value pair."""
+
+ parts = [c.strip('; ') for c in css.split(':')]
+ if len(parts) == 2 and parts[0] == 'color':
+ parts[0] = 'background-color'
+ return '%s: %s; ' % (parts[0], parts[1])
+ return css
+
+ def pygments(self, style):
+ """Get pygments style."""
+
+ return get_pygments(style)
+
+ def retrieve_selector(self, selector, key=None, explicit_background=True):
+ """Get the CSS key, value pairs for a rule."""
+
+ if NEW_SCHEMES:
+ general = self.view.style()
+ fg = general.get('foreground', '#000000')
+ bg = general.get('background', '#ffffff')
+ scope = self.view.style_for_scope(selector)
+ style = []
+ if scope['bold']:
+ style.append('bold')
+ if scope['italic']:
+ style.append('italic')
+ color = scope.get('foreground', fg)
+ bgcolor = scope.get('background', (None if explicit_background else bg))
+ else:
+ scope = self.guess_style(self.view, selector, explicit_background=explicit_background)
+ color = scope.fg_simulated
+ bgcolor = scope.bg_simulated
+ style = scope.style.split(' ')
+
+ css = []
+ if color and (key is None or key == 'color'):
+ css.append('color: %s' % color)
+ if bgcolor and (key is None or key == 'background-color'):
+ css.append('background-color: %s' % bgcolor)
+ for s in style:
+ if "bold" in s and (key is None or key == 'font-weight'):
+ css.append('font-weight: bold')
+ if "italic" in s and (key is None or key == 'font-style'):
+ css.append('font-style: italic')
+ if "underline" in s and (key is None or key == 'text-decoration') and False: # disabled
+ css.append('text-decoration: underline')
+ text = ';'.join(css)
+ if text:
+ text += ';'
+ return text
+
+ def apply_template(self, view, css, css_type, template_vars=None):
+ """Apply template to css."""
+
+ self.view = view
+
+ if css_type not in (POPUP, PHANTOM):
+ return ''
+
+ self.css_type = css_type
+ self.variables = self.get_variables()
+
+ var = copy.copy(self.variables)
+ if template_vars and isinstance(template_vars, (dict, OrderedDict)):
+ self.plugin_vars = copy.deepcopy(template_vars)
+ else:
+ self.plugin_vars = {}
+
+ var.update(
+ {
+ 'is_phantom': self.css_type == PHANTOM,
+ 'is_popup': self.css_type == POPUP
+ }
+ )
+
+ return self.env.from_string(css).render(var=var, plugin=self.plugin_vars)
+
+
+def get_pygments(style):
+ """
+ Get pygments style.
+
+ Subllime CSS support is limited. It cannot handle well
+ things like: `.class1 .class2`, but it can handle things like:
+ `.class1.class2`. So we will not use things like `.highlight` in front.
+
+ We will first find {...} which has no syntax class. This will contain
+ our background and possibly foreground. If for whatever reason we
+ have no background or foreground, we will use `#000000` or `#ffffff`
+ respectively.
+ """
+
+ try:
+ # Lets see if we can find the pygments theme
+ text = HtmlFormatter(style=style).get_style_defs('.dummy')
+ text = re_missing_semi_colon.sub('; }', text)
+ except Exception:
+ return ''
+
+ bg = None
+ fg = None
+
+ # Find {...} which has no syntax classes
+ m = re_base_colors.search(text)
+ if m:
+ # Find background
+ m1 = re_bgcolor.search(m.group(1))
+ if m1:
+ # Use `background-color` as it works better
+ # with Sublime CSS
+ bg = m1.group(1).replace('background', 'background-color')
+ # Find foreground
+ m1 = re_color.search(m.group(1))
+ if m1:
+ fg = m1.group(1)
+ # Use defaults if None found
+ if bg is None:
+ bg = 'background-color: #ffffff'
+ if fg is None:
+ fg = 'color: #000000'
+
+ # Reassemble replacing .highlight {...} with .codehilite, .inlinehilite {...}
+ # All other classes will be left bare with only their syntax class.
+ code_blocks = CODE_BLOCKS
+ if m:
+ css = clean_css(
+ (
+ text[:m.start(0)] +
+ (code_blocks % (bg, fg)) +
+ text[m.end(0):] +
+ '\n'
+ )
+ )
+ else:
+ css = clean_css(
+ (
+ (code_blocks % (bg, fg)) + '\n' + text + '\n'
+ )
+ )
+
+ return re_pygments_selectors.sub(r'.mdpopups .highlight \1', css)
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/version.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/version.py
new file mode 100644
index 0000000..96d81b2
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/version.py
@@ -0,0 +1,10 @@
+"""Version."""
+
+_version_info = (3, 3, 3)
+__version__ = '.'.join([str(x) for x in _version_info])
+
+
+def version():
+ """Get the current version."""
+
+ return _version_info
diff --git a/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/x11colors.py b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/x11colors.py
new file mode 100644
index 0000000..12d3511
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/st3/mdpopups/x11colors.py
@@ -0,0 +1,676 @@
+"""
+X11 colors.
+
+A simple name to hex and hex to name map of X11 colors.
+"""
+name2hex_map = {
+ "black": "#000000",
+ "aliceblue": "#f0f8ff",
+ "blueviolet": "#8a2be2",
+ "cadetblue": "#5f9ea0",
+ "cadetblue1": "#98f5ff",
+ "cadetblue2": "#8ee5ee",
+ "cadetblue3": "#7ac5cd",
+ "cadetblue4": "#53868b",
+ "cornflowerblue": "#6495ed",
+ "darkblue": "#00008b",
+ "darkcyan": "#008b8b",
+ "darkslateblue": "#483d8b",
+ "darkturquoise": "#00ced1",
+ "deepskyblue": "#00bfff",
+ "deepskyblue1": "#00bfff",
+ "deepskyblue2": "#00b2ee",
+ "deepskyblue3": "#009acd",
+ "deepskyblue4": "#00688b",
+ "dodgerblue": "#1e90ff",
+ "dodgerblue1": "#1e90ff",
+ "dodgerblue2": "#1c86ee",
+ "dodgerblue3": "#1874cd",
+ "dodgerblue4": "#104e8b",
+ "lightblue": "#add8e6",
+ "lightblue1": "#bfefff",
+ "lightblue2": "#b2dfee",
+ "lightblue3": "#9ac0cd",
+ "lightblue4": "#68838b",
+ "lightcyan": "#e0ffff",
+ "lightcyan1": "#e0ffff",
+ "lightcyan2": "#d1eeee",
+ "lightcyan3": "#b4cdcd",
+ "lightcyan4": "#7a8b8b",
+ "lightskyblue": "#87cefa",
+ "lightskyblue1": "#b0e2ff",
+ "lightskyblue2": "#a4d3ee",
+ "lightskyblue3": "#8db6cd",
+ "lightskyblue4": "#607b8b",
+ "lightslateblue": "#8470ff",
+ "lightsteelblue": "#b0c4de",
+ "lightsteelblue1": "#cae1ff",
+ "lightsteelblue2": "#bcd2ee",
+ "lightsteelblue3": "#a2b5cd",
+ "lightsteelblue4": "#6e7b8b",
+ "mediumaquamarine": "#66cdaa",
+ "mediumblue": "#0000cd",
+ "mediumslateblue": "#7b68ee",
+ "mediumturquoise": "#48d1cc",
+ "midnightblue": "#191970",
+ "navyblue": "#000080",
+ "paleturquoise": "#afeeee",
+ "paleturquoise1": "#bbffff",
+ "paleturquoise2": "#aeeeee",
+ "paleturquoise3": "#96cdcd",
+ "paleturquoise4": "#668b8b",
+ "powderblue": "#b0e0e6",
+ "royalblue": "#4169e1",
+ "royalblue1": "#4876ff",
+ "royalblue2": "#436eee",
+ "royalblue3": "#3a5fcd",
+ "royalblue4": "#27408b",
+ "skyblue": "#87ceeb",
+ "skyblue1": "#87ceff",
+ "skyblue2": "#7ec0ee",
+ "skyblue3": "#6ca6cd",
+ "skyblue4": "#4a708b",
+ "slateblue": "#6a5acd",
+ "slateblue1": "#836fff",
+ "slateblue2": "#7a67ee",
+ "slateblue3": "#6959cd",
+ "slateblue4": "#473c8b",
+ "steelblue": "#4682b4",
+ "steelblue1": "#63b8ff",
+ "steelblue2": "#5cacee",
+ "steelblue3": "#4f94cd",
+ "steelblue4": "#36648b",
+ "aquamarine": "#7fffd4",
+ "aquamarine1": "#7fffd4",
+ "aquamarine2": "#76eec6",
+ "aquamarine3": "#66cdaa",
+ "aquamarine4": "#458b74",
+ "azure": "#f0ffff",
+ "azure1": "#f0ffff",
+ "azure2": "#e0eeee",
+ "azure3": "#c1cdcd",
+ "azure4": "#838b8b",
+ "blue": "#0000ff",
+ "blue1": "#0000ff",
+ "blue2": "#0000ee",
+ "blue3": "#0000cd",
+ "blue4": "#00008b",
+ "cyan": "#00ffff",
+ "cyan1": "#00ffff",
+ "cyan2": "#00eeee",
+ "cyan3": "#00cdcd",
+ "cyan4": "#008b8b",
+ "navy": "#000080",
+ "turquoise": "#40e0d0",
+ "turquoise1": "#00f5ff",
+ "turquoise2": "#00e5ee",
+ "turquoise3": "#00c5cd",
+ "turquoise4": "#00868b",
+ "rosybrown": "#bc8f8f",
+ "rosybrown1": "#ffc1c1",
+ "rosybrown2": "#eeb4b4",
+ "rosybrown3": "#cd9b9b",
+ "rosybrown4": "#8b6969",
+ "saddlebrown": "#8b4513",
+ "sandybrown": "#f4a460",
+ "beige": "#f5f5dc",
+ "brown": "#a52a2a",
+ "brown1": "#ff4040",
+ "brown2": "#ee3b3b",
+ "brown3": "#cd3333",
+ "brown4": "#8b2323",
+ "burlywood": "#deb887",
+ "burlywood1": "#ffd39b",
+ "burlywood2": "#eec591",
+ "burlywood3": "#cdaa7d",
+ "burlywood4": "#8b7355",
+ "chocolate": "#d2691e",
+ "chocolate1": "#ff7f24",
+ "chocolate2": "#ee7621",
+ "chocolate3": "#cd661d",
+ "chocolate4": "#8b4513",
+ "peru": "#cd853f",
+ "tan": "#d2b48c",
+ "tan1": "#ffa54f",
+ "tan2": "#ee9a49",
+ "tan3": "#cd853f",
+ "tan4": "#8b5a2b",
+ "darkslategray": "#2f4f4f",
+ "darkslategray1": "#97ffff",
+ "darkslategray2": "#8deeee",
+ "darkslategray3": "#79cdcd",
+ "darkslategray4": "#528b8b",
+ "darkslategrey": "#2f4f4f",
+ "dimgray": "#696969",
+ "dimgrey": "#696969",
+ "lightgray": "#d3d3d3",
+ "lightgrey": "#d3d3d3",
+ "lightslategray": "#778899",
+ "lightslategrey": "#778899",
+ "slategray": "#708090",
+ "slategray1": "#c6e2ff",
+ "slategray2": "#b9d3ee",
+ "slategray3": "#9fb6cd",
+ "slategray4": "#6c7b8b",
+ "slategrey": "#708090",
+ "gray": "#bebebe",
+ "gray0": "#000000",
+ "gray1": "#030303",
+ "gray2": "#050505",
+ "gray3": "#080808",
+ "gray4": "#0a0a0a",
+ "gray5": "#0d0d0d",
+ "gray6": "#0f0f0f",
+ "gray7": "#121212",
+ "gray8": "#141414",
+ "gray9": "#171717",
+ "gray10": "#1a1a1a",
+ "gray11": "#1c1c1c",
+ "gray12": "#1f1f1f",
+ "gray13": "#212121",
+ "gray14": "#242424",
+ "gray15": "#262626",
+ "gray16": "#292929",
+ "gray17": "#2b2b2b",
+ "gray18": "#2e2e2e",
+ "gray19": "#303030",
+ "gray20": "#333333",
+ "gray21": "#363636",
+ "gray22": "#383838",
+ "gray23": "#3b3b3b",
+ "gray24": "#3d3d3d",
+ "gray25": "#404040",
+ "gray26": "#424242",
+ "gray27": "#454545",
+ "gray28": "#474747",
+ "gray29": "#4a4a4a",
+ "gray30": "#4d4d4d",
+ "gray31": "#4f4f4f",
+ "gray32": "#525252",
+ "gray33": "#545454",
+ "gray34": "#575757",
+ "gray35": "#595959",
+ "gray36": "#5c5c5c",
+ "gray37": "#5e5e5e",
+ "gray38": "#616161",
+ "gray39": "#636363",
+ "gray40": "#666666",
+ "gray41": "#696969",
+ "gray42": "#6b6b6b",
+ "gray43": "#6e6e6e",
+ "gray44": "#707070",
+ "gray45": "#737373",
+ "gray46": "#757575",
+ "gray47": "#787878",
+ "gray48": "#7a7a7a",
+ "gray49": "#7d7d7d",
+ "gray50": "#7f7f7f",
+ "gray51": "#828282",
+ "gray52": "#858585",
+ "gray53": "#878787",
+ "gray54": "#8a8a8a",
+ "gray55": "#8c8c8c",
+ "gray56": "#8f8f8f",
+ "gray57": "#919191",
+ "gray58": "#949494",
+ "gray59": "#969696",
+ "gray60": "#999999",
+ "gray61": "#9c9c9c",
+ "gray62": "#9e9e9e",
+ "gray63": "#a1a1a1",
+ "gray64": "#a3a3a3",
+ "gray65": "#a6a6a6",
+ "gray66": "#a8a8a8",
+ "gray67": "#ababab",
+ "gray68": "#adadad",
+ "gray69": "#b0b0b0",
+ "gray70": "#b3b3b3",
+ "gray71": "#b5b5b5",
+ "gray72": "#b8b8b8",
+ "gray73": "#bababa",
+ "gray74": "#bdbdbd",
+ "gray75": "#bfbfbf",
+ "gray76": "#c2c2c2",
+ "gray77": "#c4c4c4",
+ "gray78": "#c7c7c7",
+ "gray79": "#c9c9c9",
+ "gray80": "#cccccc",
+ "gray81": "#cfcfcf",
+ "gray82": "#d1d1d1",
+ "gray83": "#d4d4d4",
+ "gray84": "#d6d6d6",
+ "gray85": "#d9d9d9",
+ "gray86": "#dbdbdb",
+ "gray87": "#dedede",
+ "gray88": "#e0e0e0",
+ "gray89": "#e3e3e3",
+ "gray90": "#e5e5e5",
+ "gray91": "#e8e8e8",
+ "gray92": "#ebebeb",
+ "gray93": "#ededed",
+ "gray94": "#f0f0f0",
+ "gray95": "#f2f2f2",
+ "gray96": "#f5f5f5",
+ "gray97": "#f7f7f7",
+ "gray98": "#fafafa",
+ "gray99": "#fcfcfc",
+ "gray100": "#ffffff",
+ "grey": "#bebebe",
+ "grey0": "#000000",
+ "grey1": "#030303",
+ "grey2": "#050505",
+ "grey3": "#080808",
+ "grey4": "#0a0a0a",
+ "grey5": "#0d0d0d",
+ "grey6": "#0f0f0f",
+ "grey7": "#121212",
+ "grey8": "#141414",
+ "grey9": "#171717",
+ "grey10": "#1a1a1a",
+ "grey11": "#1c1c1c",
+ "grey12": "#1f1f1f",
+ "grey13": "#212121",
+ "grey14": "#242424",
+ "grey15": "#262626",
+ "grey16": "#292929",
+ "grey17": "#2b2b2b",
+ "grey18": "#2e2e2e",
+ "grey19": "#303030",
+ "grey20": "#333333",
+ "grey21": "#363636",
+ "grey22": "#383838",
+ "grey23": "#3b3b3b",
+ "grey24": "#3d3d3d",
+ "grey25": "#404040",
+ "grey26": "#424242",
+ "grey27": "#454545",
+ "grey28": "#474747",
+ "grey29": "#4a4a4a",
+ "grey30": "#4d4d4d",
+ "grey31": "#4f4f4f",
+ "grey32": "#525252",
+ "grey33": "#545454",
+ "grey34": "#575757",
+ "grey35": "#595959",
+ "grey36": "#5c5c5c",
+ "grey37": "#5e5e5e",
+ "grey38": "#616161",
+ "grey39": "#636363",
+ "grey40": "#666666",
+ "grey41": "#696969",
+ "grey42": "#6b6b6b",
+ "grey43": "#6e6e6e",
+ "grey44": "#707070",
+ "grey45": "#737373",
+ "grey46": "#757575",
+ "grey47": "#787878",
+ "grey48": "#7a7a7a",
+ "grey49": "#7d7d7d",
+ "grey50": "#7f7f7f",
+ "grey51": "#828282",
+ "grey52": "#858585",
+ "grey53": "#878787",
+ "grey54": "#8a8a8a",
+ "grey55": "#8c8c8c",
+ "grey56": "#8f8f8f",
+ "grey57": "#919191",
+ "grey58": "#949494",
+ "grey59": "#969696",
+ "grey60": "#999999",
+ "grey61": "#9c9c9c",
+ "grey62": "#9e9e9e",
+ "grey63": "#a1a1a1",
+ "grey64": "#a3a3a3",
+ "grey65": "#a6a6a6",
+ "grey66": "#a8a8a8",
+ "grey67": "#ababab",
+ "grey68": "#adadad",
+ "grey69": "#b0b0b0",
+ "grey70": "#b3b3b3",
+ "grey71": "#b5b5b5",
+ "grey72": "#b8b8b8",
+ "grey73": "#bababa",
+ "grey74": "#bdbdbd",
+ "grey75": "#bfbfbf",
+ "grey76": "#c2c2c2",
+ "grey77": "#c4c4c4",
+ "grey78": "#c7c7c7",
+ "grey79": "#c9c9c9",
+ "grey80": "#cccccc",
+ "grey81": "#cfcfcf",
+ "grey82": "#d1d1d1",
+ "grey83": "#d4d4d4",
+ "grey84": "#d6d6d6",
+ "grey85": "#d9d9d9",
+ "grey86": "#dbdbdb",
+ "grey87": "#dedede",
+ "grey88": "#e0e0e0",
+ "grey89": "#e3e3e3",
+ "grey90": "#e5e5e5",
+ "grey91": "#e8e8e8",
+ "grey92": "#ebebeb",
+ "grey93": "#ededed",
+ "grey94": "#f0f0f0",
+ "grey95": "#f2f2f2",
+ "grey96": "#f5f5f5",
+ "grey97": "#f7f7f7",
+ "grey98": "#fafafa",
+ "grey99": "#fcfcfc",
+ "grey100": "#ffffff",
+ "darkgreen": "#006400",
+ "darkkhaki": "#bdb76b",
+ "darkolivegreen": "#556b2f",
+ "darkolivegreen1": "#caff70",
+ "darkolivegreen2": "#bcee68",
+ "darkolivegreen3": "#a2cd5a",
+ "darkolivegreen4": "#6e8b3d",
+ "darkseagreen": "#8fbc8f",
+ "darkseagreen1": "#c1ffc1",
+ "darkseagreen2": "#b4eeb4",
+ "darkseagreen3": "#9bcd9b",
+ "darkseagreen4": "#698b69",
+ "forestgreen": "#228b22",
+ "greenyellow": "#adff2f",
+ "lawngreen": "#7cfc00",
+ "lightgreen": "#90ee90",
+ "lightseagreen": "#20b2aa",
+ "limegreen": "#32cd32",
+ "mediumseagreen": "#3cb371",
+ "mediumspringgreen": "#00fa9a",
+ "mintcream": "#f5fffa",
+ "olivedrab": "#6b8e23",
+ "olivedrab1": "#c0ff3e",
+ "olivedrab2": "#b3ee3a",
+ "olivedrab3": "#9acd32",
+ "olivedrab4": "#698b22",
+ "palegreen": "#98fb98",
+ "palegreen1": "#9aff9a",
+ "palegreen2": "#90ee90",
+ "palegreen3": "#7ccd7c",
+ "palegreen4": "#548b54",
+ "seagreen": "#2e8b57",
+ "seagreen1": "#54ff9f",
+ "seagreen2": "#4eee94",
+ "seagreen3": "#43cd80",
+ "seagreen4": "#2e8b57",
+ "springgreen": "#00ff7f",
+ "springgreen1": "#00ff7f",
+ "springgreen2": "#00ee76",
+ "springgreen3": "#00cd66",
+ "springgreen4": "#008b45",
+ "yellowgreen": "#9acd32",
+ "chartreuse": "#7fff00",
+ "chartreuse1": "#7fff00",
+ "chartreuse2": "#76ee00",
+ "chartreuse3": "#66cd00",
+ "chartreuse4": "#458b00",
+ "green": "#00ff00",
+ "green1": "#00ff00",
+ "green2": "#00ee00",
+ "green3": "#00cd00",
+ "green4": "#008b00",
+ "khaki": "#f0e68c",
+ "khaki1": "#fff68f",
+ "khaki2": "#eee685",
+ "khaki3": "#cdc673",
+ "khaki4": "#8b864e",
+ "darkorange": "#ff8c00",
+ "darkorange1": "#ff7f00",
+ "darkorange2": "#ee7600",
+ "darkorange3": "#cd6600",
+ "darkorange4": "#8b4500",
+ "darksalmon": "#e9967a",
+ "lightcoral": "#f08080",
+ "lightsalmon": "#ffa07a",
+ "lightsalmon1": "#ffa07a",
+ "lightsalmon2": "#ee9572",
+ "lightsalmon3": "#cd8162",
+ "lightsalmon4": "#8b5742",
+ "peachpuff": "#ffdab9",
+ "peachpuff1": "#ffdab9",
+ "peachpuff2": "#eecbad",
+ "peachpuff3": "#cdaf95",
+ "peachpuff4": "#8b7765",
+ "bisque": "#ffe4c4",
+ "bisque1": "#ffe4c4",
+ "bisque2": "#eed5b7",
+ "bisque3": "#cdb79e",
+ "bisque4": "#8b7d6b",
+ "coral": "#ff7f50",
+ "coral1": "#ff7256",
+ "coral2": "#ee6a50",
+ "coral3": "#cd5b45",
+ "coral4": "#8b3e2f",
+ "honeydew": "#f0fff0",
+ "honeydew1": "#f0fff0",
+ "honeydew2": "#e0eee0",
+ "honeydew3": "#c1cdc1",
+ "honeydew4": "#838b83",
+ "orange": "#ffa500",
+ "orange1": "#ffa500",
+ "orange2": "#ee9a00",
+ "orange3": "#cd8500",
+ "orange4": "#8b5a00",
+ "salmon": "#fa8072",
+ "salmon1": "#ff8c69",
+ "salmon2": "#ee8262",
+ "salmon3": "#cd7054",
+ "salmon4": "#8b4c39",
+ "sienna": "#a0522d",
+ "sienna1": "#ff8247",
+ "sienna2": "#ee7942",
+ "sienna3": "#cd6839",
+ "sienna4": "#8b4726",
+ "darkred": "#8b0000",
+ "deeppink": "#ff1493",
+ "deeppink1": "#ff1493",
+ "deeppink2": "#ee1289",
+ "deeppink3": "#cd1076",
+ "deeppink4": "#8b0a50",
+ "hotpink": "#ff69b4",
+ "hotpink1": "#ff6eb4",
+ "hotpink2": "#ee6aa7",
+ "hotpink3": "#cd6090",
+ "hotpink4": "#8b3a62",
+ "indianred": "#cd5c5c",
+ "indianred1": "#ff6a6a",
+ "indianred2": "#ee6363",
+ "indianred3": "#cd5555",
+ "indianred4": "#8b3a3a",
+ "lightpink": "#ffb6c1",
+ "lightpink1": "#ffaeb9",
+ "lightpink2": "#eea2ad",
+ "lightpink3": "#cd8c95",
+ "lightpink4": "#8b5f65",
+ "mediumvioletred": "#c71585",
+ "mistyrose": "#ffe4e1",
+ "mistyrose1": "#ffe4e1",
+ "mistyrose2": "#eed5d2",
+ "mistyrose3": "#cdb7b5",
+ "mistyrose4": "#8b7d7b",
+ "orangered": "#ff4500",
+ "orangered1": "#ff4500",
+ "orangered2": "#ee4000",
+ "orangered3": "#cd3700",
+ "orangered4": "#8b2500",
+ "palevioletred": "#db7093",
+ "palevioletred1": "#ff82ab",
+ "palevioletred2": "#ee799f",
+ "palevioletred3": "#cd6889",
+ "palevioletred4": "#8b475d",
+ "violetred": "#d02090",
+ "violetred1": "#ff3e96",
+ "violetred2": "#ee3a8c",
+ "violetred3": "#cd3278",
+ "violetred4": "#8b2252",
+ "firebrick": "#b22222",
+ "firebrick1": "#ff3030",
+ "firebrick2": "#ee2c2c",
+ "firebrick3": "#cd2626",
+ "firebrick4": "#8b1a1a",
+ "pink": "#ffc0cb",
+ "pink1": "#ffb5c5",
+ "pink2": "#eea9b8",
+ "pink3": "#cd919e",
+ "pink4": "#8b636c",
+ "red": "#ff0000",
+ "red1": "#ff0000",
+ "red2": "#ee0000",
+ "red3": "#cd0000",
+ "red4": "#8b0000",
+ "tomato": "#ff6347",
+ "tomato1": "#ff6347",
+ "tomato2": "#ee5c42",
+ "tomato3": "#cd4f39",
+ "tomato4": "#8b3626",
+ "darkmagenta": "#8b008b",
+ "darkorchid": "#9932cc",
+ "darkorchid1": "#bf3eff",
+ "darkorchid2": "#b23aee",
+ "darkorchid3": "#9a32cd",
+ "darkorchid4": "#68228b",
+ "darkviolet": "#9400d3",
+ "lavenderblush": "#fff0f5",
+ "lavenderblush1": "#fff0f5",
+ "lavenderblush2": "#eee0e5",
+ "lavenderblush3": "#cdc1c5",
+ "lavenderblush4": "#8b8386",
+ "mediumorchid": "#ba55d3",
+ "mediumorchid1": "#e066ff",
+ "mediumorchid2": "#d15fee",
+ "mediumorchid3": "#b452cd",
+ "mediumorchid4": "#7a378b",
+ "mediumpurple": "#9370db",
+ "mediumpurple1": "#ab82ff",
+ "mediumpurple2": "#9f79ee",
+ "mediumpurple3": "#8968cd",
+ "mediumpurple4": "#5d478b",
+ "lavender": "#e6e6fa",
+ "magenta": "#ff00ff",
+ "magenta1": "#ff00ff",
+ "magenta2": "#ee00ee",
+ "magenta3": "#cd00cd",
+ "magenta4": "#8b008b",
+ "maroon": "#b03060",
+ "maroon1": "#ff34b3",
+ "maroon2": "#ee30a7",
+ "maroon3": "#cd2990",
+ "maroon4": "#8b1c62",
+ "orchid": "#da70d6",
+ "orchid1": "#ff83fa",
+ "orchid2": "#ee7ae9",
+ "orchid3": "#cd69c9",
+ "orchid4": "#8b4789",
+ "plum": "#dda0dd",
+ "plum1": "#ffbbff",
+ "plum2": "#eeaeee",
+ "plum3": "#cd96cd",
+ "plum4": "#8b668b",
+ "purple": "#a020f0",
+ "purple1": "#9b30ff",
+ "purple2": "#912cee",
+ "purple3": "#7d26cd",
+ "purple4": "#551a8b",
+ "thistle": "#d8bfd8",
+ "thistle1": "#ffe1ff",
+ "thistle2": "#eed2ee",
+ "thistle3": "#cdb5cd",
+ "thistle4": "#8b7b8b",
+ "violet": "#ee82ee",
+ "antiquewhite": "#faebd7",
+ "antiquewhite1": "#ffefdb",
+ "antiquewhite2": "#eedfcc",
+ "antiquewhite3": "#cdc0b0",
+ "antiquewhite4": "#8b8378",
+ "floralwhite": "#fffaf0",
+ "ghostwhite": "#f8f8ff",
+ "navajowhite": "#ffdead",
+ "navajowhite1": "#ffdead",
+ "navajowhite2": "#eecfa1",
+ "navajowhite3": "#cdb38b",
+ "navajowhite4": "#8b795e",
+ "oldlace": "#fdf5e6",
+ "whitesmoke": "#f5f5f5",
+ "gainsboro": "#dcdcdc",
+ "ivory": "#fffff0",
+ "ivory1": "#fffff0",
+ "ivory2": "#eeeee0",
+ "ivory3": "#cdcdc1",
+ "ivory4": "#8b8b83",
+ "linen": "#faf0e6",
+ "seashell": "#fff5ee",
+ "seashell1": "#fff5ee",
+ "seashell2": "#eee5de",
+ "seashell3": "#cdc5bf",
+ "seashell4": "#8b8682",
+ "snow": "#fffafa",
+ "snow1": "#fffafa",
+ "snow2": "#eee9e9",
+ "snow3": "#cdc9c9",
+ "snow4": "#8b8989",
+ "wheat": "#f5deb3",
+ "wheat1": "#ffe7ba",
+ "wheat2": "#eed8ae",
+ "wheat3": "#cdba96",
+ "wheat4": "#8b7e66",
+ "white": "#ffffff",
+ "blanchedalmond": "#ffebcd",
+ "darkgoldenrod": "#b8860b",
+ "darkgoldenrod1": "#ffb90f",
+ "darkgoldenrod2": "#eead0e",
+ "darkgoldenrod3": "#cd950c",
+ "darkgoldenrod4": "#8b6508",
+ "lemonchiffon": "#fffacd",
+ "lemonchiffon1": "#fffacd",
+ "lemonchiffon2": "#eee9bf",
+ "lemonchiffon3": "#cdc9a5",
+ "lemonchiffon4": "#8b8970",
+ "lightgoldenrod": "#eedd82",
+ "lightgoldenrod1": "#ffec8b",
+ "lightgoldenrod2": "#eedc82",
+ "lightgoldenrod3": "#cdbe70",
+ "lightgoldenrod4": "#8b814c",
+ "lightgoldenrodyellow": "#fafad2",
+ "lightyellow": "#ffffe0",
+ "lightyellow1": "#ffffe0",
+ "lightyellow2": "#eeeed1",
+ "lightyellow3": "#cdcdb4",
+ "lightyellow4": "#8b8b7a",
+ "palegoldenrod": "#eee8aa",
+ "papayawhip": "#ffefd5",
+ "cornsilk": "#fff8dc",
+ "cornsilk1": "#fff8dc",
+ "cornsilk2": "#eee8cd",
+ "cornsilk3": "#cdc8b1",
+ "cornsilk4": "#8b8878",
+ "gold": "#ffd700",
+ "gold1": "#ffd700",
+ "gold2": "#eec900",
+ "gold3": "#cdad00",
+ "gold4": "#8b7500",
+ "goldenrod": "#daa520",
+ "goldenrod1": "#ffc125",
+ "goldenrod2": "#eeb422",
+ "goldenrod3": "#cd9b1d",
+ "goldenrod4": "#8b6914",
+ "moccasin": "#ffe4b5",
+ "yellow": "#ffff00",
+ "yellow1": "#ffff00",
+ "yellow2": "#eeee00",
+ "yellow3": "#cdcd00",
+ "yellow4": "#8b8b00"
+}
+
+hex2name_map = dict([(v, k) for k, v in name2hex_map.items()])
+
+
+def hex2name(value):
+ """Convert X11 hex to webcolor name."""
+
+ return hex2name_map.get(value.lower(), None)
+
+
+def name2hex(name):
+ """Convert X11 webcolor name to hex."""
+
+ return name2hex_map.get(name.lower(), None)
diff --git a/.config/sublime-text-3/Packages/mdpopups/tests/__init__.py b/.config/sublime-text-3/Packages/mdpopups/tests/__init__.py
new file mode 100644
index 0000000..8eef0e8
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/tests/__init__.py
@@ -0,0 +1 @@
+"""Unit Tests."""
diff --git a/.config/sublime-text-3/Packages/mdpopups/tests/spellcheck.py b/.config/sublime-text-3/Packages/mdpopups/tests/spellcheck.py
new file mode 100644
index 0000000..eca94ee
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/tests/spellcheck.py
@@ -0,0 +1,266 @@
+"""Spell check with aspell."""
+from __future__ import unicode_literals
+import subprocess
+import os
+import sys
+import codecs
+import bs4
+import yaml
+import re
+from collections import namedtuple
+
+PY3 = sys.version_info >= (3, 0)
+
+
+def yaml_load(source, loader=yaml.Loader):
+ """
+ Wrap PyYaml's loader so we can extend it to suit our needs.
+
+ Load all strings as unicode: http://stackoverflow.com/a/2967461/3609487.
+ """
+
+ def construct_yaml_str(self, node):
+ """Override the default string handling function to always return Unicode objects."""
+ return self.construct_scalar(node)
+
+ class Loader(loader):
+ """Define a custom loader to leave the global loader unaltered."""
+
+ # Attach our unicode constructor to our custom loader ensuring all strings
+ # will be unicode on translation.
+ Loader.add_constructor('tag:yaml.org,2002:str', construct_yaml_str)
+
+ return yaml.load(source, Loader)
+
+
+def read_config(file_name):
+ """Read configuration."""
+
+ config = {}
+ with codecs.open(file_name, 'r', encoding='utf-8') as f:
+ config = yaml_load(f.read())
+ return config
+
+
+def console(cmd, input_file=None, input_text=None):
+ """Call with arguments."""
+
+ returncode = None
+ output = None
+
+ if sys.platform.startswith('win'):
+ startupinfo = subprocess.STARTUPINFO()
+ startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
+ process = subprocess.Popen(
+ cmd,
+ startupinfo=startupinfo,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ stdin=subprocess.PIPE,
+ shell=False
+ )
+ else:
+ process = subprocess.Popen(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ stdin=subprocess.PIPE,
+ shell=False
+ )
+
+ if input_file is not None:
+ with open(input_file, 'rb') as f:
+ process.stdin.write(f.read())
+ if input_text is not None:
+ process.stdin.write(input_text)
+ output = process.communicate()
+ returncode = process.returncode
+
+ assert returncode == 0, "Runtime Error: %s" % (
+ output[0].rstrip().decode('utf-8') if PY3 else output[0]
+ )
+
+ return output[0].decode('utf-8') if PY3 else output[0]
+
+
+class IgnoreRule (namedtuple('IgnoreRule', ['tag', 'id', 'classes'])):
+ """Ignore rule."""
+
+
+class Spelling(object):
+ """Spell check object."""
+
+ DICTIONARY = 'dictionary.bin'
+ RE_SELECTOR = re.compile(r'(\#|\.)?[-\w]+')
+
+ def __init__(self, config_file):
+ """Initialize."""
+
+ config = read_config(config_file)
+ self.docs = config.get('docs', [])
+ self.dictionary = ('\n'.join(config.get('dictionary', []))).encode('utf-8')
+ self.attributes = set(config.get('attributes', []))
+ self.ignores = self.ignore_rules(*config.get('ignores', []))
+ self.dict_bin = os.path.abspath(self.DICTIONARY)
+
+ def ignore_rules(self, *args):
+ """
+ Process ignore rules.
+
+ Split ignore selector string into tag, id, and classes.
+ """
+
+ ignores = []
+
+ for arg in args:
+ selector = arg.lower()
+ tag = None
+ tag_id = None
+ classes = set()
+
+ for m in self.RE_SELECTOR.finditer(selector):
+ selector = m.group(0)
+ if selector.startswith('.'):
+ classes.add(selector[1:])
+ elif selector.startswith('#') and tag_id is None:
+ tag_id = selector[1:]
+ elif tag is None:
+ tag = selector
+ else:
+ raise ValueError('Bad selector!')
+
+ if tag or tag_id or classes:
+ ignores.append(IgnoreRule(tag, tag_id, tuple(classes)))
+
+ return ignores
+
+ def compile_dictionaries(self):
+ """Compile user dictionary."""
+
+ if os.path.exists(self.dict_bin):
+ os.remove(self.dict_bin)
+ print("Compiling Dictionary...")
+ print(
+ console(
+ [
+ 'aspell',
+ '--lang=en',
+ '--encoding=utf-8',
+ 'create',
+ 'master',
+ os.path.abspath(self.dict_bin)
+ ],
+ input_text=self.dictionary
+ )
+ )
+
+ def skip_tag(self, el):
+ """Determine if tag should be skipped."""
+
+ skip = False
+ for rule in self.ignores:
+ if rule.tag and el.name.lower() != rule.tag:
+ continue
+ if rule.id and rule.id != el.attrs.get('id', '').lower():
+ continue
+ if rule.classes:
+ current_classes = [c.lower() for c in el.attrs.get('class', [])]
+ found = True
+ for c in rule.classes:
+ if c not in current_classes:
+ found = False
+ break
+ if not found:
+ continue
+ skip = True
+ break
+ return skip
+
+ def html_to_text(self, tree, root=True):
+ """
+ Parse the HTML creating a buffer with each tags content.
+
+ Skip any selectors specified and include attributes if specified.
+ Ignored tags will not have their attributes scanned either.
+ """
+
+ text = []
+
+ if not self.skip_tag(tree):
+ for attr in self.attributes:
+ value = tree.attrs.get(attr)
+ if value:
+ text.append(value)
+
+ for child in tree:
+ if isinstance(child, bs4.element.Tag):
+ if child.contents:
+ text.extend(self.html_to_text(child, False))
+ else:
+ text.append(str(child))
+
+ return ' '.join(text) if root else text
+
+ def check_spelling(self, html_file):
+ """Check spelling."""
+
+ fail = False
+ with codecs.open(html_file, 'r', encoding='utf-8') as file_obj:
+ html = bs4.BeautifulSoup(file_obj.read(), "html5lib")
+ text = self.html_to_text(html.html)
+
+ wordlist = console(
+ [
+ 'aspell',
+ 'list',
+ '--lang=en',
+ '--mode=url',
+ '--encoding=utf-8',
+ '--extra-dicts',
+ self.dict_bin
+ ],
+ input_text=text.encode('utf-8')
+ )
+ words = [w for w in sorted(set(wordlist.split('\n'))) if w]
+
+ if words:
+ fail = True
+ print('Misspelled words in %s' % html_file)
+ print('-' * 80)
+ for word in words:
+ print(word)
+ print('-' * 80)
+ print('\n')
+ return fail
+
+ def check(self):
+ """Walk documents and initiate spell check."""
+
+ self.compile_dictionaries()
+
+ print('Spell Checking...')
+ fail = False
+ for doc in self.docs:
+ if os.path.isdir(doc):
+ for base, dirs, files in os.walk(doc):
+ # Remove child folders based on exclude rules
+ for f in files:
+ if f.lower().endswith('.html'):
+ file_name = os.path.join(base, f)
+ if self.check_spelling(file_name):
+ fail = True
+ elif doc.lower().endswith('.html'):
+ if self.check_spelling(doc):
+ fail = True
+ return fail
+
+
+def main():
+ """Main."""
+
+ spelling = Spelling('.spelling.yml')
+ return spelling.check()
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/.config/sublime-text-3/Packages/mdpopups/tests/test_json.py b/.config/sublime-text-3/Packages/mdpopups/tests/test_json.py
new file mode 100644
index 0000000..bab7179
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/tests/test_json.py
@@ -0,0 +1,39 @@
+"""Test JSON."""
+import unittest
+from . import validate_json_format
+import os
+import fnmatch
+
+
+class TestSettings(unittest.TestCase):
+ """Test JSON settings."""
+
+ def _get_json_files(self, pattern, folder='.'):
+ """Get json files."""
+
+ for root, dirnames, filenames in os.walk(folder):
+ for filename in fnmatch.filter(filenames, pattern):
+ yield os.path.join(root, filename)
+ for dirname in [d for d in dirnames if d not in ('.svn', '.git', '.tox')]:
+ for f in self._get_json_files(pattern, os.path.join(root, dirname)):
+ yield f
+
+ def test_json_settings(self):
+ """Test each JSON file."""
+
+ patterns = (
+ '*.sublime-settings',
+ '*.sublime-keymap',
+ '*.sublime-commands',
+ '*.sublime-menu',
+ '*.sublime-theme',
+ '*.sublime-color-scheme'
+ )
+
+ for pattern in patterns:
+ for f in self._get_json_files(pattern):
+ print(f)
+ self.assertFalse(
+ validate_json_format.CheckJsonFormat(False, True).check_format(f),
+ "%s does not comform to expected format!" % f
+ )
diff --git a/.config/sublime-text-3/Packages/mdpopups/tests/validate_json_format.py b/.config/sublime-text-3/Packages/mdpopups/tests/validate_json_format.py
new file mode 100644
index 0000000..2d63117
--- /dev/null
+++ b/.config/sublime-text-3/Packages/mdpopups/tests/validate_json_format.py
@@ -0,0 +1,231 @@
+"""
+Validate JSON format.
+
+Licensed under MIT
+Copyright (c) 2012-2015 Isaac Muse
+"""
+import re
+import codecs
+import json
+
+RE_LINE_PRESERVE = re.compile(r"\r?\n", re.MULTILINE)
+RE_COMMENT = re.compile(
+ r'''(?x)
+ (?P
+ /\*[^*]*\*+(?:[^/*][^*]*\*+)*/ # multi-line comments
+ | [ \t]*//(?:[^\r\n])* # single line comments
+ )
+ | (?P
+ "(?:\\.|[^"\\])*" # double quotes
+ | .[^/"']* # everything else
+ )
+ ''',
+ re.DOTALL
+)
+RE_TRAILING_COMMA = re.compile(
+ r'''(?x)
+ (
+ (?P
+ , # trailing comma
+ (?P[\s\r\n]*) # white space
+ (?P\]) # bracket
+ )
+ | (?P
+ , # trailing comma
+ (?P[\s\r\n]*) # white space
+ (?P\}) # bracket
+ )
+ )
+ | (?P
+ "(?:\\.|[^"\\])*" # double quoted string
+ | .[^,"']* # everything else
+ )
+ ''',
+ re.DOTALL
+)
+RE_LINE_INDENT_TAB = re.compile(r'^(?:(\t+)?(?:(/\*)|[^ \t\r\n])[^\r\n]*)?\r?\n$')
+RE_LINE_INDENT_SPACE = re.compile(r'^(?:((?: {4})+)?(?:(/\*)|[^ \t\r\n])[^\r\n]*)?\r?\n$')
+RE_TRAILING_SPACES = re.compile(r'^.*?[ \t]+\r?\n?$')
+RE_COMMENT_END = re.compile(r'\*/')
+PATTERN_COMMENT_INDENT_SPACE = r'^(%s *?[^\t\r\n][^\r\n]*)?\r?\n$'
+PATTERN_COMMENT_INDENT_TAB = r'^(%s[ \t]*[^ \t\r\n][^\r\n]*)?\r?\n$'
+
+
+E_MALFORMED = "E0"
+E_COMMENTS = "E1"
+E_COMMA = "E2"
+W_NL_START = "W1"
+W_NL_END = "W2"
+W_INDENT = "W3"
+W_TRAILING_SPACE = "W4"
+W_COMMENT_INDENT = "W5"
+
+
+VIOLATION_MSG = {
+ E_MALFORMED: 'JSON content is malformed.',
+ E_COMMENTS: 'Comments are not part of the JSON spec.',
+ E_COMMA: 'Dangling comma found.',
+ W_NL_START: 'Unnecessary newlines at the start of file.',
+ W_NL_END: 'Missing a new line at the end of the file.',
+ W_INDENT: 'Indentation Error.',
+ W_TRAILING_SPACE: 'Trailing whitespace.',
+ W_COMMENT_INDENT: 'Comment Indentation Error.'
+}
+
+
+class CheckJsonFormat(object):
+ """
+ Test JSON for format irregularities.
+
+ - Trailing spaces.
+ - Inconsistent indentation.
+ - New lines at end of file.
+ - Unnecessary newlines at start of file.
+ - Trailing commas.
+ - Malformed JSON.
+ """
+
+ def __init__(self, use_tabs=False, allow_comments=False):
+ """Setup the settings."""
+
+ self.use_tabs = use_tabs
+ self.allow_comments = allow_comments
+ self.fail = False
+
+ def index_lines(self, text):
+ """Index the char range of each line."""
+
+ self.line_range = []
+ count = 1
+ last = 0
+ for m in re.finditer('\n', text):
+ self.line_range.append((last, m.end(0) - 1, count))
+ last = m.end(0)
+ count += 1
+
+ def get_line(self, pt):
+ """Get the line from char index."""
+
+ line = None
+ for r in self.line_range:
+ if pt >= r[0] and pt <= r[1]:
+ line = r[2]
+ break
+ return line
+
+ def check_comments(self, text):
+ """
+ Check for JavaScript comments.
+
+ Log them and strip them out so we can continue.
+ """
+
+ def remove_comments(group):
+ return ''.join([x[0] for x in RE_LINE_PRESERVE.findall(group)])
+
+ def evaluate(m):
+ text = ''
+ g = m.groupdict()
+ if g["code"] is None:
+ if not self.allow_comments:
+ self.log_failure(E_COMMENTS, self.get_line(m.start(0)))
+ text = remove_comments(g["comments"])
+ else:
+ text = g["code"]
+ return text
+
+ content = ''.join(map(lambda m: evaluate(m), RE_COMMENT.finditer(text)))
+ return content
+
+ def check_dangling_commas(self, text):
+ """
+ Check for dangling commas.
+
+ Log them and strip them out so we can continue.
+ """
+
+ def check_comma(g, m, line):
+ # ,] -> ] or ,} -> }
+ self.log_failure(E_COMMA, line)
+ if g["square_comma"] is not None:
+ return g["square_ws"] + g["square_bracket"]
+ else:
+ return g["curly_ws"] + g["curly_bracket"]
+
+ def evaluate(m):
+ g = m.groupdict()
+ return check_comma(g, m, self.get_line(m.start(0))) if g["code"] is None else g["code"]
+
+ return ''.join(map(lambda m: evaluate(m), RE_TRAILING_COMMA.finditer(text)))
+
+ def log_failure(self, code, line=None):
+ """
+ Log failure.
+
+ Log failure code, line number (if available) and message.
+ """
+
+ if line:
+ print("%s: Line %d - %s" % (code, line, VIOLATION_MSG[code]))
+ else:
+ print("%s: %s" % (code, VIOLATION_MSG[code]))
+ self.fail = True
+
+ def check_format(self, file_name):
+ """Initiate the check."""
+
+ self.fail = False
+ comment_align = None
+ with codecs.open(file_name, encoding='utf-8') as f:
+ count = 1
+ for line in f:
+ indent_match = (RE_LINE_INDENT_TAB if self.use_tabs else RE_LINE_INDENT_SPACE).match(line)
+ end_comment = (
+ (comment_align is not None or (indent_match and indent_match.group(2))) and
+ RE_COMMENT_END.search(line)
+ )
+ # Don't allow empty lines at file start.
+ if count == 1 and line.strip() == '':
+ self.log_failure(W_NL_START, count)
+ # Line must end in new line
+ if not line.endswith('\n'):
+ self.log_failure(W_NL_END, count)
+ # Trailing spaces
+ if RE_TRAILING_SPACES.match(line):
+ self.log_failure(W_TRAILING_SPACE, count)
+ # Handle block comment content indentation
+ if comment_align is not None:
+ if comment_align.match(line) is None:
+ self.log_failure(W_COMMENT_INDENT, count)
+ if end_comment:
+ comment_align = None
+ # Handle general indentation
+ elif indent_match is None:
+ self.log_failure(W_INDENT, count)
+ # Enter into block comment
+ elif comment_align is None and indent_match.group(2):
+ alignment = indent_match.group(1) if indent_match.group(1) is not None else ""
+ if not end_comment:
+ comment_align = re.compile(
+ (PATTERN_COMMENT_INDENT_TAB if self.use_tabs else PATTERN_COMMENT_INDENT_SPACE) % alignment
+ )
+ count += 1
+ f.seek(0)
+ text = f.read()
+
+ self.index_lines(text)
+ text = self.check_comments(text)
+ self.index_lines(text)
+ text = self.check_dangling_commas(text)
+ try:
+ json.loads(text)
+ except Exception as e:
+ self.log_failure(E_MALFORMED)
+ print(e)
+ return self.fail
+
+
+if __name__ == "__main__":
+ import sys
+ cjf = CheckJsonFormat(False, True)
+ cjf.check_format(sys.argv[1])
diff --git a/.config/sublime-text-3/Packages/pygments/.gitignore b/.config/sublime-text-3/Packages/pygments/.gitignore
new file mode 100644
index 0000000..42658ed
--- /dev/null
+++ b/.config/sublime-text-3/Packages/pygments/.gitignore
@@ -0,0 +1,4 @@
+*.sublime-project
+*.sublime-workspace
+*.pyc
+.DS_Store
diff --git a/.config/sublime-text-3/Packages/pygments/README.md b/.config/sublime-text-3/Packages/pygments/README.md
new file mode 100644
index 0000000..69d606e
--- /dev/null
+++ b/.config/sublime-text-3/Packages/pygments/README.md
@@ -0,0 +1,51 @@
+# *pygments* module for Package Control
+
+This is the *[pygments][]* module bundled for usage with [Package Control][], a package manager for the [Sublime Text][] text editor.
+
+
+This repository | Pypi
+---- | ----
+![Latest tag](https://img.shields.io/github/tag/packagecontrol/pygments.svg) | [![pypi](https://img.shields.io/pypi/v/pygments.svg)][pypi]
+
+
+## How to use *pygments* as a dependency
+
+In order to tell Package Control that you are using the *pygments* module in your ST package, create a `dependencies.json` file in your package root with the following contents:
+
+```js
+{
+ "*": {
+ "*": [
+ "pygments"
+ ]
+ }
+}
+```
+
+If the file exists already, add `"pygments"` to the every dependency list.
+
+Then run the **Package Control: Satisfy Dependencies** command to make Package Control install the module for you locally (if you don't have it already).
+
+After all this you can use `import pygments` in any of your Python plugins.
+
+See also: [Documentation on Dependencies](https://packagecontrol.io/docs/dependencies)
+
+
+## How to update this repository (for contributors)
+
+1. Download the latest zip from [Bitbucket][].
+2. Delete everything inside the `all/` folder.
+3. Copy the `pygments/` folder to the `all/` folder.
+4. Commit changes and either create a pull request or create a tag directly in the format `v` (in case you have push access).
+
+
+## License
+
+The contents of the root folder in this repository are released under the *public domain*. The contents of the `all/` folder fall under *their own bundled licenses* displayed on top of every file. If not displayed, see the `LICENSE` file on pygments' [Bitbucket][].
+
+
+[pygments]: http://pygments.org
+[Package Control]: http://packagecontrol.io/
+[Sublime Text]: http://sublimetext.com/
+[pypi]: https://pypi.python.org/pypi/pygments
+[Bitbucket]: https://bitbucket.org/birkenfeld/pygments-main
diff --git a/.config/sublime-text-3/Packages/pygments/all/pygments/__init__.py b/.config/sublime-text-3/Packages/pygments/all/pygments/__init__.py
new file mode 100644
index 0000000..1ce34b2
--- /dev/null
+++ b/.config/sublime-text-3/Packages/pygments/all/pygments/__init__.py
@@ -0,0 +1,92 @@
+# -*- coding: utf-8 -*-
+"""
+ Pygments
+ ~~~~~~~~
+
+ Pygments is a syntax highlighting package written in Python.
+
+ It is a generic syntax highlighter for general use in all kinds of software
+ such as forum systems, wikis or other applications that need to prettify
+ source code. Highlights are:
+
+ * a wide range of common languages and markup formats is supported
+ * special attention is paid to details, increasing quality by a fair amount
+ * support for new languages and formats are added easily
+ * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image
+ formats that PIL supports, and ANSI sequences
+ * it is usable as a command-line tool and as a library
+ * ... and it highlights even Brainfuck!
+
+ The `Pygments tip`_ is installable with ``easy_install Pygments==dev``.
+
+ .. _Pygments tip:
+ http://bitbucket.org/birkenfeld/pygments-main/get/tip.zip#egg=Pygments-dev
+
+ :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+__version__ = '2.1a0'
+__docformat__ = 'restructuredtext'
+
+__all__ = ['lex', 'format', 'highlight']
+
+
+import sys
+
+from pygments.util import StringIO, BytesIO
+
+
+def lex(code, lexer):
+ """
+ Lex ``code`` with ``lexer`` and return an iterable of tokens.
+ """
+ try:
+ return lexer.get_tokens(code)
+ except TypeError as err:
+ if isinstance(err.args[0], str) and \
+ ('unbound method get_tokens' in err.args[0] or
+ 'missing 1 required positional argument' in err.args[0]):
+ raise TypeError('lex() argument must be a lexer instance, '
+ 'not a class')
+ raise
+
+
+def format(tokens, formatter, outfile=None):
+ """
+ Format a tokenlist ``tokens`` with the formatter ``formatter``.
+
+ If ``outfile`` is given and a valid file object (an object
+ with a ``write`` method), the result will be written to it, otherwise
+ it is returned as a string.
+ """
+ try:
+ if not outfile:
+ realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()
+ formatter.format(tokens, realoutfile)
+ return realoutfile.getvalue()
+ else:
+ formatter.format(tokens, outfile)
+ except TypeError as err:
+ if isinstance(err.args[0], str) and \
+ ('unbound method format' in err.args[0] or
+ 'missing 1 required positional argument' in err.args[0]):
+ raise TypeError('format() argument must be a formatter instance, '
+ 'not a class')
+ raise
+
+
+def highlight(code, lexer, formatter, outfile=None):
+ """
+ Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``.
+
+ If ``outfile`` is given and a valid file object (an object
+ with a ``write`` method), the result will be written to it, otherwise
+ it is returned as a string.
+ """
+ return format(lex(code, lexer), formatter, outfile)
+
+
+if __name__ == '__main__': # pragma: no cover
+ from pygments.cmdline import main
+ sys.exit(main(sys.argv))
diff --git a/.config/sublime-text-3/Packages/pygments/all/pygments/cmdline.py b/.config/sublime-text-3/Packages/pygments/all/pygments/cmdline.py
new file mode 100644
index 0000000..f5ea565
--- /dev/null
+++ b/.config/sublime-text-3/Packages/pygments/all/pygments/cmdline.py
@@ -0,0 +1,528 @@
+# -*- coding: utf-8 -*-
+"""
+ pygments.cmdline
+ ~~~~~~~~~~~~~~~~
+
+ Command line interface.
+
+ :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+from __future__ import print_function
+
+import sys
+import getopt
+from textwrap import dedent
+
+from pygments import __version__, highlight
+from pygments.util import ClassNotFound, OptionError, docstring_headline, \
+ guess_decode, guess_decode_from_terminal, terminal_encoding
+from pygments.lexers import get_all_lexers, get_lexer_by_name, guess_lexer, \
+ get_lexer_for_filename, find_lexer_class_for_filename, TextLexer
+from pygments.formatters.latex import LatexEmbeddedLexer, LatexFormatter
+from pygments.formatters import get_all_formatters, get_formatter_by_name, \
+ get_formatter_for_filename, find_formatter_class, \
+ TerminalFormatter # pylint:disable-msg=E0611
+from pygments.filters import get_all_filters, find_filter_class
+from pygments.styles import get_all_styles, get_style_by_name
+
+
+USAGE = """\
+Usage: %s [-l | -g] [-F [:]] [-f ]
+ [-O ] [-P