Edit a file in a text editor
769622
def do_edit(self, args: argparse.Namespace) -> None:
        """"""
        if not self.editor:
            raise EnvironmentError("Please use 'set editor' to specify your text editing program of choice.")

        command = utils.quote_string_if_needed(os.path.expanduser(self.editor))
        if args.file_path:
            command += " " + utils.quote_string_if_needed(os.path.expanduser(args.file_path))

        self.do_shell(command)
41157
def do_edit(self, arg):
        ""
        if arg == '':
            filename, lineno = self._get_current_position()
        else:
            filename, lineno, _ = self._get_position_of_arg(arg)
            if filename is None:
                return
        # this case handles code generated with py.code.Source()
        # filename is something like '<0-codegen foo.py:18>'
        match = re.match(r'.*<\d+-codegen (.*):(\d+)>', filename)
        if match:
            filename = match.group(1)
            lineno = int(match.group(2))

        try:
            self._open_editor(self._get_editor_cmd(filename, lineno))
        except Exception as exc:
            self.error(exc)
927083
def update_file(file)
      log "file: #{file}"
      text = File.read(file)
      text = yield text
      File.open(file, 'w') { |f| f.write(text) }
    end
336875
function setupFileElement( editor, fileInput, filebrowser ) {
		var params = filebrowser.params || {};
		params.CKEditor = editor.name;
		params.CKEditorFuncNum = editor._.filebrowserFn;
		if ( !params.langCode )
			params.langCode = editor.langCode;

		fileInput.action = addQueryString( filebrowser.url, params );
		fileInput.filebrowser = filebrowser;
	}
1102673
def edit_file(self, file_name):
        
        with io.open(file_name, "r", encoding=self.encoding) as from_file:
            try:
                from_lines = from_file.readlines()
            except UnicodeDecodeError as err:
                log.error("encoding error (see --encoding): %s", err)
                raise

        if self._executables:
            nb_execs = len(self._executables)
            if nb_execs > 1:
                log.warn("found %d executables. Will use first one", nb_execs)
            exec_list = self._executables[0].split()
            exec_list.append(file_name)
            try:
                log.info("running %s...", " ".join(exec_list))
                output = subprocess.check_output(exec_list,
                                                 universal_newlines=True)
            except Exception as err:
                log.error("failed to execute %s: %s", " ".join(exec_list), err)
                raise  # Let the exception be handled at a higher level.
            to_lines = output.split(unicode("\n"))
        else:
            to_lines = from_lines

        # unified_diff wants structure of known length. Convert to a list.
        to_lines = list(self.edit_content(to_lines, file_name))
        diffs = difflib.unified_diff(from_lines, to_lines,
                                     fromfile=file_name, tofile='<new>')
        if not self.dry_run:
            bak_file_name = file_name + ".bak"
            if os.path.exists(bak_file_name):
                msg = "{} already exists".format(bak_file_name)
                if sys.version_info < (3, 3):
                    raise OSError(msg)
                else:
                    # noinspection PyCompatibility
                    # pylint: disable=undefined-variable
                    raise FileExistsError(msg)
            try:
                os.rename(file_name, bak_file_name)
                with io.open(file_name, 'w', encoding=self.encoding, newline=self.newline) as new:
                    new.writelines(to_lines)
                # Keeps mode of original file.
                shutil.copymode(bak_file_name, file_name)
            except Exception as err:
                log.error("failed to write output to %s: %s", file_name, err)
                # Try to recover...
                try:
                    os.rename(bak_file_name, file_name)
                except OSError as err:
                    log.error("failed to restore %s from %s: %s",
                              file_name, bak_file_name, err)
                raise
            try:
                os.unlink(bak_file_name)
            except OSError as err:
                log.warning("failed to remove backup %s: %s",
                            bak_file_name, err)
        return list(diffs)
1265436
function editorUpdate() {
    if (editor.binding) {
      if ('hold' === generator.clientUpdateFragmentText(editor.binding, editor.$edit.val())) {
        editor.holding = true;
      }
    }
  }
935923
def _open_file_in_editor(self, filename):
        
        # If the 'VISUAL' or 'EDITOR' environment variable has been set, use that.
        # Otherwise, fall back to the first available editor that we can find.
        visual = os.environ.get('VISUAL')
        editor = os.environ.get('EDITOR')

        editors = [
            visual,
            editor,

            # Order of preference.
            '/usr/bin/editor',
            '/usr/bin/nano',
            '/usr/bin/pico',
            '/usr/bin/vi',
            '/usr/bin/emacs',
        ]

        for e in editors:
            if e:
                try:
                    # Use 'shlex.split()', because $VISUAL can contain spaces
                    # and quotes.
                    returncode = subprocess.call(shlex.split(e) + [filename])
                    return returncode == 0

                except OSError:
                    # Executable does not exist, try the next one.
                    pass

        return False
8239
def text_changed(self):
        """"""
        # Save text as bytes, if it was initially bytes
        if self.is_binary:
            self.text = to_binary_string(self.edit.toPlainText(), 'utf8')
        else:
            self.text = to_text_string(self.edit.toPlainText())
        if self.btn_save_and_close:
            self.btn_save_and_close.setEnabled(True)
            self.btn_save_and_close.setAutoDefault(True)
            self.btn_save_and_close.setDefault(True)
318053
def do_edit(self, line):
        """"""
        self._split_args(line, 0, 0)
        self._command_processor.get_operation_queue().edit()
        self._print_info_if_verbose("The write operation queue was successfully edited")
