Esempio n. 1
0
    def GetPathsIncludeCase(self, path_dir, quoted_include, filepath,
                            client_data):
        paths = []
        quoted_include_paths, include_paths = (self._flags.UserIncludePaths(
            filepath, client_data))

        if quoted_include:
            include_paths.extend(quoted_include_paths)

        for include_path in include_paths:
            unicode_path = ToUnicode(os.path.join(include_path, path_dir))
            try:
                # We need to pass a unicode string to get unicode strings out of
                # listdir.
                relative_paths = os.listdir(unicode_path)
            except:
                relative_paths = []

            paths.extend(
                os.path.join(include_path, path_dir, relative_path)
                for relative_path in relative_paths)

        return sorted(set(paths))
        def Wrapper(*args, **kwargs):
            try:
                test(*args, **kwargs)
            except Exception as test_exception:
                # Ensure that we failed for the right reason
                test_exception_message = ToUnicode(test_exception)
                try:
                    for matcher in exception_matchers:
                        assert_that(test_exception_message, matcher)
                except AssertionError:
                    # Failed for the wrong reason!
                    import traceback
                    print('Test failed for the wrong reason: ' +
                          traceback.format_exc())
                    # Real failure reason is the *original* exception, we're only trapping
                    # and ignoring the exception that is expected.
                    raise test_exception

                # Failed for the right reason
                raise nose.SkipTest(reason)
            else:
                raise AssertionError(
                    'Test was expected to fail: {0}'.format(reason))
Esempio n. 3
0
def _ConvertCompletionDataToVimData( completion_data ):
  # See :h complete-items for a description of the dictionary fields.
  return {
    'word'     : completion_data[ 'insertion_text' ],
    'abbr'     : completion_data.get( 'menu_text', '' ),
    'menu'     : completion_data.get( 'extra_menu_info', '' ),
    'info'     : _GetCompletionInfoField( completion_data ),
    'kind'     : ToUnicode( completion_data.get( 'kind', '' ) )[ :1 ].lower(),
    # Disable Vim filtering.
    'equal'    : 1,
    'dup'      : 1,
    'empty'    : 1,
    # We store the completion item extra_data as a string in the completion
    # user_data. This allows us to identify the _exact_ item that was completed
    # in the CompleteDone handler, by inspecting this item from v:completed_item
    #
    # We convert to string because completion user data items must be strings.
    #
    # Note: Not all versions of Vim support this (added in 8.0.1483), but adding
    # the item to the dictionary is harmless in earlier Vims.
    # Note: Since 8.2.0084 we don't need to use json.dumps() here.
    'user_data': json.dumps( completion_data.get( 'extra_data', {} ) )
  }
Esempio n. 4
0
    def _PostRequest(self, request, request_data):
        """Send a raw request with the supplied request block, and
    return the server's response. If the server is not running, it is started.

    This method is useful where the query block is not supplied, i.e. where just
    the files are being updated.

    The request block should contain the optional query block only. The file
    data are added automatically."""

        if not self._ServerIsRunning():
            raise ValueError('Not connected to server')

        def MakeIncompleteFile(name, file_data):
            return {
                'type': 'full',
                'name': name,
                'text': file_data['contents'],
            }

        file_data = request_data.get('file_data', {})

        full_request = {
            'files': [
                MakeIncompleteFile(x, file_data[x]) for x in file_data.keys()
                if 'javascript' in file_data[x]['filetypes']
            ],
        }
        full_request.update(request)
        try:
            response = urllib.request.urlopen(self._GetServerAddress(),
                                              data=ToBytes(
                                                  json.dumps(full_request)))

            return json.loads(response.read())
        except urllib.error.HTTPError as response:
            raise RuntimeError(ToUnicode(response.fp.read()))
Esempio n. 5
0
    def UserIncludePaths(self, filename, client_data):
        flags = [
            ToUnicode(x)
            for x in self.FlagsForFile(filename, client_data=client_data)
        ]

        quoted_include_paths = [os.path.dirname(filename)]
        include_paths = []

        if flags:
            quote_flag = '-iquote'
            path_flags = ['-isystem', '-I']

            try:
                it = iter(flags)
                for flag in it:
                    flag_len = len(flag)
                    if flag.startswith(quote_flag):
                        quote_flag_len = len(quote_flag)
                        # Add next flag to the include paths if current flag equals to
                        # '-iquote', or add remaining string otherwise.
                        quoted_include_paths.append(
                            next(it) if flag_len ==
                            quote_flag_len else flag[quote_flag_len:])
                    else:
                        for path_flag in path_flags:
                            if flag.startswith(path_flag):
                                path_flag_len = len(path_flag)
                                include_paths.append(
                                    next(it) if flag_len ==
                                    path_flag_len else flag[path_flag_len:])
                                break
            except StopIteration:
                pass

        return ([x for x in quoted_include_paths
                 if x], [x for x in include_paths if x])
