-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMarksy Convert.py
More file actions
208 lines (168 loc) · 5.84 KB
/
Marksy Convert.py
File metadata and controls
208 lines (168 loc) · 5.84 KB
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
import sys
import os
import subprocess
import sublime
import sublime_plugin
import threading
import json
global is_py3
is_py3 = sys.version_info >= (3, 0)
if is_py3:
from urllib.request import Request, urlopen
from urllib.error import URLError
else:
from urllib2 import Request, urlopen, URLError
global input_formats
global output_formats
global ext
input_formats = ['markdown', 'github', 'rst', 'textile', 'html', 'mediawiki', 'jira']
output_formats = ['markdown', 'rst', 'textile', 'html', 'mediawiki', 'jira', 'googlecode', 'jspwiki', 'moinmoin', 'trac']
ext = {'markdown': 'md','rst': 'rst','textile': 'textile','html': 'html','mediawiki': 'mwiki','jira': 'jira','googlecode': 'google','jspwiki': 'jwiki','moinmoin': 'moin','trac': 'trac'}
def display_message(message):
sublime.status_message(message)
sublime.active_window().run_command('sub_notify', {'title': "Marksy",'msg': message,'sound': False})
################################################################################
# Get the IO formats
################################################################################
class MarksyPromptCommand(sublime_plugin.WindowCommand):
i_format = None
o_format = None
def run(self, o_format):
self.o_format = o_format
inputs = ['Markdown','Github Flavored Markdown (GFM)','reStructuredText','Textile','HTML','Mediawiki','Jira (Confluence)']
input_list = []
text = 'Convert from: {0}'
for i in inputs:
input_list.append(text.format(i))
index = self.get_syntax(self.window.active_view())
if int(sublime.version()) >= 3000:
self.window.show_quick_panel(input_list, self.on_done, selected_index=index)
else:
self.window.show_quick_panel(input_list, self.on_done)
def on_done(self, i):
if i == -1:
print('Canceled')
return
self.i_format = input_formats[i]
self.window.active_view().run_command('marksy', {
'i_format':self.i_format,
'o_format':self.o_format
})
def get_syntax(self, view):
syntax = {
'markdown':['markdown','mdown','mkdn','md','mkd','mdwn','mdtxt','mdtext','text'],
'github':['github','gfm'],
'rst': ['rst'],
'textile': ['textile'],
'html': ['html','htm'],
'mediawiki': ['mwiki','wiki','mediawiki'],
'jira': ['jira','confluence'],
}
file_name = view.file_name()
if file_name == None:
return 0
ext = file_name.split('.')[-1]
for s in syntax:
if ext in s:
return input_formats.index(s)
return 0
################################################################################
# Begin the conversion
################################################################################
class MarksyCommand(sublime_plugin.TextCommand):
""" Use Marksy API to convert between various markup languages """
def run(self, edit, i_format, o_format):
settings = sublime.load_settings("Marksy.sublime-settings")
filename = self.get_file_name(self.view)
title = '{0}.{1}'.format(filename, ext[o_format])
contents = self.view.substr(sublime.Region(0, self.view.size()))
# Run the following in a new thread
t1 = MarksyApiCall({'input': i_format, 'output': o_format}, contents)
t1.start()
# Handle the thread
self.launch(edit, t1, title)
def get_file_name(self, view):
file_name = view.file_name()
if file_name == None:
return 'Untitled'
else:
split_char = '/' if sublime.platform() != 'windows' else '\\'
return file_name.split(split_char)[-1].split('.')[0]
def launch(self, edit, thread, title, i=0, direction=1):
if not thread.is_alive():
self.view.erase_status('marksy')
if thread.result == False:
display_message("There was an error converting the text.")
else:
self.view.run_command('marksy_launch', {'title': title, 'text':thread.result})
else:
before = i % 8
after = (7) - before
if not after:
direction = -1
if not before:
direction = 1
i += direction
self.view.set_status("marksy", "Marksy Convert [%s=%s]" % (' ' * before, ' ' * after))
sublime.set_timeout(lambda: self.launch(edit, thread, title, i, direction), 100)
################################################################################
# Load the result in a new window
################################################################################
class MarksyLaunchCommand(sublime_plugin.TextCommand):
""" Launch the Marksy converted text in a new window """
def run(self, edit, title, text):
new_view = self.view.window().new_file()
new_view.set_name(title)
new_view.insert(edit, 0, text)
display_message('Text has been converted successfully.')
################################################################################
# Talk to the API to convert the text
################################################################################
class MarksyApiCall(threading.Thread):
def __init__(self, formats, contents):
self.error = False
self.result = None
self.input = formats['input']
self.output = formats['output']
self.text = contents
threading.Thread.__init__(self)
def run(self):
if self.input not in input_formats:
display_message('Invalid Input format')
return
elif self.output not in output_formats:
display_message('Invalid Output format')
return
url = 'http://marksy.arc90.com/convert'
payload = {
'input': self.input,
'output': self.output,
'text': self.text
}
# Convert to json
data = json.dumps(payload)
# Setup HTTP headers
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
# Encode the data
data = data.encode('utf-8')
# Create and send the request
r = Request(url, data, headers)
try:
response = urlopen(r)
if is_py3:
self.result = json.loads(response.read().decode('utf-8'))
else:
self.result = json.loads(response.read())
self.result = self.result['payload']
return
except URLError as e:
self.result = False
self.error = e.reason
return
except:
self.result = False
self.error = True
raise