Python editor.get_path() Examples

The following are 23 code examples of editor.get_path(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module editor , or try the search function .
Example #1
Source File: Tabs.py    From pythonista-scripts with MIT License 6 votes vote down vote up
def did_load(self):
        sv=self['scrollview1']
        self.sv=sv
        self.add_button = sv['add_button']
        self.add_button.action=self.add_file
        self.remove = sv['remove']
        self.edit = sv['edit']
        self.edit.action=edit_menu
        
        d=shelve.open(os.path.expanduser('~/Documents/.tabs'),writeback=True )
    
        current_path = editor.get_path()
    
        for tab in d.itervalues():
            self.add_new_button(tab['name'])
        self.d=d
        self.present('sidebar')
        self.check_tab()
        type(self)._lastinstance=self 
Example #2
Source File: refactoring.py    From blackmamba with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: futurize.py    From blackmamba with MIT License 6 votes vote down vote up
def main(mock):
    import libfuturize.main

    path = editor.get_path()
    if not path or not path.endswith('.py'):
        console.hud_alert('Not a Python file', 'error')
        return

    tab.save()
    args = ['-1', '-n', '-w', '--all-imports', '--add-suffix', _SUFFIX, path]

    result = libfuturize.main.main(args)
    if result == 0 and _replace_file_content(path):
        console.hud_alert('Futurized')
    else:
        console.hud_alert('Failed to futurize', 'error') 
Example #4
Source File: md2html.py    From pythonista-scripts with MIT License 5 votes vote down vote up
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() 
Example #5
Source File: rename.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def main(args):
    try:
        # Source and destination are passed via runtime args
        src, dest = args
    except (TypeError, ValueError):
        # Get source and destination from user
        curfile = os.path.relpath(editor.get_path() or "", DOCUMENTS)
        
        shortsrc = console.input_alert(
            "Source Name", # title
            "Path is relative to Script Library root", # message
            curfile, # input
        )
        src = os.path.join(DOCUMENTS, shortsrc)
        
        if not os.path.exists(src):
            console.hud_alert("Source file does not exist", "error")
            sys.exit(1)
        
        dest = os.path.join(DOCUMENTS, console.input_alert(
            "Destination Name", # title
            "Path is relative to Script Library root", # message
            shortsrc, # input
        ))
    else:
        # Process source and destination from runtime args
        src, dest = os.path.join(DOCUMENTS, src), os.path.join(DOCUMENTS, dest)
        
        if not os.path.exists(src):
            console.hud_alert("Source file does not exist", "error")
            sys.exit(1)
    
    if os.path.exists(dest):
        console.hud_alert("Destination file already exists", "error")
        sys.exit(1)
    
    os.rename(src, dest)
    
    sys.exit(0) 
Example #6
Source File: gitui.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def checkout(self,sender):
        repo =self._get_repo()
        cwd=os.path.abspath('.')
        os.chdir(r._get_repo().path)
        #repo.clean_working()
        repo.switch_branch(self.view['branch'].text)
        self.refresh()
        os.chdir(cwd)
        editor.open_file(editor.get_path())
        console.hud_alert('checked out') 
Example #7
Source File: EmbedPyui.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def main():
	filename = editor.get_path()
	if not filename:
		dialogs.hud_alert('No file selected', 'error')
		return
	pyui_filename = os.path.splitext(filename)[0] + '.pyui'
	if not os.path.exists(pyui_filename):
		folder = os.path.split(filename)[0]
		files = os.listdir(folder)
		files = [f for f in files if f.endswith('.pyui')]
		if not files:
			dialogs.hud_alert('No pyui files found', 'error')
			return
		selected_pyui = dialogs.list_dialog('Select pyui file', files)
		if not selected_pyui:
			return
		pyui_filename = os.path.join(folder, selected_pyui)
	with open(pyui_filename, 'rb') as f:
		pyui = f.read()
	compressed = base64.b64encode(bz2.compress(pyui)).decode('utf-8')
	wrapped = '\n'.join(textwrap.wrap(compressed, 70))
	code = """\
data = '''\\\n%s
'''
import ui
import bz2
from base64 import b64decode
pyui = bz2.decompress(b64decode(data))
v = ui.load_view_str(pyui.decode('utf-8'))
""" % (wrapped,)
	clipboard.set(code)
	dialogs.hud_alert('Code copied', 'success') 
Example #8
Source File: Tabs.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def add_file(self,sender):
        d=self.d
        current_path = str(editor.get_path())
        name = os.path.split(current_path)[1]
        for item in self.d.itervalues():
            if current_path==item['path']:
                console.hud_alert('There is already a tab for this file', duration = 1)
                return None
        if self.d.has_key(name): #has name, but diff path, still create the tab, but append !#
            suffix_list=[(k+'!').split('!')[1] or '0' for k in self.d.keys() if k.startswith(name) ]
            new_suffix='!'+max([int(m) for m in suffix_list])+1
            name=name+new_suffix
        d[name]={'name':name,'path':current_path,'selection':editor.get_selection()}
        self.add_new_button(name, new = True) 
Example #9
Source File: Tabs.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def check_tab(self):
        open_path = editor.get_path()
        for tab in self.sv.subviews:
            try:
                if self.d[tab.name]['path'] != open_path:
                    tab.background_color = 'white'
                else:
                    tab.background_color = 'orange'
            except KeyError:
                pass 
Example #10
Source File: wannabetabs.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def current_path():
    # path to file currently open in editor
    return "/private" + editor.get_path() 
Example #11
Source File: rename.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def main(args):
    try:
        # Source and destination are passed via runtime args
        src, dest = args
    except (TypeError, ValueError):
        # Get source and destination from user
        curfile = os.path.relpath(editor.get_path() or "", DOCUMENTS)
        
        shortsrc = console.input_alert(
            "Source Name", # title
            "Path is relative to Script Library root", # message
            curfile, # input
        )
        src = os.path.join(DOCUMENTS, shortsrc)
        
        if not os.path.exists(src):
            console.hud_alert("Source file does not exist", "error")
            sys.exit(1)
        
        dest = os.path.join(DOCUMENTS, console.input_alert(
            "Destination Name", # title
            "Path is relative to Script Library root", # message
            shortsrc, # input
        ))
    else:
        # Process source and destination from runtime args
        src, dest = os.path.join(DOCUMENTS, src), os.path.join(DOCUMENTS, dest)
        
        if not os.path.exists(src):
            console.hud_alert("Source file does not exist", "error")
            sys.exit(1)
    
    if os.path.exists(dest):
        console.hud_alert("Destination file already exists", "error")
        sys.exit(1)
    
    os.rename(src, dest)
    
    sys.exit(0) 
Example #12
Source File: apphack.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def run_script(sender):
		'''run a script without clearing glbals'''
		import editor
		editor.reload_files()
		execfile(editor.get_path(),globals())

	#create_toolbar_button(run_script,'iow:play_32',0,'execfile')
	
	#remove_toolbar_button(0) 
Example #13
Source File: outline_quickly.py    From blackmamba with MIT License 5 votes vote down vote up
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() 
Example #14
Source File: find_usages.py    From blackmamba with MIT License 5 votes vote down vote up
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) 
Example #15
Source File: show_documentation.py    From blackmamba with MIT License 5 votes vote down vote up
def main():
    if not get_config_value('general.jedi', False):
        log.warn('show_documentation 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.goto_definitions()
        if d.module_path and d.line and d.docstring()
    ]

    if not definitions:
        console.hud_alert('Documentation not found', 'error')
        return

    if len(definitions) == 1:
        _show_documentation(definitions[0])
    else:
        _select_location(definitions) 
