Wrap an IPython's Prompt class

    This is needed in order for Prompt to inject the correct escape sequences
    at the right positions for shell integrations.
975549
def wrap_prompts_class(Klass):
    

    try:
        from prompt_toolkit.token import ZeroWidthEscape
    except ImportError:
        return Klass

    class ITerm2IPythonPrompt(Klass):

        def in_prompt_tokens(self, cli=None):
            return  [
                     (ZeroWidthEscape, last_status(self.shell)+BEFORE_PROMPT),
                    ]+\
                    super(ITerm2IPythonPrompt, self).in_prompt_tokens(cli)+\
                    [(ZeroWidthEscape, AFTER_PROMPT)]


    return ITerm2IPythonPrompt
804859
def prompt(text='', title='' , default='', root=None, timeout=None):
    """"""
    assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox'
    return __fillablebox(text, title, default=default, mask=None,root=root, timeout=timeout)
36498
def prompt(prompt_string, default=None, secret=False, boolean=False, bool_type=None):
    
    if boolean or bool_type in BOOLEAN_DEFAULTS:
        if bool_type is None:
            bool_type = 'y_n'
        default_msg = BOOLEAN_DEFAULTS[bool_type][is_affirmative(default)]
    else:
        default_msg = " (default {val}): "
    prompt_string += (default_msg.format(val=default) if default else ": ")
    if secret:
        val = getpass(prompt_string)
    else:
        val = input(prompt_string)
    val = (val if val else default)
    if boolean:
        val = val.lower().startswith('y')
    return val
42541
def hook_wrapper(prompt):
    '''
    try:
        # call the Python hook
        res = ensure_str(readline_hook(prompt))
        # make sure it returned the right sort of thing
        if res and not isinstance(res, str):
            raise TypeError, u'readline must return a string.'
    except KeyboardInterrupt:
        # GNU readline returns 0 on keyboard interrupt
        return 0
    except EOFError:
        # It returns an empty string on EOF
        res = u''
    except:
        print >>sys.stderr, u'Readline internal error'
        traceback.print_exc()
        res = u'\n'
    # we have to make a copy because the caller expects to free the result
    p = _strdup(res)
    return p
1339966
def new_prompt(self, prompt):
        
        if self.get_cursor_line_column()[1] != 0:
            self.write('\n')
        self.write(prompt, prompt=True)
        # now we update our cursor giving end of prompt
        self.current_prompt_pos = self.get_position('cursor')
        self.ensureCursorVisible()
        self.new_input_line = False
802261
def std_input(prompt="", style=None):
    
    p = ansi_wrap(prompt, **(style or {}))
    try:
        return raw_input(p).strip()
    except NameError:
        return input(p).strip()
210166
def password_prompt(ctx, param, value):
    """"""
    if ctx.resilient_parsing:
        return

    if not value:
        if 'password_stdin' in ctx.params:
            with click.open_file('-') as fp:
                value = fp.read().strip('\n')
        else:
            value = click.prompt('Password', hide_input=True)

    click.echo(value)
    return value
116684
def prompt_gui(path):
    """"""

    import subprocess

    filepath, extension = os.path.splitext(path)
    basename = os.path.basename(filepath)
    dirname = os.path.dirname(filepath)

    retry_text = 'Sorry, please try again...'
    icon = 'video-x-generic'

    # detect and configure dialog program
    if have('yad'):
        args = ['yad',
                '--borders=5',
                '--entry',
                '--entry-label=Filename:',
                '--entry-text=' + basename,
                '--title=Batch Tool',
                '--window-icon=' + icon]
        retry_args = args + ['--text=<b>' + retry_text + '</b>',
                             '--text-align=center']

    elif have('zenity'):
        base = ['zenity',
                '--entry',
                '--entry-text=' + basename,
                '--title=Batch Tool',
                '--window-icon=info']
        args = base + ['--text=Filename:']
        retry_args = base + ['--text=' + retry_text]

    else:
        fatal('Please install yad (or zenity)')

    # display filename prompt
    try:
        new_basename = subprocess.check_output(
            args, universal_newlines=True).strip()
    except subprocess.CalledProcessError:
        sys.exit(1)

    # retry prompt if new filename already exists
    while os.path.exists(os.path.join(dirname, new_basename + extension)) and \
            new_basename != basename:
        try:
            new_basename = subprocess.check_output(
                retry_args, universal_newlines=True).strip()
        except subprocess.CalledProcessError:
            sys.exit(1)

    if new_basename == '':
        new_basename = basename

    return os.path.join(dirname, new_basename + extension)
978759
def wrap_setup(self, class_name, typ, with_async=False):
        """"""
        equivalence = self.equivalence[typ]
        return [
              (NEWLINE, '\n')
            , (NAME, class_name)
            , (OP, '.')
            , (NAME, equivalence)
            , (OP, '=')
            , (NAME, "%snoy_wrap_%s" % ('async_' if with_async else '', equivalence))
            , (OP, "(")
            , (NAME, class_name)
            , (OP, ',')
            , (NAME, class_name)
            , (OP, '.')
            , (NAME, equivalence)
            , (OP, ")")
            ]
400761
def wrap_toks(self, block, lineno, indent):
        """"""
        tokens = tokenize.generate_tokens(self.gen_lines(block, indent).next)
        for type, value, (line0, col0), (line1, col1), line_text in tokens:
            line0 += lineno - 1
            line1 += lineno - 1
            # Don't bother updating the columns; this is too complicated
            # since line_text would also have to be updated and it would
            # still break for tokens spanning lines.  Let the user guess
            # that the column numbers for doctests are relative to the
            # end of the prompt string (PS1 or PS2).
            yield type, value, (line0, col0), (line1, col1), line_text
833525
def ipython_paste(*args, **kwargs):
    
    if WIN32:
        pass
    else:
        winhandle = 'joncrall@Hyrule'
        args1 = ['wmctrl', '-a', winhandle]
        args2 = ['xdotool', 'key', 'shift+5', 'p', 'a', 's', 't', 'e', 'enter']
        os.system(' '.join(args1))
        os.system(' '.join(args2))
1112479
def regexp_prompt(prompt, regexp='.', answer=''):
    '''
    
    '''
    get_input = getattr(__builtins__, 'raw_input', input)
    while not re.search(regexp, answer):
        answer = get_input(prompt + ': ').strip()
        # If the option isn't valid, this is shown next
        message = "Your entry must match the regular expression %s" %regexp    

    return answer
34804
def hook_wrapper_23(stdin, stdout, prompt):
    '''
    try:
        # call the Python hook
        res = ensure_str(readline_hook(prompt))
        # make sure it returned the right sort of thing
        if res and not isinstance(res, str):
            raise TypeError, u'readline must return a string.'
    except KeyboardInterrupt:
        # GNU readline returns 0 on keyboard interrupt
        return 0
    except EOFError:
        # It returns an empty string on EOF
        res = u''
    except:
        print >>sys.stderr, u'Readline internal error'
        traceback.print_exc()
        res = u'\n'
    # we have to make a copy because the caller expects to free the result
    n = len(res)
    p = Console.PyMem_Malloc(n + 1)
    _strncpy(cast(p, c_char_p), res, n + 1)
    return p
