'Return selected text as a processed text,
to be executable in a Python/IPython interpreter'

def get_selection_as_executable_code(self):

    ls = self.get_line_separator()
    _indent = (lambda line: (len(line) - len(line.lstrip())))
    (line_from, line_to) = self.get_selection_bounds()
    text = self.get_selected_text()
    if (not text):
        return
    lines = text.split(ls)
    if (len(lines) > 1):
        original_indent = _indent(self.get_text_line(line_from))
        text = (('    ' * (original_indent - _indent(lines[0]))) + text)
    min_indent = 999
    current_indent = 0
    lines = text.split(ls)
    for i in range((len(lines) - 1), (-1), (-1)):
        line = lines[i]
        if line.strip():
            current_indent = _indent(line)
            min_indent = min(current_indent, min_indent)
        else:
            lines[i] = ('    ' * current_indent)
    if min_indent:
        lines = [line[min_indent:] for line in lines]
    while lines:
        first_line = lines[0].lstrip()
        if ((first_line == '') or (first_line[0] == '#')):
            lines.pop(0)
        else:
            break
    varname = re.compile('[a-zA-Z0-9_]*')
    maybe = False
    nextexcept = ()
    for (n, line) in enumerate(lines):
        if (not _indent(line)):
            word = varname.match(line).group()
            if (maybe and (word not in nextexcept)):
                lines[(n - 1)] += ls
                maybe = False
            if word:
                if (word in ('def', 'for', 'while', 'with', 'class')):
                    maybe = True
                    nextexcept = ()
                elif (word == 'if'):
                    maybe = True
                    nextexcept = ('elif', 'else')
                elif (word == 'try'):
                    maybe = True
                    nextexcept = ('except', 'finally')
    if maybe:
        if (lines[(-1)].strip() == ''):
            lines[(-1)] += ls
        else:
            lines.append(ls)
    return ls.join(lines)
