MDtables base OK. Use bs4. #12

This commit is contained in:
Mathieu PATUREL
2017-01-26 09:21:49 +11:00
parent 4198504fd1
commit bad1cb74c6
7 changed files with 111 additions and 21 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,6 +21,7 @@ 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
DEFAULT_STYLE_FILE = sublime.load_resource('Packages/MarkdownLivePreview/default.css') DEFAULT_STYLE_FILE = sublime.load_resource('Packages/MarkdownLivePreview/default.css')
@ -48,35 +50,32 @@ 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())) sublime.set_clipboard(html)
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

@ -9,13 +9,13 @@ body {
font-family: "Open Sans", sans-serif; font-family: "Open Sans", sans-serif;
background-color: var(--background); background-color: var(--background);
font-size: 15px; font-size: 15px;
color: #333;
} }
blockquote { blockquote {
font-style: italic; font-style: italic;
display: block; display: block;
margin-left: 30px; margin-left: 30px;
border: 1px solid red;
} }
code { code {

7
dependencies.json Normal file
View File

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

View File

@ -16,5 +16,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

@ -5,6 +5,7 @@ import sublime
import re import re
from .image_manager import ImageManager from .image_manager import ImageManager
def plugin_loaded(): def plugin_loaded():
global error404, loading global error404, loading
loading = sublime.load_resource('Packages/MarkdownLivePreview/loading.txt') loading = sublime.load_resource('Packages/MarkdownLivePreview/loading.txt')

72
lib/pre_tables.py Normal file
View File

@ -0,0 +1,72 @@
# -*- encoding: utf-8 -*-
from bs4 import BeautifulSoup
html = """
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>56</td>
<td>Matt</td>
</tr>
<tr>
<td>42</td>
<td>Colin</td>
</tr>
<tr>
<td>23</td>
<td>Lisa</td>
</tr>
<tr>
<td>45</td>
<td>John</td>
</tr>
<tr>
<td><code>&lt;table&gt;</code></td>
<td><code>&lt;e&gt;</code></td>
</tr>
</tbody>
</table>
<p><a href="https://upload.wikimedia.org/wikipedia/en/4/4c/Sublime_Text_Logo.png">Sublime Text Logo</a></p>
"""
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><code>'
for i, row in enumerate(rows):
for j, cell in enumerate(row):
text += '| ' + ''.join(str(node) for node in cell.contents) + ' ' * (cols_width[j] - len(cell.text))
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)
if __name__ == "__main__":
# CSW: ignore
print(pre_tables(html))

View File

@ -16,7 +16,17 @@ 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*: