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 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 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 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 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 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 out_to_editor(sender): request = post_multipart("c.docverter.com", "/convert", formats.items() + fields, files) buffer = StringIO.StringIO(request) output = buffer.getvalue() editor.replace_text(0, 0, output) buffer.close() view.close() workflow.stop()
def force_scroll(offset): line = line_from_offset(offset) if line > 10: scrollline = line - 10 else: scrollline = line scrolloffset = offset_from_line(line) editor.replace_text(scrolloffset, scrolloffset, '')
def out_to_editor(sender): request = post_multipart("c.docverter.com", "/convert", list(formats.items()) + fields, files) buffer = io.StringIO(request) output = buffer.getvalue() editor.replace_text(0, 0, output) buffer.close() view.close() workflow.stop()
def force_scroll(offset): line = line_from_offset(offset) if line > 10: scrollline = line -10 else: scrollline = line scrolloffset = offset_from_line(line) editor.replace_text(scrolloffset,scrolloffset,'')
def replace_with_cursor(replacement, cursor): if indent != '': lines = replacement.splitlines() replacement = ('\n'+indent).join(lines) cursor = replacement.find('|') replacement = replacement[:cursor]+replacement[cursor+1:] editor.replace_text(place[0], place[1], replacement) editor.replace_text(place[0]+cursor, place[0]+cursor, '')
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 comment_action(sender): """" comment out selected lines""" 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 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 setsel(): sel=new_tab['selection'] while editor.get_selection()[0] < sel[0]: import time editor.replace_text(sel[0],sel[0],'') editor.replace_text(sel[0]+400,sel[0]+400,'') time.sleep(0.25) editor.set_selection(*sel)
def setsel(): sel = new_tab['selection'] while editor.get_selection()[0] < sel[0]: import time editor.replace_text(sel[0], sel[0], '') editor.replace_text(sel[0] + 400, sel[0] + 400, '') time.sleep(0.25) editor.set_selection(*sel)
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 uncomment_action(self): """" uncomment selected lines""" 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 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 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 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 refresh_editor(): #reload current file in editor # TODO: only reload if the file was recently updated... try: sel = editor.get_selection() editor.open_file(editor.get_path()) import time time.sleep(0.5) #let the file load editor.replace_text(sel[0], sel[0], '') #force scroll editor.set_selection(sel[0], sel[1]) except: print('Could not refresh editor. continuing anyway')
def refresh_editor(): #reload current file in editor # TODO: only reload if the file was recently updated... try: sel=editor.get_selection() editor.open_file(editor.get_path()) import time time.sleep(0.5) #let the file load editor.replace_text(sel[0],sel[0],'') #force scroll editor.set_selection(sel[0],sel[1]) except: print 'Could not refresh editor. continuing anyway'
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 indent(): """indent selected lines by one tab""" import editor import re INDENTSTR = '\t' #two spaces i = editor.get_line_selection() t = editor.get_text() # replace every occurance of newline with ewline 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 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 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 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 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 _editor_text(): text = editor.get_text() range_end = len(text) if _remove_whitespaces(): text = _remove_trailing_whitespaces(text) text = _remove_trailing_lines(text) editor.replace_text(0, range_end, text) tab.save() # Pythonista is adding '\n' automatically, so, if we removed them # all we have to simulate Pythonista behavior by adding '\n' # for pyflakes & pep8 analysis return text + '\n' tab.save() return text
def toggle_comments(): 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() 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_length = len(selected_lines[-1]) if selection_range[1] == selected_lines_range[1] - last_line_length: del selected_lines[-1] selected_lines_range = (selected_lines_range[0], selected_lines_range[1] - last_line_length - 1) is_commented = selected_lines_text.strip().startswith('#') replacement = '' for line in selected_lines: if is_commented: if line.strip().startswith('#'): replacement += line[line.find('#') + 1:] + '\n' else: replacement += line + '\n' else: replacement += '#' + line + '\n' # Remove trailing \n to avoid empty new lines 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 __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(): 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 apply_change_set(change_set, path=None, initial_selection=None): # # Why not project.do(change_set)? # # - iCloud, Files, ... - there're special functions to update files, not a simple file system # - we have to be sure just one file (= opened) is updated only, because of Pythonista reloading, ... # for change in change_set.changes: if path and not change.resource.real_path == path: # Make sure we modify opened file only continue if path and not path == editor.get_path(): # Make sure that user didn't switch tab, close tab, ... continue end = len(editor.get_text()) - 1 editor.replace_text(0, end, change.new_contents) if initial_selection: editor.set_selection(*initial_selection, scroll=True)
def _replace_file_content(path): futurized_path = '{}{}'.format(path, _SUFFIX) if not os.path.exists(futurized_path): # This function is not called unless result is 0, thus if file doesn't # exist, we can assume that there's no need to change anything -> success return True line_number = source.get_line_number() content = editor.get_text() if not line_number or content is None: os.remove(futurized_path) return False new_content = open(futurized_path, 'r').read() editor.replace_text(0, len(content) - 1, new_content) source.scroll_to_line(line_number) os.remove(futurized_path) return True
# Add the script to your action menu, # when you are in another script, select the text that you want to indent. # Then start the indentation-tool and you'll get a pop up where you will # write how many indentations you want to add. # You can also remove indentations from lines by writing negative integers. import editor, console script = editor.get_text() selection = editor.get_selection() selected_text = script[selection[0]:selection[1]].splitlines() indentation = int(console.input_alert('Indent')) replacement = [] for line in selected_text: if indentation > 0: replacement.append(('\t'*indentation)+line+('\n' if line != selected_text[-1] else '')) elif indentation == 0: replacement.append(line+('\n' if line != selected_text[-1] else '')) elif indentation < 0: if len(line) == 0: replacement.append('\n') elif line[0] == '\t': indent = min(abs(indentation), line.count('\t')) replacement.append(line.replace('\t', '', indent)+('\n' if line != selected_text[-1] else '')) else: replacement.append(line+('\n' if line != selected_text[-1] else '')) editor.replace_text(selection[0], selection[1], ''.join(replacement))
# https://gist.github.com/jefflovejapan/5076080 # Comment/Uncomment selected lines import 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)
def paste(self): if self.val : sel = editor.get_selection() editor.replace_text(sel[0], sel[1], self.val)
def instxt(pos,txt): # insert text editor.replace_text(pos,pos,txt)
import editor full_text = editor.get_text() cursor = editor.get_selection()[1] while True: try: if full_text[cursor - 3] + full_text[cursor - 2] + full_text[cursor - 1] == 'def': editor.replace_text(cursor, cursor, ' func_name():') editor.set_selection(cursor + 1, cursor + 10) if full_text[cursor - 3] + full_text[cursor - 2] + full_text[cursor - 1] == 'ifc': editor.replace_text(cursor, cursor, ' condition:') editor.set_selection(cursor + 1, cursor + 10) if full_text[cursor - 3] + full_text[cursor - 2] + full_text[cursor - 1] == 'wlt': editor.replace_text(cursor - 2, cursor, 'hile i < num:') editor.set_selection(cursor + 7, cursor + 10) if full_text[cursor - 3] + full_text[cursor - 2] + full_text[cursor - 1] == 'fea': editor.replace_text(cursor - 2, cursor, 'or entry in array:') editor.set_selection(cursor + 10, cursor + 15) break except: pass
# coding: utf-8 # Put this script into the editor action (wrench) menu. # Whenever you want to import an Objective-C class, # you jutst need to type the classname, select it and invoke this script via the action menu. # This script will check if a classname with the name you selected exists # and add ` = ObjcClass(_classname_)` to the end of the line import editor, console, sys from objc_util import ObjCClass selection = editor.get_selection() line = editor.get_line_selection() text = editor.get_text() classname = text[int(selection[0]):int(selection[1])] try: ObjCClass(classname) editor.set_selection(selection[1]) editor.replace_text(selection[1], selection[1], ' = ObjCClass(\'{}\')'.format(classname)) except: console.hud_alert(sys.exc_info()[1].message, 'error')
def __bRA(self, sender): if len(editor.get_text()) != 0: editor.replace_text( 0, len(editor.get_text()), editor.get_text().replace(self.__tfF.text, self.__tfR.text)) self.close()
# replace ALL tab characters with four spaces import editor, sys theText = editor.get_text() theCount = theText.count('\t') if not theText.count('\t'): print('no tabs found.') sys.exit() theLength = len(theText) theText = theText.splitlines() #theSelection = editor.get_selection() for i in range(len(theText)): theText[i] = theText[i].replace('\t', ' ') editor.replace_text(0, theLength, '\n'.join(theText)) #editor.set_selection(theSelection[0])
import editor text = editor.get_text() selection = editor.get_line_selection() selected_lines = text[selection[0]:selection[1]] if len(selected_lines) == len(text) - 1: editor.replace_text(selection[0], selection[1]+1, '\n') # when complete text is deleted else: editor.replace_text(selection[0], selection[1]+1, '')
------------ - Add this script to Pythonista as "Find and Replace". - Tap Action Menu, tap '+', then go find this script. Usage ----- - Tap the Action Menu - Tap Find and Replace - Enter the string to find - Enter the replacement string - Enjoy! Modification Log ---------------- 20131207 [email protected] Updated installation instructions ''' import console import editor all_text = editor.get_text() find = console.input_alert('Find', 'Please enter text to find.', '', 'Find') replace = console.input_alert('Replace', 'Please enter replacement text.', find, 'Replace') new_text = all_text.replace(find, replace) editor.replace_text(0, len(all_text), new_text)
def insert_action(sender): text = sender.superview['textview1'].text start, end = editor.get_selection() editor.replace_text(start, end, text) if not platform.machine().startswith('iPad'): view.close()
outfile.close() def file_get_contents(filename): with open(filename,'rb') as f: return f.read() def file_set_contents(filename, contents): with open(filename,'wb') as f: f.write(contents) #input = workflow.get_input() #input = file_get_contents(editor.get_path()) input = editor.get_text() root, documentfilename = editor.to_relative_path(editor.get_path()) # prompt user for password password = console.password_alert("Document Password Required", "Enter your password",'',"OK") inputfile = tempfile.NamedTemporaryFile(delete=False) outputfile = tempfile.NamedTemporaryFile(delete=False) file_set_contents(inputfile.name, input) encryptFile(inputfile, password, outputfile) result = file_get_contents(outputfile.name) os.remove(inputfile.name) os.remove(outputfile.name) end = len(input) result64 = base64.b64encode(result) editor.replace_text(0,end,result64) console.hud_alert('Encryption Completed', 'info')
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 cut_action(sender): 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])
import editor text = editor.get_text() replacement = '' for line in text.splitlines(): replacement += line.rstrip() + '\n' replacement = replacement[:-1] # don't use last linefeed editor.replace_text(0, len(text), replacement)
# https://gist.github.com/GuyCarver/4143014 # unindent selection import editor text = editor.get_text() selection = editor.get_line_selection() selected_text = text[selection[0]:selection[1]] replacement = '' for line in selected_text.splitlines(): replacement += line[line.find('\t') + 1:] + '\n' editor.replace_text(selection[0], selection[1], replacement) editor.set_selection(selection[0], selection[0] + len(replacement) - 1)
d = '{}{} {}'.format(chars, fields[i]['title'], data['{}'.format(fields[i]['key'])]) data['{}'.format(fields[i]['key'])] = wrap(d, wrap_len, i) # Create new or recreate edited header comments comments = [] for i in range(len(fields)): comments.append('{' + fields[i]['key'] + '}') comments = '\n'.join(comments) if field_titles: fmt = """'''\n{}'''""".format(comments) else: fmt = """'''\n{}'''\n""".format(comments) # Insert field values from form into comments comments = fmt.format(**data) # Debug #print comments #sys.exit() # Add new or edited header comments to any existing text updated_text = '{}{}{}'.format(beginning_text, comments, remaining_text) # Erase all of the old text editor.replace_text(0, len(old_text), '') # Replace the old with the updated text editor.replace_text(0, len(updated_text), updated_text)
def paste(self): import clipboard i=editor.get_selection() t=editor.get_text() editor.replace_text(i[0],i[1], clipboard.get()) editor.set_selection(i[0],i[1]-len(t)+len(editor.get_text()))