Example #16
Source File: analyze.py    From blackmamba with MIT License 5 votes vote down vote up
def main():
    path = editor.get_path()

    if not path:
        return

    if not path.endswith('.py'):
        return

    editor.clear_annotations()

    flake8_options = get_config_value('analyzer.flake8', None)

    selection = editor.get_selection()
    text = _editor_text()

    if flake8_options:
        annotations = _flake8_annotations(
            os.path.abspath(path),
            flake8_options
        )
    else:
        annotations = _pep8_annotations(
            text,
            ignore=_ignore_codes(),
            max_line_length=_max_line_length()
        )

        annotations += _pyflakes_annotations(path, text)

    if not annotations:
        if selection:
            editor.set_selection(selection[0], scroll=True)
        console.hud_alert('No Issues Found', 'iob:checkmark_32', _hud_alert_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 
Example #17
Source File: run_unit_tests.py    From blackmamba with MIT License 5 votes vote down vote up
def main():
    path = editor.get_path()

    if not path:
        return

    if not path.endswith('.py'):
        return

    save(all=True)
    _run_unit_tests(path) 
Example #18
Source File: jump_to_definition.py    From blackmamba with MIT License 5 votes vote down vote up
def main():
    if not get_config_value('general.jedi', False):
        log.warn('jump_to_definition 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.goto_definitions()
        if d.module_path and d.line
    ]

    if not definitions:
        console.hud_alert('Definition not found', 'error')
        return

    if len(definitions) == 1:
        tab.open_file(definitions[0].module_path, line=definitions[0].line)
    else:
        _select_location(definitions) 
Example #19
Source File: wannabetabs.py    From pythonista-scripts with MIT License 5 votes vote down vote up
def current_path():
    # path to file currently open in editor
    return "/private" + editor.get_path() 
Example #20
Source File: expand_star_imports.py    From blackmamba with MIT License 4 votes vote down vote up
def main():
    from rope.base.project import Project
    from rope.base import libutils
    from rope.refactor.importutils import ImportOrganizer
    from rope.base.exceptions import RopeError

    path = editor.get_path()
    selection = editor.get_selection()

    if not path or not selection:
        console.hud_alert('Not a Python file', 'error')
        return

    tab.save()

    project = None
    try:
        project = Project(os.path.dirname(path), ropefolder=None)
        resource = libutils.path_to_resource(project, path)
        if not libutils.is_python_file(project, resource):
            console.hud_alert('Not a Python file', 'error')
            return

        organizer = ImportOrganizer(project)
        change_set = organizer.expand_star_imports(resource)
        if not change_set:
            console.hud_alert('No changes required')
            return

        if refactoring.ask_if_apply_change_set(change_set):
            refactoring.apply_change_set(change_set, path, selection)
            console.hud_alert('Imports expanded')

    except RopeError as e:
        console.hud_alert(str(e), 'error')

    except KeyboardInterrupt:
        pass

    finally:
        if project:
            project.close() 
Example #21
Source File: organize_imports.py    From blackmamba with MIT License 4 votes vote down vote up
def main():
    from rope.base.project import Project
    from rope.base import libutils
    from rope.refactor.importutils import ImportOrganizer
    from rope.base.exceptions import RopeError

    path = editor.get_path()
    selection = editor.get_selection()

    if not path or not selection:
        console.hud_alert('Not a Python file', 'error')
        return

    tab.save()

    project = None
    try:
        project = Project(os.path.dirname(path), ropefolder=None)
        resource = libutils.path_to_resource(project, path)
        if not libutils.is_python_file(project, resource):
            console.hud_alert('Not a Python file', 'error')
            return

        organizer = ImportOrganizer(project)
        change_set = organizer.organize_imports(resource)

        if not change_set:
            console.hud_alert('No changes required')
            return

        if refactoring.ask_if_apply_change_set(change_set):
            refactoring.apply_change_set(change_set, path, selection)
            console.hud_alert('Imports organized')

    except RopeError as e:
        console.hud_alert(str(e), 'error')

    except KeyboardInterrupt:
        pass

    finally:
        if project:
            project.close() 
Example #22
Source File: drag_and_drop.py    From blackmamba with MIT License 4 votes vote down vote up
def __init__(self):
        global _datasource

        self.name = 'Drag & Drop'

        self.width = min(ui.get_window_size()[0] * 0.8, 700)
        self.height = ui.get_window_size()[1] * 0.8

        path = editor.get_path()
        if path:
            expanded_folder = os.path.dirname(path)
            files = tab.get_paths()
        else:
            expanded_folder = None
            files = None

        root_node = FileNode(os.path.expanduser('~/Documents'), ignore=ignore)
        _datasource = FolderPickerDataSource(root_node, expanded_folder, files)

        tv = ui.TableView(frame=self.bounds, flex='WH')
        tv.delegate = _datasource
        tv.data_source = _datasource
        tv.allows_multiple_selection = False
        tv.allows_selection = True
        tv.allows_multiple_selection_during_editing = False
        tv.allows_selection_during_editing = False
        tv.separator_color = 'clear'
        self.add_subview(tv)

        methods = [tableView_itemsForBeginningDragSession_atIndexPath_]
        protocols = ['UITableViewDragDelegate']
        DragDelegate = create_objc_class('DragDelegate', methods=methods, protocols=protocols)
        self._drag_delegate = DragDelegate.alloc().init()

        methods = [
            tableView_canHandleDropSession_,
            tableView_dropSessionDidUpdate_withDestinationIndexPath_,
            tableView_performDropWithCoordinator_
        ]
        protocols = ['UITableViewDropDelegate']
        DropDelegate = create_objc_class('DropDelegate', methods=methods, protocols=protocols)
        self._drop_delegate = DropDelegate.alloc().init()

        tv_objc = ObjCInstance(tv)
        tv_objc.setDragDelegate_(self._drag_delegate)
        tv_objc.setDropDelegate_(self._drop_delegate)

        def handle_escape():
            self.close()

        self._handlers = [
            register_key_event_handler(UIEventKeyCode.ESCAPE, handle_escape),
            register_key_event_handler(UIEventKeyCode.DOT, handle_escape,
                                       modifier=UIKeyModifier.COMMAND)
        ] 
Example #23
Source File: edit.py    From stash with MIT License 4 votes vote down vote up
def open_temp(file='', new_tab=True):
    try:
        file_to_edit = file
        temp = tempfile.NamedTemporaryFile(dir=os.path.expanduser('~/Documents'), suffix='.py')
        cur_path = editor.get_path()
        if file_to_edit != '':
            try:
                to_edit = open(file_to_edit, 'r')
            except:
                to_edit = open(file_to_edit, 'w+')

            temp.write(to_edit.read())
            temp.flush()
            to_edit.close()

        print('***When you are finished editing the file, you must come back to console to confim changes***')
        editor.open_file(temp.name, new_tab)
        time.sleep(1.5)
        console.hide_output()
        input = raw_input('Save Changes? Y,N: ')

        if input == 'Y' or input == 'y':
            while True:
                try:
                    save_as = raw_input('Save file as [Enter to confirm]: %s' % file_to_edit) or file_to_edit
                except:
                    save_as = file_to_edit
                if save_as:
                    break

            if not new_tab:
                editor.open_file(cur_path)  # restore previous script in editor
            with open(save_as, 'w') as f:
                with open(temp.name, 'r') as tmp:
                    f.write(tmp.read())

            print('File Saved.')
        elif input == 'N' or input == 'n':
            if not new_tab:
                editor.open_file(cur_path)  # restore previous script in editor

    except Exception as e:
        print(e)

    finally:
        temp.close()