Skip to content
This repository has been archived by the owner on May 17, 2018. It is now read-only.

Commit

Permalink
Merge pull request #308 from facelessuser/master
Browse files Browse the repository at this point in the history
Bug fixes
  • Loading branch information
facelessuser committed Dec 8, 2015
2 parents adcf252 + ee06ade commit 24bc7f8
Show file tree
Hide file tree
Showing 7 changed files with 195 additions and 153 deletions.
163 changes: 82 additions & 81 deletions MarkdownPreview.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ def is_ST3():


if is_ST3():
from .helper import INSTALLED_DIRECTORY
from . import desktop
from .markdown_settings import Settings
from .markdown_wrapper import StMarkdown as Markdown
from .helper import INSTALLED_DIRECTORY
from urllib.request import urlopen, url2pathname, pathname2url
from urllib.parse import urlparse, urlunparse
from urllib.error import HTTPError, URLError
Expand All @@ -43,10 +43,10 @@ def Request(url, data, headers):
unicode_str = str

else:
from helper import INSTALLED_DIRECTORY
import desktop
from markdown_settings import Settings
from markdown_wrapper import StMarkdown as Markdown
from helper import INSTALLED_DIRECTORY
from urllib2 import Request, urlopen, HTTPError, URLError
from urllib import quote, url2pathname, pathname2url
from urlparse import urlparse, urlunparse
Expand Down Expand Up @@ -225,50 +225,50 @@ def repl_relative(m, base_path, relative_path):
link = m.group(0)
try:
scheme, netloc, path, params, query, fragment, is_url, is_absolute = parse_url(m.group('path')[1:-1])
except:
# Parsing crashed an burned; no need to continue.
return link

if not is_url:
# Get the absolute path of the file or return
# if we can't resolve the path
path = url2pathname(path)
abs_path = None
if (not is_absolute):
# Convert current relative path to absolute
temp = os.path.normpath(os.path.join(base_path, path))
if os.path.exists(temp):
abs_path = temp.replace("\\", "/")
elif os.path.exists(path):
abs_path = path

if abs_path is not None:
convert = False
# Determine if we should convert the relative path
# (or see if we can realistically convert the path)
if (sublime.platform() == "windows"):
# Make sure basepath starts with same drive location as target
# If they don't match, we will stay with absolute path.
if (base_path.startswith('//') and base_path.startswith('//')):
convert = True
else:
base_drive = RE_WIN_DRIVE_PATH.match(base_path)
path_drive = RE_WIN_DRIVE_PATH.match(abs_path)
if (
(base_drive and path_drive) and
base_drive.group('drive').lower() == path_drive.group('drive').lower()
):

if not is_url:
# Get the absolute path of the file or return
# if we can't resolve the path
path = url2pathname(path)
abs_path = None
if (not is_absolute):
# Convert current relative path to absolute
temp = os.path.normpath(os.path.join(base_path, path))
if os.path.exists(temp):
abs_path = temp.replace("\\", "/")
elif os.path.exists(path):
abs_path = path

if abs_path is not None:
convert = False
# Determine if we should convert the relative path
# (or see if we can realistically convert the path)
if (sublime.platform() == "windows"):
# Make sure basepath starts with same drive location as target
# If they don't match, we will stay with absolute path.
if (base_path.startswith('//') and base_path.startswith('//')):
convert = True
else:
# OSX and Linux
convert = True
else:
base_drive = RE_WIN_DRIVE_PATH.match(base_path)
path_drive = RE_WIN_DRIVE_PATH.match(abs_path)
if (
(base_drive and path_drive) and
base_drive.group('drive').lower() == path_drive.group('drive').lower()
):
convert = True
else:
# OSX and Linux
convert = True

# Convert the path, url encode it, and format it as a link
if convert:
path = pathname2url(os.path.relpath(abs_path, relative_path).replace('\\', '/'))
else:
path = pathname2url(abs_path)
link = '%s"%s"' % (m.group('name'), urlunparse((scheme, netloc, path, params, query, fragment)))
# Convert the path, url encode it, and format it as a link
if convert:
path = pathname2url(os.path.relpath(abs_path, relative_path).replace('\\', '/'))
else:
path = pathname2url(abs_path)
link = '%s"%s"' % (m.group('name'), urlunparse((scheme, netloc, path, params, query, fragment)))
except:
# Parsing crashed an burned; no need to continue.
pass

return link

Expand All @@ -279,15 +279,16 @@ def repl_absolute(m, base_path):

try:
scheme, netloc, path, params, query, fragment, is_url, is_absolute = parse_url(m.group('path')[1:-1])
except Exception:
return link

if (not is_absolute and not is_url):
path = url2pathname(path)
temp = os.path.normpath(os.path.join(base_path, path))
if os.path.exists(temp):
path = pathname2url(temp.replace("\\", "/"))
link = '%s"%s"' % (m.group('name'), urlunparse((scheme, netloc, path, params, query, fragment)))
if (not is_absolute and not is_url):
path = url2pathname(path)
temp = os.path.normpath(os.path.join(base_path, path))
if os.path.exists(temp):
path = pathname2url(temp.replace("\\", "/"))
link = '%s"%s"' % (m.group('name'), urlunparse((scheme, netloc, path, params, query, fragment)))
except Exception:
# Parsing crashed an burned; no need to continue.
pass

return link

Expand Down Expand Up @@ -609,42 +610,42 @@ def postprocessor_base64(self, html):

