Compare commits

...

8 Commits

Author SHA1 Message Date
bbbeae6fe9 center tables <th>s #12 2017-01-26 12:24:09 +11:00
271c7c619a fix bug: remove hard-coded color in CSS 2017-01-26 11:47:18 +11:00
8cc6b2b263 fix typo, add a tiny bit of doc to the code 2017-01-26 11:30:56 +11:00
c7961ce94c update stylesheet for tables 2017-01-26 11:03:52 +11:00
eae91fa428 add separator for tables' header 2017-01-26 10:57:12 +11:00
6f18e8e4a2 remove .prettify() @ pre_with_pr (bs4);
fix spaces in tables too
2017-01-26 10:43:04 +11:00
48c1800065 use bs4 for pre2br; fix style sheet for tables
Also: load default.css from the actual file if the package is not
zipped.
2017-01-26 10:36:52 +11:00
bad1cb74c6 MDtables base OK. Use bs4. #12 2017-01-26 09:21:49 +11:00
7 changed files with 111 additions and 39 deletions

View File

@ -7,6 +7,7 @@ import os.path
from html.parser import HTMLParser from html.parser import HTMLParser
from .lib import markdown2 as md2 from .lib import markdown2 as md2
from .lib.pre_tables import pre_tables
from .escape_amp import * from .escape_amp import *
from .functions import * from .functions import *
from .setting_names import * from .setting_names import *
@ -20,8 +21,13 @@ USER_STYLE_FILE = os.path.join(os.path.dirname(__folder__), 'User', 'MarkdownLiv
# used to store the phantom's set # used to store the phantom's set
windows_phantom_set = {} windows_phantom_set = {}
def plugin_loaded(): def plugin_loaded():
global DEFAULT_STYLE_FILE global DEFAULT_STYLE_FILE
if os.path.exists(os.path.join(__folder__, 'default.css')):
with open(os.path.join(__folder__, 'default.css')) as fp:
DEFAULT_STYLE_FILE = fp.read()
else:
DEFAULT_STYLE_FILE = sublime.load_resource('Packages/MarkdownLivePreview/default.css') DEFAULT_STYLE_FILE = sublime.load_resource('Packages/MarkdownLivePreview/default.css')
def get_preview_name(md_view): def get_preview_name(md_view):
@ -48,35 +54,31 @@ def get_style():
content += '\n' + fp.read() + '\n' content += '\n' + fp.read() + '\n'
return content return content
def show_html(md_view, preview): def markdown2html(md, basepath):
global windows_phantom_set html = ''
html = [] html += '<style>\n{}\n</style>\n'.format(get_style())
html.append('<style>\n{}\n</style>'.format(get_style())) # pre_with_br
html.append(pre_with_br(md2.markdown(get_view_content(md_view), html += pre_with_br(pre_tables(md2.markdown(md, extras=['fenced-code-blocks',
extras=['fenced-code-blocks', 'no-code-highlighting', 'tables'])))
'no-code-highlighting']))) # the option no-code-highlighting does not exists in the official version of markdown2 for now
# the option no-code-highlighting does not exists
# in the official version of markdown2 for now
# I personaly edited the file (markdown2.py:1743) # I personaly edited the file (markdown2.py:1743)
html = '\n'.join(html)
html = html.replace('&nbsp;', '&nbspespace;') # save where are the spaces html = html.replace('&nbsp;', '&nbspespace;') # save where are the spaces
html = HTMLParser().unescape(html)
html = escape_amp(html)
# exception, again, because <pre> aren't supported by the phantoms # exception, again, because <pre> aren't supported by the phantoms
html = html.replace('&nbspespace;', '<i class="space">.</i>') html = html.replace('&nbspespace;', '<i class="space">.</i>')
html = replace_img_src_base64(html, basepath=os.path.dirname( html = replace_img_src_base64(html, basepath=os.path.dirname(basepath))
md_view.file_name())) return html
def show_html(md_view, preview):
global windows_phantom_set
html = markdown2html(get_view_content(md_view), os.path.dirname(md_view.file_name()))
phantom_set = windows_phantom_set.setdefault(preview.window().id(), phantom_set = windows_phantom_set.setdefault(preview.window().id(),
sublime.PhantomSet(preview, sublime.PhantomSet(preview, 'markdown_live_preview'))
'markdown_live_preview'))
phantom_set.update([sublime.Phantom(sublime.Region(0), html, sublime.LAYOUT_BLOCK, phantom_set.update([sublime.Phantom(sublime.Region(0), html, sublime.LAYOUT_BLOCK,
lambda href: sublime.run_command('open_url', lambda href: sublime.run_command('open_url', {'url': href}))])
{'url': href}))])
# lambda href: sublime.run_command('open_url', {'url': href}) # lambda href: sublime.run_command('open_url', {'url': href})
# get the "ratio" of the markdown view's position. # get the "ratio" of the markdown view's position.

View File

@ -15,7 +15,6 @@ blockquote {
font-style: italic; font-style: italic;
display: block; display: block;
margin-left: 30px; margin-left: 30px;
border: 1px solid red;
} }
code { code {
@ -24,24 +23,32 @@ code {
background-color: var(--light-bg); background-color: var(--light-bg);
margin: 0; margin: 0;
border-radius: 3px; border-radius: 3px;
margin: 5px;
} }
pre { pre {
display: block; display: block;
margin-top: 20px; margin-top: 20px;
line-height: 1.7;
background-color: var(--light-bg); background-color: var(--light-bg);
padding-left: 10px; padding-left: 10px;
padding-top: 5px;
padding-bottom: 5px;
width: 100%; width: 100%;
border-radius: 3px; border-radius: 3px;
} }
pre code { pre code {
padding-left: 0; padding: 0;
} }
pre code .space { pre code .space {
color: var(--light-bg) color: var(--light-bg);
}
pre.table {
background-color: var(--backgroud);
}
pre.table code {
background-color: var(--backgroud);
padding: 0;
margin: 0;
} }
kbd { kbd {

7
dependencies.json Normal file
View File

@ -0,0 +1,7 @@
{
"*": {
"*": [
"bs4"
]
}
}

View File

@ -7,7 +7,6 @@ import os.path
class MLPDevListener(sublime_plugin.EventListener): class MLPDevListener(sublime_plugin.EventListener):
def on_post_save(self, view): def on_post_save(self, view):
# return
if not (os.path.dirname(__file__) in view.file_name() and if not (os.path.dirname(__file__) in view.file_name() and
view.file_name().endswith('.py')): view.file_name().endswith('.py')):
return return
@ -16,5 +15,6 @@ class MLPDevListener(sublime_plugin.EventListener):
'MarkdownLivePreview.py'), 'MarkdownLivePreview.py'),
'scripts': ['image_manager', 'functions', 'MLPApi', 'scripts': ['image_manager', 'functions', 'MLPApi',
'setting_names'], 'setting_names'],
'folders': ['lib'],
'quiet': True 'quiet': True
}) })

