-
Notifications
You must be signed in to change notification settings - Fork 1
/
OutlineNotesPublisher.py
executable file
·251 lines (222 loc) · 7.43 KB
/
OutlineNotesPublisher.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import sublime, sublime_plugin
import re
"""
Configure using Preferences ➡ Settings
{
// ...
"outline_to_html": {
// "css": "", // Override CSS.
// "title": "", // Override Title (or use meta comment //title ...)
// "header": "", // Add to <head>
// "body": "", // Add to <body>
// "footer": "", // Add before </body>
}
}
"""
class OutlineToHtml(sublime_plugin.TextCommand):
# Default settings.
HTML_TITLE = "Hello World" # Replace using //title New Title
HTML_CSS = """
body { font-size: 1em; font-family: "sans"; background: #222; color: #aaa; padding: 2rem 2.4rem; }
ul { list-style-type: circle; }
a { color: white; }
"""
HTML_HEADER_EXTRA = ''
HTML_BODY_EXTRA = ''
HTML_FOOTER_EXTRA = ''
INDENT_TABS = '\t' # One tab is typical.
INDENT_SPACES = ' ' # If you use something other than 4 spaces.
WS = INDENT_TABS # Whitespace.
HTML_WS = f"\n{WS*2}"
def run(self, edit):
s = OutlineToHtml
# Can be set by User Preferences.
_s = sublime.load_settings("Preferences.sublime-settings")
s.HTML_TITLE = _s.get("outline_to_html", {}).get("title", s.HTML_TITLE)
s.HTML_CSS = _s.get("outline_to_html", {}).get("css", s.HTML_CSS)
s.HTML_HEADER_EXTRA = _s.get("outline_to_html", {}).get("header", s.HTML_HEADER_EXTRA)
s.HTML_BODY_EXTRA = _s.get("outline_to_html", {}).get("body", s.HTML_BODY_EXTRA)
s.HTML_FOOTER_EXTRA = _s.get("outline_to_html", {}).get("footer", s.HTML_FOOTER_EXTRA)
parser = OutlineToHtmlCreator()
# Get current selection
sels = self.view.sel()
sels_parsed = 0
if(len(sels) > 0):
for sel in sels:
# Make sure selection isn't just a cursor
if(abs(sel.b - sel.a) > 0):
self.fromRegion(parser, sel, edit)
sels_parsed += 1
# All selections just cursor marks?
if(sels_parsed == 0):
region = sublime.Region(0, self.view.size() - 1)
self.fromRegion(parser, region, edit)
def fromRegion(self, parser, region, edit):
lines = self.view.line(region)
text = self.view.substr(lines)
indented = parser.fromSelection(text)
newview = self.view.window().new_file()
newview.insert(edit, 0, indented)
class OutlineToHtmlCreator:
def fromSelection(self, text):
return self.create(text.split("\n"))
def tagify(self, text, token, token_end, formatter, remove_token=False):
pos = 0
found = True
while found:
found = False
''' Attempt to convert tokens into tags. '''
if (pos := text.find(token, pos)) >= 0:
found = True
url = ''
url_name = ''
url_end = 0
token_remove = len(token)
# Bail if this token is inside a quote (ex: HTML tag attribute)
if text[pos-1] == '"' or text[pos-1] == "'":
pos = pos+1
continue
# Bail if this ")[" token does not have supporting "[" or ")"
if token == "](":
if text.find('[', 0, pos) == -1 or text.find(')', pos) == -1:
return text
# Extract name.
if token == "](":
url_name = text[text.find('[', 0, pos)+1:pos]
# Extract URL
partial = text[pos:]
for i,c in enumerate(partial):
if c.isspace() or c == token_end: # Will end at whitespace or token_end
url_end = pos+i
break
if not url_end: # We reached EOL
url_end = len(text)
url = text[pos+token_remove:url_end]
if token == "](": # Special case.
text = text[:text.find('[', 0, pos)] + formatter.format(url, url_name) + text[url_end+len(token_end):]
else:
text = text[:pos] + formatter.format(url, url_name) + text[url_end:]
return text
def create(self, text_iterable):
s = OutlineToHtml
indent_level_previous = 0
inside_code_block = False
output = ""
# Compile whitespace regex for reuse.
regex_indent = re.compile(f"^({s.INDENT_TABS}|{s.INDENT_SPACES})")
# Parse text
for line in text_iterable:
# ```lang Code block.
if(inside_code_block or line.find("```") == 0):
if not inside_code_block and line.find("```") == 0:
if line == "```\n":
language = 'html'
else:
line = line.replace("```", "")
language = line.split("\n")[0]
output += f"<pre><code class='language-{language}'>"
inside_code_block = True
continue
# End of code block.
elif inside_code_block and line.find("```") == 0:
line = line.replace("```", "")
output += f"{line}</code></pre>"
inside_code_block = False
continue
else:
# Inside code block.
output += f"{line}\n"
continue
# // Metadata comments.
if(line.find("//title ") == 0):
line = line.replace("//title ", "")
s.HTML_TITLE = line
continue
# // Comments.
if(line.find("//") == 0):
continue # Skip line.
# Levels of indentation
indent_level = 0
while(regex_indent.match(line)):
line = regex_indent.sub("", line)
indent_level += 1
indentDiff = indent_level - indent_level_previous
# Does a new level of indentation need to be created?
if(indentDiff >= 1):
output += f"{s.HTML_WS}{s.WS*(indent_level-1)}<ul>"
'''
# W3C compliant, but UGLY. Leave for now.
if indent_level > 1:
output += f"{s.HTML_WS}{s.WS*(indent_level-1)}<li><ul>"
else:
output += f"{s.HTML_WS}{s.WS*(indent_level-1)}<ul>"
'''
# Outdent
elif(indentDiff <= -1):
outdent_level = abs(indentDiff)
for i in range(outdent_level):
output += f"{s.HTML_WS}{s.WS*(indent_level+outdent_level-i-1)}</ul>"
'''
# W3C compliant, but UGLY. Leave for now.
if indent_level+outdent_level-i > 1:
output += f"{s.HTML_WS}{s.WS*(indent_level+outdent_level-i-1)}</ul></li>"
else:
output += f"{s.HTML_WS}{s.WS*(indent_level+outdent_level-i-1)}</ul>"
'''
# Special format line.
prefix = ""
suffix = ""
line = line.strip()
special = {
"# ": "h1",
"## ": "h2",
"### ": "h3",
"#### ": "h4",
"##### ": "h5",
"###### ": "h6",
"** ": "strong",
"* ": "em",
}
for key,value in special.items():
if line.startswith(key):
line = line.replace(key, "")
prefix = f"<{value}>"
suffix = f"</{value}>"
line = self.tagify(line, "](", ')', '<a href="{0}">{1}</a>', remove_token=True) # Named link.
line = self.tagify(line, "https://", ')', '<a href="https://{0}">{0}</a>')
line = self.tagify(line, "http://", ')', '<a href="http://{0}">{0}</a>')
if indent_level > 0:
output += f"{s.HTML_WS}{s.WS*(indent_level)}" + "<li>" + prefix + line + suffix + "</li>"
elif prefix in ['<strong>', '<em>']:
output += f"{s.HTML_WS}{s.WS*(indent_level)}" + prefix + line + suffix + "<br />"
elif prefix:
output += f"{s.HTML_WS}{s.WS*(indent_level)}" + prefix + line + suffix
else:
output += f"{s.HTML_WS}{s.WS*(indent_level)}" + prefix + line + suffix + "<br />" # Plain text.
indent_level_previous = indent_level
HTML_HEADER = f"""<!doctype html>
<html lang='en'>
<head>
<title>{s.HTML_TITLE}</title>
<style>{s.HTML_CSS}</style>
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/themes/prism-twilight.min.css" rel="stylesheet" />
{s.HTML_HEADER_EXTRA}
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/components/prism-core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/plugins/autoloader/prism-autoloader.min.js"></script>
{s.HTML_BODY_EXTRA}
"""
HTML_FOOTER = f"""{s.HTML_FOOTER_EXTRA}
</body>
</html>
"""
return f"{HTML_HEADER}{output}{HTML_FOOTER}"
"""
# TODO: Unused currently. For generating from full directories.
def fromFile(self, filename):
input = open(filename, "rU")
output = self.create(input)
input.close()
return output
"""