Esempio n. 6
0
def _CallExtraConfFlagsForFile(module, filename, client_data):
    # We want to ensure we pass a native py2 `str` on py2 and a native py3 `str`
    # (unicode) object on py3. That's the API we provide.
    # In a vacuum, always passing a unicode object (`unicode` on py2 and `str` on
    # py3) would be better, but we can't do that because that would break all the
    # ycm_extra_conf files already out there that expect a py2 `str` object on
    # py2, and WE DO NOT BREAK BACKWARDS COMPATIBILITY.
    # Hindsight is 20/20.
    if PY2:
        filename = native(ToBytes(filename))
    else:
        filename = native(ToUnicode(filename))

    # For the sake of backwards compatibility, we need to first check whether the
    # FlagsForFile function in the extra conf module even allows keyword args.
    if inspect.getargspec(module.FlagsForFile).keywords:
        results = module.FlagsForFile(filename, client_data=client_data)
    else:
        results = module.FlagsForFile(filename)

    results['flags'] = _MakeRelativePathsInFlagsAbsolute(
        results['flags'], results.get('include_paths_relative_to_dir'))

    return results
Esempio n. 7
0
  def GetIncludePaths( self, request_data ):
    column_codepoint = request_data[ 'column_codepoint' ] - 1
    current_line = request_data[ 'line_value' ]
    line = current_line[ : column_codepoint ]
    path_dir, quoted_include, start_codepoint = (
        GetIncompleteIncludeValue( line ) )
    if start_codepoint is None:
      return None

    request_data[ 'start_codepoint' ] = start_codepoint

    # We do what GCC does for <> versus "":
    # http://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html
    flags, filepath = self._FlagsForRequest( request_data )
    quoted_include_paths, include_paths = UserIncludePaths( flags, filepath )
    if quoted_include:
      include_paths.extend( quoted_include_paths )

    includes = IncludeList()
    for include_path in include_paths:
      unicode_path = ToUnicode( os.path.join( include_path, path_dir ) )
      includes.AddIncludes( self._include_cache.GetIncludes( unicode_path ) )

    return includes.GetIncludes()
Esempio n. 8
0
    def ComputeCandidatesInner(self, request_data):
        filename = request_data['filepath']
        LOGGER.info('Gocode completion request %s', filename)

        contents = utils.ToBytes(
            request_data['file_data'][filename]['contents'])

        # NOTE: Offsets sent to gocode are byte offsets, so using start_column
        # with contents (a bytes instance) above is correct.
        offset = _ComputeOffset(contents, request_data['line_num'],
                                request_data['start_column'])

        stdoutdata = self._ExecuteCommand([
            self._gocode_binary_path, '-sock', 'tcp', '-addr',
            self._gocode_host, '-f=json', 'autocomplete', filename,
            str(offset)
        ],
                                          contents=contents)

        try:
            resultdata = json.loads(ToUnicode(stdoutdata))
        except ValueError:
            LOGGER.error(GOCODE_PARSE_ERROR_MESSAGE)
            raise RuntimeError(GOCODE_PARSE_ERROR_MESSAGE)

        if not isinstance(resultdata, list) or len(resultdata) != 2:
            LOGGER.error(GOCODE_NO_COMPLETIONS_MESSAGE)
            raise RuntimeError(GOCODE_NO_COMPLETIONS_MESSAGE)
        for result in resultdata[1]:
            if result.get('class') == 'PANIC':
                raise RuntimeError(GOCODE_PANIC_MESSAGE)

        return [
            responses.BuildCompletionData(insertion_text=x['name'],
                                          extra_data=x) for x in resultdata[1]
        ]
Esempio n. 9
0
def TextBeforeCursor():
    """Returns the text before CurrentColumn."""
    return ToUnicode(vim.current.line[:CurrentColumn()])
Esempio n. 10
0
def CurrentLineContents():
    return ToUnicode(vim.current.line)
