diff --git a/python/ycm/tests/vimsupport_test.py b/python/ycm/tests/vimsupport_test.py index f789f045..b8137efb 100644 --- a/python/ycm/tests/vimsupport_test.py +++ b/python/ycm/tests/vimsupport_test.py @@ -1255,3 +1255,39 @@ def TextAfterCursor_EncodedUnicode_test( *args ): @patch( 'vim.current.line', ToBytes( 'fДa' ) ) def CurrentLineContents_EncodedUnicode_test( *args ): eq_( vimsupport.CurrentLineContents(), u'fДa' ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_IntAsUnicode_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( '123' ), 123 ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_IntAsBytes_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( ToBytes( '123' ) ), 123 ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_StringAsUnicode_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( 'foo' ), 'foo' ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_StringAsBytes_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( ToBytes( 'foo' ) ), 'foo' ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_ListPassthrough_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( [ 1, 2 ] ), [ 1, 2 ] ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_ObjectPassthrough_test( *args ): + eq_( vimsupport.VimExpressionToPythonType( { 1: 2 } ), { 1: 2 } ) + + +@patch( 'vim.eval', side_effect = lambda x: x ) +def VimExpressionToPythonType_GeneratorPassthrough_test( *args ): + gen = ( x**2 for x in [ 1, 2, 3 ] ) + eq_( vimsupport.VimExpressionToPythonType( gen ), gen ) diff --git a/python/ycm/vimsupport.py b/python/ycm/vimsupport.py index be55e3e0..514c1d05 100644 --- a/python/ycm/vimsupport.py +++ b/python/ycm/vimsupport.py @@ -318,13 +318,20 @@ def GetReadOnlyVimGlobals( force_python_objects = False ): def VimExpressionToPythonType( vim_expression ): + """Returns a Python type from the return value of the supplied Vim expression. + If the expression returns a list, dict or other non-string type, then it is + returned unmodified. If the string return can be converted to an + integer, returns an integer, otherwise returns the result converted to a + Unicode string.""" + result = vim.eval( vim_expression ) - if not isinstance( result, str ) or isinstance( result, bytes ): - return ToUnicode( result ) + if not ( isinstance( result, str ) or isinstance( result, bytes ) ): + return result + try: return int( result ) except ValueError: - return result + return ToUnicode( result ) def HiddenEnabled( buffer_object ):