def commit(): token = get_token() fpath = editor.get_path() fname = os.path.basename(fpath) m = console.input_alert('Edit Description','Enter a new description:','') if m == '': m = None gist_id = get_gist_id() res = commit_or_create(gist_id,{fpath:editor.get_text()},token,m) try: id = res['id'] except KeyError: if gist_id: f = console.alert('Commit Failed', 'Do you have permission to commit? Would you like to fork?','Fork') if f == 1: res = fork(gist_id,token) try: id = res['id'] except KeyError: console.alert('Fork Error', 'There was a problem with the fork') else: set_gist_id(id) res = commit_or_create(id,{fpath:editor.get_text()},token,m) try: id = res['id'] except KeyError: console.alert('Commit Error', 'Commit still failed, maybe fork too') else: if gist_id is None: set_gist_id(id) print('success!')
def unindent(self): """unindent selected lines all the way""" import editor import textwrap i=editor.get_line_selection() t=editor.get_text() editor.replace_text(i[0],i[1], textwrap.dedent(t[i[0]:i[1]])) editor.set_selection(i[0],i[1]-len(t)+len(editor.get_text()))
def indent(self): """indent selected lines by one tab""" import editor import re i=editor.get_line_selection() t=editor.get_text() # replace every occurance of newline with newline plus indent, except last newline editor.replace_text(i[0],i[1]-1,INDENTSTR+re.sub(r'\n',r'\n'+INDENTSTR,t[i[0]:i[1]-1])) editor.set_selection(i[0],i[1]-len(t)+len(editor.get_text()))
def comment(self): """" comment out selected lines""" import editor import re COMMENT='#' i=editor.get_line_selection() t=editor.get_text() # replace every occurance of newline with ewline plus COMMENT, except last newline editor.replace_text(i[0],i[1]-1,COMMENT+re.sub(r'\n',r'\n'+COMMENT,t[i[0]:i[1]-1])) editor.set_selection(i[0],i[1]-len(t)+len(editor.get_text()))
def uncomment(self): """" uncomment selected lines""" import editor import re COMMENT='#' i=editor.get_line_selection() t=editor.get_text() # replace every occurance of newline # with newline, except last newline if all( [x.startswith('#') for x in t[i[0]:i[1]-1].split(r'\n')]): editor.replace_text(i[0],i[1]-1,re.sub(r'^'+COMMENT,r'',t[i[0]:i[1]-1],flags=re.MULTILINE)) editor.set_selection(i[0],i[1]-len(t)+len(editor.get_text()))
def indent(self): """indent selected lines by one tab""" import editor import re i = editor.get_line_selection() t = editor.get_text() # replace every occurance of newline with newline plus indent, except last newline INDENTSTR = ' ' editor.replace_text( i[0], i[1] - 1, INDENTSTR + re.sub(r'\n', r'\n' + INDENTSTR, t[i[0]:i[1] - 1])) editor.set_selection(i[0], i[1] - len(t) + len(editor.get_text()))
def sendToWCPt1(sender): ''' Sends the contents of the file in pythonista to overwrite the working copy version. ''' repo,path = info() sendText(repo,path,editor.get_text()) sender.superview.close()
def close_settings(self): sPl = plistlib.writePlistToString(self.plSettings) sN = self._sA[0:self._iS] + sPl[:-1] + self._sA[self._iF:-1] with open(self._f, 'w') as fS: fS.write(sN) if os.path.split(editor.get_path())[1] == self._f: editor.replace_text(0, len(editor.get_text()), sN)
def cut(self): import clipboard i = editor.get_selection() t = editor.get_text() clipboard.set(t[i[0]:i[1]]) editor.replace_text(i[0], i[1], '') editor.set_selection(i[0], i[0])
def get_line_count(): text = editor.get_text() if text is None: return None return len(text.splitlines())
def get_line_number(): text = editor.get_text() if text is None: return None return text.count('\n', 0, editor.get_selection()[0]) + 1
def commit_authenticated(user, commit_message): path = editor.get_path() tree_path, blob_name = os.path.split(path) repository = get_current_repository(user) blob = repository.create_git_blob(editor.get_text(), 'utf-8') parent_commit = get_current_head_commit(user) original_tree = repository.get_git_tree(parent_commit.tree.sha, True) tree_elements = [] for original_element in original_tree.tree: element_sha = original_element.sha if blob_name == original_element.path: element_sha = blob.sha element = InputGitTreeElement( original_element.path, original_element.mode, original_element.type, sha = element_sha) tree_elements.append(element) tree = repository.create_git_tree(tree_elements) # Need to update all ancestor trees as well commit = repository.create_git_commit(commit_message, tree, [parent_commit]) current_branch_head_ref = 'heads/' + get_current_branch_name() head_ref = repository.get_git_ref(current_branch_head_ref) head_ref.edit(commit.sha)
def main(): console.clear() class BrythonRunner(wkwebview.WKWebView): @on_main_thread def load_html(self, html): # Need to set a base directory to get # real js errors current_working_directory = os.path.dirname(editor.get_path()) root_dir = NSURL.fileURLWithPath_(current_working_directory) self.webview.loadHTMLString_baseURL_(html, root_dir) def _message(self, message): level, content = message['level'], message['content'] if level not in ['code', 'raw']: if content == 'using indexedDB for stdlib modules cache': #print('Brython started') return if level.upper() == 'LOG': print(content, end=('' if content.endswith('\n') else '\n')) return super()._message(message) python_code = editor.get_text() wv = BrythonRunner() html = html_start + python_code + html_end wv.load_html(html)
def main(): import editor selection_range = editor.get_selection() if not selection_range: # No file opened in the editor return text = editor.get_text() selected_lines_range = editor.get_line_selection() selected_lines_text = text[selected_lines_range[0]:selected_lines_range[1]] selected_lines = selected_lines_text.splitlines(True) last_line_deleted = False if len(selected_lines) > 1: # Ignore the last line selection if there's just cursor at the beginning of # this line and nothing is selected last_line = selected_lines[-1] if selected_lines_range[1] - len(last_line) == selection_range[1]: last_line_deleted = True del selected_lines[-1] selected_lines_range = (selected_lines_range[0], selected_lines_range[1] - len(last_line) - 1) replacement = ''.join(_toggle_lines(selected_lines)) if last_line_deleted: replacement = replacement[:-1] editor.replace_text(selected_lines_range[0], selected_lines_range[1], replacement) editor.set_selection(selected_lines_range[0], selected_lines_range[0] + len(replacement))
def textfield_did_change(self, textfield): global find_text full_text = editor.get_text() find_text = textfield.text global count count = full_text.count(find_text) select_text()
def main(): filename = editor.get_path() if not filename: return if not filename.endswith('.py'): return text = editor.get_text() if not text: return def scroll_to_node(node, shift_enter): source.scroll_to_line(node.line) v = PickerView() v.name = 'Outline' v.datasource = OutlineDataSource(text, os.path.basename(filename)) v.shift_enter_enabled = False v.help_label.text = ( '⇅ - select • Enter - scroll to location' '\n' 'Esc - close • Cmd . - close with Apple smart keyboard') v.textfield.placeholder = 'Start typing to filter nodes...' v.did_select_item_action = scroll_to_node v.present('sheet') v.wait_modal()
def main(): title = os.path.split(editor.get_path())[1] html = editor.get_text() webview = ui.WebView(title) webview.load_html(html) webview.present()
def analyze(): path = editor.get_path() if not path: return if not path.endswith('.py'): return editor.clear_annotations() text = editor.get_text() annotations = _pep8_annotations( text, ignore=settings.ANALYZER_PEP8_IGNORE, max_line_length=settings.ANALYZER_PEP8_MAX_LINE_LENGTH) annotations += _pyflakes_annotations(path, text) if not annotations: console.hud_alert('No Issues Found', 'iob:checkmark_32', settings.ANALYZER_HUD_DELAY) return None scroll = True by_line = sorted(annotations, key=lambda x: x.line) for l, a in groupby(by_line, lambda x: x.line): _annotate(l, a, scroll) scroll = False
def pull(): gist = get_gist_id(editor.get_path()) if gist is not None: fname = os.path.basename(editor.get_path()) newtxt = load(gist,fname) if newtxt is not None: editor.replace_text(0,len(editor.get_text()),newtxt)
def main(): if not get_config_value('general.jedi', False): log.warn( 'find_usages disabled, you can enable it by setting general.jedi to True' ) return path = editor.get_path() if path is None: return if not path.endswith('.py'): return tab.save() text = editor.get_text() if not text: return line = source.get_line_number() column = source.get_column_index() if line is None or column is None: return script = jedi.api.Script(text, line, column, path) definitions = [d for d in script.usages() if d.module_path and d.line] if not definitions: console.hud_alert('Definition not found', 'error') return _select_location(definitions)
def pull(): gist = get_gist_id(editor.get_path()) if gist is not None: fname = os.path.basename(editor.get_path()) newtxt = load(gist, fname) if newtxt is not None: editor.replace_text(0, len(editor.get_text()), newtxt)
def view_md(sender): mdviewwin = ui.View() webview = ui.WebView(frame=(0, 0, mdviewwin.width, mdviewwin.height), flex="WH") webview.load_html(markdown.markdown(editor.get_text())) mdviewwin.add_subview(webview) mdviewwin.present('fullscreen')
def get_configuration(): ''' Reads the docstring in the open file and finds AWS configuration information, starting with the magic string followed by JSON formatted key-value pairs. Remember that JSON uses double quotes for strings. ''' lambda_function_name = os.path.basename(current_dir) current_file = os.path.basename(editor.get_path()) if current_file.endswith('.py'): handler_first_part = current_file[:-3] file_text = editor.get_text() tree = ast.parse(file_text) conf = None for func in top_level_functions(tree.body): docstr = ast.get_docstring(func) if docstr: if conf_strings.awslambda in docstr: conf = { 'function_name': lambda_function_name, 'handler': handler_first_part + '.' + func.name } if conf_strings.noapi in docstr: conf['no-api'] = True print('** Will not update API endpoint') if conf_strings.html in docstr: conf['html'] = True return conf return None
def main(): text = editor.get_text() converted = markdown(text) html = TEMPLATE.replace('{{CONTENT}}', converted) webview = ui.WebView(name='Markdown Preview') webview.load_html(html) webview.present()
def cut(self): import clipboard i=editor.get_selection() t=editor.get_text() clipboard.set(t[i[0]:i[1]]) editor.replace_text(i[0],i[1], '') editor.set_selection(i[0],i[0])
def parse_ipynb(): try: ipynb = json.loads(editor.get_text()) except TypeError: console.hud_alert("Tap 'Edit as Text' first", 'error') return try: for cell in ipynb['cells']: if cell['cell_type'] == 'markdown': for line in cell['source']: print(line) print() # source: 마크다운 내용, 각 줄(str)의 리스트 elif cell['cell_type'] == 'code': print('[' + str(cell['execution_count']) + ']') for line in cell['source']: print('>>>', line.strip()) print() output = cell['outputs'] for out_cell in output: if out_cell['output_type'] == 'execute_result': print(out_cell['execution_count'], ) for l in out_cell['data']: if l == 'text/plain': for txt in out_cell['data'][l]: print(txt.strip()) elif l == 'text/html': for txt in out_cell['data'][l]: print(txt) print() elif out_cell['output_type'] == 'stream': for line in out_cell['text']: print(line.strip()) elif out_cell['output_type'] == 'error': print(out_cell['ename'] + ': ' + out_cell['evalue']) for line in out_cell['traceback']: print(line) else: print('+' * 50) print() # source: 코드 내용, 각 줄(str)의 리스트 # outputs: # name: 아웃풋 이름 - stdout, # output_type: - stream # text: - 아웃풋 내용, 각 줄의 리스트 # execution_count: 실행 순서(int 혹은 null) elif cell['cell_type'] == 'raw': print(cell['source']) print() # source: 코드 내용, 각 줄(str)의 리스트 else: print('+' * 50) print(cell) print('=' * 50) print() except KeyError: console.hud_alert('Not a proper notebook', 'error')
def uncomment(): """" uncomment selected lines""" import editor import re COMMENT = '#' i = editor.get_line_selection() t = editor.get_text() # replace every occurance of newline # with newline, except last newline # todo.. probably should verify every line has comment... # num lines= re.findall if all([x.startswith('#') for x in t[i[0]:i[1] - 1].split(r'\n')]): editor.replace_text( i[0], i[1] - 1, re.sub(r'^' + COMMENT, r'', t[i[0]:i[1] - 1], flags=re.MULTILINE)) editor.set_selection(i[0], i[1] - len(t) + len(editor.get_text()))
def execlines(self): """execute selected lines in console. """ import editor import textwrap a=editor.get_text()[editor.get_line_selection()[0]:editor.get_line_selection()[1]] exec(textwrap.dedent(a))
def __init__(self): ''' Initialize document generator from the Python file open in the editor. ''' file_text = editor.get_text() self.tree = ast.parse(file_text) self.lines = file_text.splitlines() self.section_lines = [] self.section_titles = {} self.used_section_titles = set()
def execlines(): """execute selected lines in console. """ import editor import textwrap a = editor.get_text()[editor.get_line_selection()[0]:editor. get_line_selection()[1]] exec(textwrap.dedent(a))
def pull(): gist = get_gist_id(editor.get_path()) if gist is None: console.alert('Error', 'There is no gist id set for this file') else: fname = os.path.basename(editor.get_path()) newtxt = load(gist, fname) if newtxt is not None: editor.replace_text(0, len(editor.get_text()), newtxt)
def pull(): gist = get_gist_id(editor.get_path()) if gist is None: console.alert('Error', 'There is no gist id set for this file') else: fname = os.path.basename(editor.get_path()) newtxt = load(gist,fname) if newtxt is not None: editor.replace_text(0,len(editor.get_text()),newtxt)
def main(): print(sys.argv) if len(sys.argv) <= 1: print("No changes detected.") quit() editor.open_file(sys.argv[1]) text_length = len(editor.get_text()) editor.replace_text(0, text_length, sys.argv[2])
def search_apple(sender): import editor, webbrowser, urllib3.request _sel = editor.get_selection() _txt = editor.get_text()[_sel[0]:_sel[1]] webbrowser.open('https://google.com/search?{}'.format( urllib3.request.urlencode({ 'q': 'reference ' + _txt, 'as_sitesearch': 'developer.apple.com', 'btnI': 'I' })))
def main(): foo = editor.get_text() gist_url = first_url_from_comments(foo) try: filename, content = download_gist(gist_url) editor.replace_text(0,len(editor.get_text()),content) #else: #editor.make_new_file(filename, content) except InvalidGistURLError: console.alert('No Gist URL', 'The clipboard doesn\'t seem to contain a valid Gist URL.', 'OK') except MultipleFilesInGistError: console.alert('Multiple Files', 'This Gist contains multiple ' + 'Python files, which isn\'t currently supported.') except NoFilesInGistError: console.alert('No Python Files', 'This Gist contains no Python files.') except GistDownloadError: console.alert('Error', 'The Gist could not be downloaded.')
def get_selected_text(): if appex.is_running_extension(): return False text = editor.get_text() s = editor.get_selection() if not s[0] == s[1]: selection = text[s[0]:s[1]] return selection else: return False
def main(): html = editor.get_text() if not html: print( 'No input text found. Use this script from the share sheet in an app like Notes.' ) return webview = ui.WebView(name='Html Preview') webview.load_html(html) webview.present()
def createTables(text=None): if text is None: text = editor.get_text() path = os.path.join(os.path.expanduser('~/Documents'), '.tmp.html') with open(path, 'wb') as f: f.write( TEMPLATE.format('\n'.join([ TEMPLATE_ROW.format(x) for x in text.split('\n') if x != '' ]))) webbrowser.open("file://{}".format(path))
def replace_it(sender): global once_or_all, find_text, replacement #global find_text #global replacement if once_or_all == 'once': # Replace selected instance selection = editor.get_selection() editor.replace_text(selection[0], selection[1], replacement) else: # Replace all instances full_text = editor.get_text() full_replacement = full_text.replace(find_text, replacement) editor.replace_text(0, len(full_text), full_replacement)
def finddocstring(self): ''' find the docstring at current cursor location ''' import StringIO from jedi import Script i=editor.get_selection() t=editor.get_text() (line,txt)=[(line,n) for (line,n) in enumerate(StringIO.StringIO(editor.get_text()[:i[1]]))][-1] script = Script(t, line+1, len(txt)) dfn = script.goto_definitions() if dfn: doc=dfn[0].doc import ui v=ui.TextView() v.width=200 v.height=250 v.text=doc v.present('popover')
def get_write_url(): params = OrderedDict() params["key"] = key params["x-success"] = "pythonista://" params["repo"] = "Pythonista" params["path"] = get_path() params["text"] = editor.get_text() params["askcommit"] = 1 return "working-copy://x-callback-url/write/?" + urlencode(params, quote_via=quote)
def finddocstring(self): ''' find the docstring at current cursor location ''' import StringIO from jedi import Script i=editor.get_selection() t=editor.get_text() (line,txt)=[(line,n) for (line,n) in enumerate(StringIO.StringIO(editor.get_text()[:i[1]]))][-1] script = Script(t, line+1, len(txt)) dfn = script.goto_definitions() if dfn: doc=dfn[0].doc import ui v=ui.TextView() v.width=100 v.height=50 v.text=doc editor._set_toolbar(v)
def pull(): gist_id = get_gist_id() if gist_id is None: console.alert('Error', 'There is no gist id set for this file') else: fname = os.path.basename(editor.get_path()) gist_data = requests.get(api_url + gist_id).json() try: newtext = gist_data['files'][fname]['content'] except: console.alert('Pull Error', 'There was a problem with the pull',gist_data) if newtext is not None: editor.replace_text(0,len(editor.get_text()),newtext)
def did_load(self): text = editor.get_text() selection = editor.get_line_selection() selected_text = text[selection[0]:selection[1]] is_comment = selected_text.strip().startswith('#') if is_comment: self.__bC.title = 'Uncomment' self.__tvP.text = selected_text.strip()[1:11] + '...' self.__tvP.text_color = 'black' else: self.__bC.title = 'Comment' self.__tvP.text = '#' + selected_text.strip()[0:10] + '...' self.__tvP.text_color = 'green'
def commit(): gist = get_gist_id(editor.get_path()) if gist is not None: token = keychain.get_password('gistcheck','gistcheck') if token is None: u, p = console.login_alert('GitHub Login') r = json.loads(auth(u, p)) print r token = r['token'] keychain.set_password('gistcheck','gistcheck',token) fname = os.path.basename(editor.get_path()) m = console.input_alert('Edit Description','Enter a new description:','') if m == '': m = None return edit(gist,{fname:editor.get_text()},token,m)
def close_settings(self): while self.__iR != 0: pass if self.settings_file[:7] == 'http://': pass else: sPl = plistlib.writePlistToString(self.settings_dict) sN = self.__sA[0:self.__iS] + sPl[:-1] + self.__sA[self.__iF:] with open(self.settings_file, 'w') as fS: fS.write(sN) if editor.get_path() == self.settings_file: tS = editor.get_selection() iD = 0 if tS[0] <= self.__iF else len(sN) - len(self.__sA) editor.replace_text(0, len(editor.get_text()), sN[:-1]) editor.set_selection(tS[0] + iD, tS[1] + iD) return True self.settings_dict = None
def __bCA(self, sender): # from: pythonista/docs/editor -------------- text = editor.get_text() selection = editor.get_line_selection() selected_text = text[selection[0]:selection[1]] is_comment = selected_text.strip().startswith('#') replacement = '' for line in selected_text.splitlines(): if is_comment: if line.strip().startswith('#'): replacement += line[line.find('#') + 1:] + '\n' else: replacement += line + '\n' else: replacement += '#' + line + '\n' editor.replace_text(selection[0], selection[1], replacement) editor.set_selection(selection[0], selection[0] + len(replacement) - 1) # end ----------------------------------------- self.close()
def main(): text = None label = 'Shared text' if appex.is_running_extension(): text = appex.get_text() if not text: try: import editor editor_file = editor.get_path() if editor_file: sel = console.alert('Editor or clipboard?', button1='Editor', button2='Clipboard') if sel == 1: editor_text = editor.get_text() sel_st, sel_end = editor.get_selection() label = os.path.basename(editor_file) if sel_end != sel_st: text = editor_text[sel_st:sel_end] elif editor_text: text = editor_text except ImportError: pass if not text: label = 'Clipboard' text = clipboard.get().strip() if text: converted = markdown(text) html = TEMPLATE.replace('{{CONTENT}}', converted) clip = console.alert('Replace clipboard?', button1='Yes', button2='No', hide_cancel_button=True) if clip ==1: clipboard.set(html) console.hud_alert('HTML copied to clipboard.') wv = MyWebView(name='Markdown - %s' % label) wv.load_html(html) wv.present('full_screen') else: console.hud_alert('No text found.') appex.finish()
def main(args): if args: name = args[0] else: sel = editor.get_selection() or "" seltxt = preformat(editor.get_text()[sel[0]:sel[1]]) if sel and sel[0] != sel[1] and is_valid_name(seltxt): name = seltxt else: name = console.input_alert("Find Module") try: loc = find_path(name) except ValueError: console.hud_alert(name + " is not a valid module name", "error") return if loc == "<built-in>": console.hud_alert(name + " is a built-in module", "error") elif loc == "<string>": console.hud_alert("Could not find module " + name, "error") else: editor.open_file(os.path.relpath(loc, DOCS))
def push_current_file_to_wc(self): self._push_file_to_wc(self.path, editor.get_text())
try: mk_file = open(file_name) except IOError: raise Exception('Could not open: {0}'.format(file_name)) lines = mk_file.readlines() #get the file name without extension #Works with a file name or a path file_name_rgx = re.compile("^(.*/)?(.*)\.(.*)$") m = file_name_rgx.match(file_name) if m: output_name = m.group(2) + '.html' elif ipad: #iPad Editorial setting settings = defaults['config'] lines = editor.get_text() else: raise Exception('Unkwon Platform - Run in Editorial for iPad or OS X') starts_with_hash = re.compile('^\s*#') slides = "" buf = "" for line in lines: if starts_with_hash.match(line) and buf: slides += slide_template.format(buf) buf = line elif not starts_with_hash.match(line) and buf: buf += line elif starts_with_hash.match(line) and not buf: buf = line
form_sections = (('About', fields[0], None), ('File info', fields[1], None)) data = dialogs.form_dialog('New File', sections=form_sections) assert data, 'No data entered.' #data['filename'] = os.path.basename(editor.get_path()) data['copyright_year'] = datetime.datetime.now().year fmt = """#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' {description} {documentation} ''' import sys __author__ = '{author_name}' __copyright__ = 'Copyright © {copyright_year}, {author_name} <{email}>' __credits__ = ['{author_name}'] __email__ = '{email}' __license__ = 'MIT' __maintainer__ = '{author_name}' __status__ = 'Pre-Alpha' __version__ = '0.0.1' """ editor.replace_text(0, len(editor.get_text()), fmt.format(**data))
def sendToWCPt2(sender): # Sends the contents of the file in pythonista to overwrite the working copy version. closePopup(sender) repo,path = info() sendText(repo,path,editor.get_text())
if not username: username = console.input_alert("Username", "Enter your GitHub Username", '', "Save") keychain.set_password('GitHub', 'username', username) tokn = keychain.get_password('GitHub', 'token') if not tokn: tokn = console.password_alert("API Token", "Enter your GitHub API Token", '', "Save") keychain.set_password('GitHub', 'token', tokn) repo = keychain.get_password('GitHub', 'repository') if not repo: repo = console.input_alert("Repository", "Enter your GitHub Repository name", '', "Save") keychain.set_password('GitHub', 'repository', repo) # Mangle the post ;) post_text = editor.get_text() post_sections = post_text.split('---') if len(post_sections) > 1: yaml_header = post_sections[1].splitlines() # Find the title in the YAML post_title = None date = None for line in yaml_header: if line[:6] == 'title:': post_title = line[6:].strip() elif line[:5] == 'date:': date = line[5:].strip()[:10] if post_title:
def insert_code(): return 'Write Something!\n\n<pre><code>\n\n%s\n</code></pre>' % editor.get_text()
def email_md(sender): subject = 'subject='+urllib.quote(editor.get_path().split('/')[-1]) body = 'body='+urllib.quote(markdown.markdown(editor.get_text())) webbrowser.open('mailto:?'+subject+'&'+body)
def view_md(sender): mdviewwin = ui.View() webview = ui.WebView(frame = (0, 0, mdviewwin.width, mdviewwin.height), flex="WH") webview.load_html(markdown.markdown(editor.get_text())) mdviewwin.add_subview(webview) mdviewwin.present('fullscreen')