562591
def execute_edit(args, root_dir=None):
    
    # Get editor
    EDITOR = os.environ.get('EDITOR', 'vim')
    # Get command from server
    key = args['key']
    status = command_factory('status')({}, root_dir=root_dir)

    # Check if queue is not empty, the entry exists and is queued or stashed
    if not isinstance(status['data'], str) and key in status['data']:
        if status['data'][key]['status'] in ['queued', 'stashed']:
            command = status['data'][key]['command']
        else:
            print("Entry is not 'queued' or 'stashed'")
            sys.exit(1)
    else:
        print('No entry with this key')
        sys.exit(1)

    with tempfile.NamedTemporaryFile(suffix=".tmp") as tf:
        tf.write(command.encode('utf-8'))
        tf.flush()
        call([EDITOR, tf.name])

        # do the parsing with `tf` using regular File operations.
        # for instance:
        tf.seek(0)
        edited_command = tf.read().decode('utf-8')

    print_command_factory('edit')({
        'key': key,
        'command': edited_command,
    }, root_dir=root_dir)
873589
def edit(ctx, file_to_edit, previous_file):
    
    timesheet_collection = None
    autofill = not bool(file_to_edit) and previous_file == 0
    if not file_to_edit:
        file_to_edit = ctx.obj['settings'].get_entries_file_path(False)

    # If the file was not specified and if it's the current file, autofill it
    if autofill:
        try:
            timesheet_collection = get_timesheet_collection_for_context(
                ctx, file_to_edit
            )
        except ParseError:
            pass
        else:
            t = timesheet_collection.latest()

            if ctx.obj['settings']['auto_add'] != Settings.AUTO_ADD_OPTIONS['NO']:
                auto_fill_days = ctx.obj['settings']['auto_fill_days']
                if auto_fill_days:
                    t.prefill(auto_fill_days, limit=None)

                t.save()

    # Get the path to the file we should open in the editor
    timesheet_files = list(reversed(TimesheetCollection.get_files(file_to_edit, previous_file)))
    if previous_file >= len(timesheet_files):
        ctx.fail("Couldn't find the requested previous file for `%s`." % file_to_edit)

    expanded_file_to_edit = list(timesheet_files)[previous_file]

    editor = ctx.obj['settings']['editor']
    edit_kwargs = {
        'filename': expanded_file_to_edit,
        'extension': '.tks'
    }
    if editor:
        edit_kwargs['editor'] = editor

    click.edit(**edit_kwargs)

    try:
        # Show the status only for the given file if it was specified with the
        # --file option, or for the files specified in the settings otherwise
        timesheet_collection = get_timesheet_collection_for_context(
            ctx, file_to_edit
        )
    except ParseError as e:
        ctx.obj['view'].err(e)
    else:
        ctx.obj['view'].show_status(
            timesheet_collection.entries.filter(regroup=True, pushed=False)
        )
884508
private String openTextEditor() throws IOException, InterruptedException {
        String editor = Optional.ofNullable(System.getenv().get("EDITOR")).orElse(EDITOR_DEFAULT);
        File tempFile = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value() + EDITOR_FILE);
        tempFile.createNewFile();

        // Run the editor, pipe input into and out of tty so we can provide the input/output to the editor via Graql
        ProcessBuilder builder = new ProcessBuilder(
                "/bin/bash", "-c",
                editor + " </dev/tty >/dev/tty " + tempFile.getAbsolutePath()
        );

        builder.start().waitFor();
        return String.join("\n", Files.readAllLines(tempFile.toPath()));
    }
724550
function _updateFileInfo(editor) {
        var lines = editor.lineCount();
        $fileInfo.text(_formatCountable(lines, Strings.STATUSBAR_LINE_COUNT_SINGULAR, Strings.STATUSBAR_LINE_COUNT_PLURAL));
    }
439887
def save_as(self):
        """"""
        editorstack = self.get_current_editorstack()
        if editorstack.save_as():
            fname = editorstack.get_current_filename()
            self.__add_recent_file(fname)
475347
function deleteCurrentLines(editor) {
        editor = editor || EditorManager.getFocusedEditor();
        if (!editor) {
            return;
        }

        // Walk the selections, calculating the deletion edits we need to do as we go;
        // document.doMultipleEdits() will take care of adjusting the edit locations when
        // it actually performs the edits.
        var doc = editor.document,
            from,
            to,
            lineSelections = editor.convertToLineSelections(editor.getSelections()),
            edits = [];

        _.each(lineSelections, function (lineSel, index) {
            var sel = lineSel.selectionForEdit;

            from = sel.start;
            to = sel.end; // this is already at the beginning of the line after the last selected line
            if (to.line === editor.getLastVisibleLine() + 1) {
                // Instead of deleting the newline after the last line, delete the newline
                // before the beginning of the line--unless this is the entire visible content
                // of the editor, in which case just delete the line content.
                if (from.line > editor.getFirstVisibleLine()) {
                    from.line -= 1;
                    from.ch = doc.getLine(from.line).length;
                }
                to.line -= 1;
                to.ch = doc.getLine(to.line).length;
            }

            // We don't need to track the original selections, since they'll get collapsed as
            // part of the various deletions that occur.
            edits.push({edit: {text: "", start: from, end: to}});
        });
        doc.doMultipleEdits(edits);
    }
1310836
def editorData( self, editor ):
        
        # set the information from a multi-tag edit
        if ( isinstance(editor, XMultiTagEdit) ):
            return editor.tags()
        
        # set the information from a combo box
        elif ( isinstance(editor, QComboBox) ):
            return nativestring(editor.currentText())
        
        # set the information from a line edit
        elif ( isinstance(editor, QLineEdit) ):
            return nativestring(editor.text())
        
        return None
152705
def text_changed(self):
        """"""
        self.default = False
        self.editor.document().changed_since_autosave = True
        self.text_changed_at.emit(self.filename,
                                  self.editor.get_position('cursor'))