Edit a line with one code object built in the ctor.
333783
def __edit_line(line, code, code_obj):  # pylint: disable=R0201
        """"""
        try:
            # pylint: disable=eval-used
            result = eval(code_obj, globals(), locals())
        except TypeError as ex:
            log.error("failed to execute %s: %s", code, ex)
            raise
        if result is None:
            log.error("cannot process line '%s' with %s", line, code)
            raise RuntimeError('failed to process line')
        elif isinstance(result, list) or isinstance(result, tuple):
            line = unicode(' '.join([unicode(res_element)
                                     for res_element in result]))
        else:
            line = unicode(result)
        return line
1286392
def refactor(self, symbol, value):
        
        if value:
            self.pset.add(symbol)
        else:
            self.pset.remove(symbol)
130641
def code_to_text(self):
        """"""
        active = is_active(self.ext, self.metadata)
        source = copy(self.source)
        escape_code_start(source, self.ext, self.language)

        if active:
            comment_magic(source, self.language, self.comment_magics)

        if not active:
            source = ['# ' + line if line else '#' for line in source]

        lines = []
        if not is_active('R', self.metadata):
            self.metadata['eval'] = False
        options = metadata_to_rmd_options(None, self.metadata)
        if options:
            lines.append('#+ {}'.format(options))
        lines.extend(source)
        return lines
440731
def transform(self, line, _continue_prompt):
        """'"""

        # Capture the original line
        orig_line = line

        # Get tokens from all the currently active namespace
        ns_token_set = set([token for nspace in self.shell.all_ns_refs for token in nspace])

        # Build up token set and info out of the incoming line
        token_list = re.split(' |;|,|(|)|\'|"', line)
        token_list = [item for item in token_list if item != None and item != '']
        num_tokens = len(token_list)
        first_token = token_list[0]
        token_set = set(token_list)       

        # Very conservative logic (but possibly flawed)
        # 1) Lines with any of these symbols ; , ' " ( ) aren't touched
        # 2) Need to have more than one token
        # 3) First token in line must be in the workbench command set
        # 4) If first token is 'help' than all other tokens are quoted
        # 5) Otherwise only tokens that are not in any of the namespace are quoted

        # Fixme: Horse shit temp hack for load_sample
        # 0) If load_sample do special processing
        if first_token == 'load_sample':
            # If the second arg isn't in namespace quote it
            if token_list[1] not in ns_token_set:
                line = line.replace(token_list[1], '"'+token_list[1]+'",')
            return line

        # Fixme: Horse shit temp hack for pivot
        # 0) If pivot do special processing
        if first_token == 'pivot':
            # Quote all other tokens
            for token in token_list:
                if token not in ns_token_set:
                    line = line.replace(token, '"' + token + '",')
            return line

        # 1) Lines with any of these symbols ; , ' " ( ) aren't touched
        skip_symbols = [';', ',', '\'', '"', '(', ')']
        if any([sym in line for sym in skip_symbols]):
            return line

        # 2) Need to have more than one token
        # 3) First token in line must be in the workbench command set
        if num_tokens > 1 and first_token in self.command_set:

            # 4) If first token is 'help' than all other tokens are quoted
            if first_token == 'help':
                token_set.remove('help')
                for token in token_set:
                    line = line.replace(token, '"'+token+'"')

            # 5) Otherwise only tokens that are not in any of the namespace are quoted
            else: # Not help
                for token in token_set:
                    if token not in ns_token_set:
                        line = line.replace(token, '"'+token+'"')

        # Return the processed line
        return line
268518
def register_code_edit(cls, code_edit_class):
        
        if not inspect.isclass(code_edit_class):
            raise TypeError('must be a class, not an instance.')
        for mimetype in code_edit_class.mimetypes:
            if mimetype in cls.editors:
                _logger().warn('editor for mimetype already registered, '
                               'skipping')
            cls.editors[mimetype] = code_edit_class
        _logger().log(5, 'registered editors: %r', cls.editors)
487659
def rewritten_code
      if rewritten_source.split("\n").length > 1
        "\n\n" + rewritten_source.split("\n").map { |line|
          indent(@node) + line
        }.join("\n")
      else
        "\n" + indent(@node) + rewritten_source
      end
    end
230274
def update_extent(self, operation):
        """"""
        #Operations represent continuous lines of code.
        #The last operation to be executed is still the current one.
        line, col = operation.start
        operation.context.module.update_elements(line, col, operation.length,
                                                 operation.docdelta)
260338
def _compile(cls, lines):
        ''''''
        m = cls.RE_PASTE.match(lines.current)
        if m is None:
            raise MacroBlockUsageError(
                'Incorrect macro or block usage at line {}, {}\nShould be '
                'something like: #my_macro'.format(lines.pos, lines.current))
        return m.group(1)
806904
def copy(self):
        
        if self.select_line_on_copy_empty and not self.textCursor().hasSelection():
            TextHelper(self).select_whole_line()
        super(CodeEdit, self).copy()
359165
def format_code(source, preferred_quote="'"):
    """"""
    try:
        return _format_code(source, preferred_quote)
    except (tokenize.TokenError, IndentationError):
        return source