213363
def _prompt_wrapper(message, default=None, validator=None):
    

    class MockDocument:

        def __init__(self, text):
            self.text = text

    if HAS_INPUT:
        ret = prompt(message, default=default, validator=validator)
    else:
        ret = sys.stdin.readline().strip()
        print(message, ret)
        if validator:
            validator.validate(MockDocument(ret))
    if "q" in ret:
        if not HAS_OUTPUT:
            print("User exit")
        sys.exit("User exit")
    return ret
135377
def prompt(msg, default=None):
    ""
    if default is not None:
        msg = '{} ({})'.format(msg, repr(default))
    msg = '{}: '.format(msg)
    try:
        s = input(msg)
    except KeyboardInterrupt:
        exit(1)
    except EOFError:
        s = ''
    if not s:
        s = default
    return s
775574
def wrap(self, starter_cls):
        
        if isinstance(starter_cls, type) and issubclass(starter_cls, ProcessStarter):
            return starter_cls
        depr_msg = 'Pass a ProcessStarter for preparefunc'
        warnings.warn(depr_msg, DeprecationWarning, stacklevel=3)
        return functools.partial(CompatStarter, starter_cls)
945919
def _fix_unsafe(shell_input):
    
    _unsafe = re.compile(r'[^\w@%+=:,./-]', 256)
    try:
        if len(_unsafe.findall(shell_input)) == 0:
            return shell_input.strip()
        else:
            clean = "'" + shell_input.replace("'", "'\"'\"'") + "'"
            return clean
    except TypeError:
        return None