Esempio n. 11
0
def _PrepareTrigger( trigger ):
  trigger = ToUnicode( trigger )
  if trigger.startswith( TRIGGER_REGEX_PREFIX ):
    return re.compile( trigger[ len( TRIGGER_REGEX_PREFIX ) : ], re.UNICODE )
  return re.compile( re.escape( trigger ), re.UNICODE )
Esempio n. 12
0
 def setUp(self):
     self._hmac_secret = os.urandom(HMAC_SECRET_LENGTH)
     self._options_dict['hmac_secret'] = ToUnicode(
         b64encode(self._hmac_secret))
Esempio n. 13
0
def PostMultiLineNotice( message ):
  vim.command( "echohl WarningMsg | echo '{0}' | echohl None"
               .format( EscapeForVim( ToUnicode( message ) ) ) )
Esempio n. 14
0
def GetBufferFiletypes( bufnr ):
  command = f'getbufvar({ bufnr }, "&ft")'
  filetypes = vim.eval( command )
  if not filetypes:
    filetypes = 'ycm_nofiletype'
  return ToUnicode( filetypes ).split( '.' )
Esempio n. 15
0
def CurrentFiletypes():
  filetypes = vim.eval( "&filetype" )
  if not filetypes:
    filetypes = 'ycm_nofiletype'
  return ToUnicode( filetypes ).split( '.' )
Esempio n. 16
0
def FiletypesForBuffer( buffer_object ):
  # NOTE: Getting &ft for other buffers only works when the buffer has been
  # visited by the user at least once, which is true for modified buffers
  return ToUnicode( GetBufferOption( buffer_object, 'ft' ) ).split( '.' )
Esempio n. 17
0
def PostVimMessage( message ):
  vim.command( "redraw | echohl WarningMsg | echom '{0}' | echohl None"
               .format( EscapeForVim( ToUnicode( message ) ) ) )
Esempio n. 18
0
def _FormatRawComment( comment ):
  """Strips leading indentation and comment markers from the comment string"""
  return textwrap.dedent(
    '\n'.join( [ re.sub( STRIP_TRAILING_COMMENT, '',
                 re.sub( STRIP_LEADING_COMMENT, '', line ) )
                 for line in ToUnicode( comment ).splitlines() ] ) )
Esempio n. 19
0
def getBufferFiletypeByNumber(bufnr):
    command = 'getbufvar({0}, "&ft")'.format(bufnr)
    return ToUnicode(vim.eval(command)).split('.')[0]
Esempio n. 20
0
def UsingPreviewPopup():
    return 'popup' in ToUnicode(vim.options['completeopt']).split(',')
Esempio n. 21
0
def Parse(data):
    """Reads the raw language server message payload into a Python dictionary"""
    return json.loads(ToUnicode(data))
Esempio n. 22
0
def GetBufferFiletypes(bufnr):
    command = f'getbufvar({ bufnr }, "&ft")'
    return ToUnicode(vim.eval(command)).split('.')
Esempio n. 23
0
 def GetLines(self):
     """Returns the contents of the buffer as a list of unicode strings."""
     return [ToUnicode(x) for x in self.contents]
Esempio n. 24
0
def _GetRustSysroot(rustc_exec):
    return ToUnicode(
        utils.SafePopen([rustc_exec, '--print', 'sysroot'],
                        stdin_windows=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE).communicate()[0].rstrip())
Esempio n. 25
0
def EscapeForVim(text):
    return ToUnicode(text.replace("'", "''"))
Esempio n. 26
0
def CurrentFiletypes():
    return ToUnicode(vim.eval("&filetype")).split('.')
Esempio n. 27
0
def TextAfterCursor():
    """Returns the text after CurrentColumn."""
    return ToUnicode(vim.current.line[CurrentColumn():])
Esempio n. 28
0
def GetBufferFilepath(buffer_object):
    if buffer_object.name:
        return ToUnicode(buffer_object.name)
    # Buffers that have just been created by a command like :enew don't have any
    # buffer name so we use the buffer number for that.
    return os.path.join(GetCurrentDirectory(), str(buffer_object.number))
Esempio n. 29
0
 def matcher(key):
     return (ToUnicode(completed_item.get(key, "")) == ToUnicode(
         item.get(key, "")))
Esempio n. 30
0
def _ExtractFlagsList(flags_for_file_output):
    return [ToUnicode(x) for x in flags_for_file_output['flags']]