103259
def _do_code_blocks(self, text):
        """"""
        code_block_re = re.compile(r'''
            (?:\n\n|\A\n?)
            (               # $1 = the code block -- one or more lines, starting with a space/tab
              (?:
                (?:[ ]{%d} | \t)  # Lines must start with a tab or a tab-width of spaces
                .*\n+
              )+
            )
            ((?=^[ ]{0,%d}\S)|\Z)   # Lookahead for non-space at line-start, or end of doc
            ''' % (self.tab_width, self.tab_width),
            re.M | re.X)
        return code_block_re.sub(self._code_block_sub, text)
767419
def write_docstring_at_first_line_of_function(self):
        """"""
        result = self.get_function_definition_from_first_line()
        editor = self.code_editor
        if result:
            func_text, number_of_line_func = result
            line_number_function = (self.line_number_cursor +
                                    number_of_line_func - 1)

            cursor = editor.textCursor()
            line_number_cursor = cursor.blockNumber() + 1
            offset = line_number_function - line_number_cursor
            if offset > 0:
                for __ in range(offset):
                    cursor.movePosition(QTextCursor.NextBlock)
            else:
                for __ in range(abs(offset)):
                    cursor.movePosition(QTextCursor.PreviousBlock)
            cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.MoveAnchor)
            editor.setTextCursor(cursor)

            indent = get_indent(func_text)
            editor.insert_text('\n{}{}"""'.format(indent, editor.indent_chars))
            self.write_docstring()
569432
def edit_line lineno=@current_index
      line = self[lineno]
      prompt = "Edit: "
      maxlen = 80
      config={}; 
      oldline = line.dup
      config[:default] = line
      ret, str = rb_getstr(@form.window, $error_message_row, $error_message_col,  prompt, maxlen, config)
      $log.debug " rb_getstr returned #{ret} , #{str} "
      return if ret != 0
      # we possibly cou;d have done []= but maybe in textpad or something that would replace a row pointer ??
      self[lineno].replace(str)
      fire_handler :CHANGE, InputDataEvent.new(0,oldline.length, self, :DELETE_LINE, lineno, oldline)     #  2008-12-24 18:34 
      fire_handler :CHANGE, InputDataEvent.new(0,str.length, self, :INSERT_LINE, lineno, str)
      fire_row_changed lineno
    end
7827
def fix_lines(source_lines, options, filename=''):
    """"""
    # Transform everything to line feed. Then change them back to original
    # before returning fixed source code.
    original_newline = find_newline(source_lines)
    tmp_source = ''.join(normalize_line_endings(source_lines, '\n'))

    # Keep a history to break out of cycles.
    previous_hashes = set()

    if options.line_range:
        # Disable "apply_local_fixes()" for now due to issue #175.
        fixed_source = tmp_source
    else:
        pep8_options = {
            'ignore': options.ignore,
            'select': options.select,
            'max_line_length': options.max_line_length,
            'hang_closing': options.hang_closing,
        }
        sio = io.StringIO(tmp_source)
        contents = sio.readlines()
        results = _execute_pep8(pep8_options, contents)
        codes = {result['id'] for result in results
                 if result['id'] in SELECTED_GLOBAL_FIXED_METHOD_CODES}
        # Apply global fixes only once (for efficiency).
        fixed_source = apply_global_fixes(tmp_source,
                                          options,
                                          filename=filename,
                                          codes=codes)

    passes = 0
    long_line_ignore_cache = set()
    while hash(fixed_source) not in previous_hashes:
        if options.pep8_passes >= 0 and passes > options.pep8_passes:
            break
        passes += 1

        previous_hashes.add(hash(fixed_source))

        tmp_source = copy.copy(fixed_source)

        fix = FixPEP8(
            filename,
            options,
            contents=tmp_source,
            long_line_ignore_cache=long_line_ignore_cache)

        fixed_source = fix.fix()

    sio = io.StringIO(fixed_source)
    return ''.join(normalize_line_endings(sio.readlines(), original_newline))
666191
def cli(ctx, editor):
    """"""

    commands = utils.read_commands()
    if commands is []:
        click.echo("No commands to edit, Add one by 'keep new'. ")
    else:
        edit_header = "# Unchanged file will abort the operation\n"
        new_commands = utils.edit_commands(commands, editor, edit_header)
        if new_commands and new_commands != commands:
            click.echo("Replace:\n")
            click.secho("\t{}".format('\n\t'.join(utils.format_commands(commands))),
                        fg="green")
            click.echo("With:\n\t")
            click.secho("\t{}".format('\n\t'.join(utils.format_commands(new_commands))),
                        fg="green")
            if click.confirm("", default=False):
                utils.write_commands(new_commands)
179144
def fix_indentation(code, base_indentation=None, correct_indentation="",
                    modifiers=(True, True)):
    
    if base_indentation is None:
        base_indentation = get_base_indentation(code, modifiers[0])
    return re_line_and_indentation(base_indentation, modifiers).sub(
        "\n" + correct_indentation, code)
474600
private static String addLineNumber(String code) {
		String[] lines = code.split("\n");
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < lines.length; i++) {
			builder.append("/* ").append(i + 1).append(" */").append(lines[i]).append("\n");
		}
		return builder.toString();
	}