def b64(m):
import base64
src = url2pathname(m.group('path')[1:-1])
data = m.group(0)
base_path = self.settings.get('builtin').get("basepath")
if base_path is None:
base_path = ""

# Format the link
absolute = False
if src.startswith('file://'):
src = src.replace('file://', '', 1)
if sublime.platform() == "windows" and not src.startswith('//'):
src = src.lstrip("/")
absolute = True
elif sublime.platform() == "windows" and RE_WIN_DRIVE.match(src) is not None:
absolute = True

# Make sure we are working with an absolute path
if not src.startswith(exclusion_list):
if absolute:
src = os.path.normpath(src)
else:
src = os.path.normpath(os.path.join(base_path, src))
try:
src = url2pathname(m.group('path')[1:-1])
base_path = self.settings.get('builtin').get("basepath")
if base_path is None:
base_path = ""

# Format the link
absolute = False
if src.startswith('file://'):
src = src.replace('file://', '', 1)
if sublime.platform() == "windows" and not src.startswith('//'):
src = src.lstrip("/")
absolute = True
elif sublime.platform() == "windows" and RE_WIN_DRIVE.match(src) is not None:
absolute = True

# Make sure we are working with an absolute path
if not src.startswith(exclusion_list):
if absolute:
src = os.path.normpath(src)
else:
src = os.path.normpath(os.path.join(base_path, src))

if os.path.exists(src):
ext = os.path.splitext(src)[1].lower()
for b64_ext in file_types:
if ext in b64_ext:
try:
if os.path.exists(src):
ext = os.path.splitext(src)[1].lower()
for b64_ext in file_types:
if ext in b64_ext:
with open(src, "rb") as f:
data = " src=\"data:%s;base64,%s\"" % (
file_types[b64_ext],
base64.b64encode(f.read()).decode('ascii')
)
except Exception:
pass
break
break
except Exception:
pass
return data

def repl(m):
Expand Down
9 changes: 9 additions & 0 deletions helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@
import re
import sys

# Make sure unicodedata is accesible,
# if not add the python executable path to sys.path
# so we can properly import it (ST2 Windows).
try:
import unicodedata
except Exception:
sys.path.append(os.path.dirname(sys.executable))
import unicodedata

'''
INSTALLED_DIRECTORY - The install directory name for this plugin.
Expand Down
49 changes: 33 additions & 16 deletions markdown/extensions/headeranchor.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,18 @@
from __future__ import absolute_import
from ..extensions import Extension
from ..treeprocessors import Treeprocessor
try:
import unicodedata
except Exception:
unicodedata = None
import unicodedata
import re
from .toc import slugify, stashedHTML2text, unique, TocExtension
import sys
from .. import util
from .toc import slugify, stashedHTML2text, unique, TocExtension

PY3 = sys.version_info >= (3, 0) and sys.version_info < (4, 0)

if PY3:
from urllib.parse import quote # noqa
else:
from urllib import quote # noqa

LINK = (
'<a '
Expand All @@ -49,17 +54,29 @@
RE_WORD = re.compile(r'''[^\w\- ]''', re.UNICODE)


if unicodedata is not None:
# ST2 may bomb on unicode data, so we will ignore this if it happens.
def uslugify(text, sep):
"""Custom slugify."""
def uslugify(text, sep):
"""Unicode slugify (utf-8)."""

if text is None:
return ''
# Normalize, Strip html tags, strip leading and trailing whitespace, and lower
tag_id = RE_TAGS.sub('', unicodedata.normalize('NFKD', text)).strip().lower()
# Remove non word characters, non spaces, and non dashes, and convert spaces to dashes.
return RE_WORD.sub('', tag_id).replace(' ', sep)


def uslugify_encoded(text, sep):
"""Custom slugify (percent encoded)."""

if text is None:
return ''
# Normalize, Strip html tags, strip leading and trailing whitespace, and lower
tag_id = RE_TAGS.sub('', unicodedata.normalize('NFKD', text)).strip().lower()
# Remove non word characters, non spaces, and non dashes, and convert spaces to dashes.
return RE_WORD.sub('', tag_id).replace(' ', sep)
if text is None:
return ''
# Strip html tags and lower
tag_id = RE_TAGS.sub('', unicodedata.normalize('NFKD', text)).lower()
# Remove non word characters or non spaces and dashes
# Then convert spaces to dashes
tag_id = RE_WORD.sub('', tag_id).replace(' ', sep)
# Encode anything that needs to be
return quote(tag_id.encode('utf-8'))


class HeaderAnchorTreeprocessor(Treeprocessor):
Expand All @@ -78,7 +95,7 @@ def get_settings(self):
self.slugify = self.config['slugify']
self.separator = self.config['separator']
self.use_toc_settings = self.config['use_toc_settings']
if TocExtension and self.use_toc_settings:
if self.use_toc_settings:
for ext in self.markdown.registeredExtensions:
if isinstance(ext, TocExtension):
self.separator = ext.config['separator'][0]
Expand Down
9 changes: 7 additions & 2 deletions markdown/extensions/magiclink.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
"""
Magic Link.
pymdownx.magiclink
An extension for Python Markdown.
Find http|ftp links and email address and turn them to actual links
MIT license.
Copyright (c) 2014 Isaac Muse <[email protected]>
Copyright (c) 2014 - 2015 Isaac Muse <[email protected]>
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:
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.
Expand Down
Loading

0 comments on commit 24bc7f8

Please sign in to comment.