View File

@ -4,6 +4,7 @@ import os.path
import sublime import sublime
import re import re
from .image_manager import ImageManager from .image_manager import ImageManager
from bs4 import BeautifulSoup
def plugin_loaded(): def plugin_loaded():
global error404, loading global error404, loading
@ -89,14 +90,9 @@ def get_settings():
def pre_with_br(html): def pre_with_br(html):
"""Because the phantoms of sublime text does not support <pre> blocks """Because the phantoms of sublime text does not support <pre> blocks
this function replaces every \n with a <br> in a <pre>""" this function replaces every \n with a <br> in a <pre>"""
soup = BeautifulSoup(html)
while True: for pre in soup.find_all('pre'):
obj = re.search(r'<pre>(.*?)</pre>', html, re.DOTALL) code = pre.find('code')
if not obj: code.replaceWith(BeautifulSoup(''.join(str(node) for node in pre.contents) \
break .replace('\n', '<br/>').replace(' ', '<i class="space">.</i>'), 'html.parser'))
html = list(html) return str(soup).replace('<br/>', '<br />')
html[obj.start(0):obj.end(0)] = '<pre >' + ''.join(html[obj.start(1):obj.end(1)]) \
.replace('\n', '<br>') \
.replace(' ', '&nbsp;') + '</pre>'
html = ''.join(html)
return html

52
lib/pre_tables.py Normal file
View File

@ -0,0 +1,52 @@
# -*- encoding: utf-8 -*-
"""
'pre_tables' transform *html* tables into markdown tables, and put them in some <pre><code> tags
"""
from bs4 import BeautifulSoup
def python_table(s_table):
"""Transform BeautifulSoup table into list of list"""
rows = []
for row in s_table.find_all('tr'):
# rows.append(list(map( lambda td: td.text, row.find_all(['th', 'td']) )))
rows.append(row.find_all(['th', 'td']))
return rows
def pre_table(s_table):
rows = python_table(s_table)
cols_width = [len(cell) for cell in rows[0]]
for j, row in enumerate(rows):
for i, cell in enumerate(row):
if cols_width[i] < len(cell.text):
cols_width[i] = len(cell.text)
text = '<pre class="table"><code>'
for i, row in enumerate(rows):
if i == 1:
for j, cell in enumerate(row):
text += '|' + '-' * (cols_width[j] + 2)
text += '|\n'
for j, cell in enumerate(row):
text += '| '
if cell.name == 'th':
title = ' ' * ((cols_width[j] - len(cell.text)) // 2) \
+ ''.join(str(node) for node in cell.contents) \
+ ' ' * int(round((cols_width[j] - len(cell.text)) / 2 ) + 1)
# + 1 because of the added space before the closing | of each cell
if cols_width[j] + 1 != len(title):
title += ' '
text += title
else:
text += ''.join(str(node) for node in cell.contents) \
+ ' ' * (cols_width[j] - len(cell.text) + 1)
text += '|\n'
text += '</pre></code>'
return text
def pre_tables(html):
soup = BeautifulSoup(html, 'html.parser')
for table in soup.find_all('table'):
table.replace_with(BeautifulSoup(pre_table(table), 'html.parser'))
return str(soup)

View File

@ -16,7 +16,15 @@ if you is moods.curious:
- you need - you need
- todos - todos
![Sublime Text Logo](https://upload.wikimedia.org/wikipedia/en/4/4c/Sublime_Text_Logo.png) | ID | Name |
|-----------|-------|
| 56 | Matt |
| 42 | Colin |
| 23 | Lisa |
| 45 | John |
| `<table>` | `><` |
[Sublime Text Logo](https://upload.wikimedia.org/wikipedia/en/4/4c/Sublime_Text_Logo.png)
Some plugin I just *need*: Some plugin I just *need*: