1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057 |
- from __future__ import unicode_literals
- from __future__ import print_function
- from __future__ import division
- from __future__ import absolute_import
- from builtins import *
- from future.utils import iterkeys
- import vim
- import os
- import json
- import re
- from collections import defaultdict
- from ycmd.utils import ( ByteOffsetToCodepointOffset, GetCurrentDirectory,
- JoinLinesAsUnicode, ToBytes, ToUnicode )
- from ycmd import user_options_store
- BUFFER_COMMAND_MAP = { 'same-buffer' : 'edit',
- 'horizontal-split' : 'split',
- 'vertical-split' : 'vsplit',
- 'new-tab' : 'tabedit' }
- FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT = (
- 'The requested operation will apply changes to {0} files which are not '
- 'currently open. This will therefore open {0} new files in the hidden '
- 'buffers. The quickfix list can then be used to review the changes. No '
- 'files will be written to disk. Do you wish to continue?' )
- NO_SELECTION_MADE_MSG = "No valid selection was made; aborting."
- def CurrentLineAndColumn():
- """Returns the 0-based current line and 0-based current column."""
-
-
- line, column = vim.current.window.cursor
- line -= 1
- return line, column
- def SetCurrentLineAndColumn( line, column ):
- """Sets the cursor position to the 0-based line and 0-based column."""
-
- vim.current.window.cursor = ( line + 1, column )
- def CurrentColumn():
- """Returns the 0-based current column. Do NOT access the CurrentColumn in
- vim.current.line. It doesn't exist yet when the cursor is at the end of the
- line. Only the chars before the current column exist in vim.current.line."""
-
-
-
-
-
- return vim.current.window.cursor[ 1 ]
- def CurrentLineContents():
- return ToUnicode( vim.current.line )
- def CurrentLineContentsAndCodepointColumn():
- """Returns the line contents as a unicode string and the 0-based current
- column as a codepoint offset. If the current column is outside the line,
- returns the column position at the end of the line."""
- line = CurrentLineContents()
- byte_column = CurrentColumn()
-
- column = ByteOffsetToCodepointOffset( line, byte_column + 1 ) - 1
- return line, column
- def TextAfterCursor():
- """Returns the text after CurrentColumn."""
- return ToUnicode( vim.current.line[ CurrentColumn(): ] )
- def TextBeforeCursor():
- """Returns the text before CurrentColumn."""
- return ToUnicode( vim.current.line[ :CurrentColumn() ] )
- def GetBufferOption( buffer_object, option ):
-
-
-
-
-
-
-
-
- to_eval = 'getbufvar({0}, "&{1}")'.format( buffer_object.number, option )
- return GetVariableValue( to_eval )
- def BufferModified( buffer_object ):
- return bool( int( GetBufferOption( buffer_object, 'mod' ) ) )
- def GetUnsavedAndSpecifiedBufferData( including_filepath ):
- """Build part of the request containing the contents and filetypes of all
- dirty buffers as well as the buffer with filepath |including_filepath|."""
- buffers_data = {}
- for buffer_object in vim.buffers:
- buffer_filepath = GetBufferFilepath( buffer_object )
- if not ( BufferModified( buffer_object ) or
- buffer_filepath == including_filepath ):
- continue
- buffers_data[ buffer_filepath ] = {
-
- 'contents': JoinLinesAsUnicode( buffer_object ) + '\n',
- 'filetypes': FiletypesForBuffer( buffer_object )
- }
- return buffers_data
- def GetBufferNumberForFilename( filename, open_file_if_needed = True ):
- return GetIntValue( u"bufnr('{0}', {1})".format(
- EscapeForVim( os.path.realpath( filename ) ),
- int( open_file_if_needed ) ) )
- def GetCurrentBufferFilepath():
- return GetBufferFilepath( vim.current.buffer )
- def BufferIsVisible( buffer_number ):
- if buffer_number < 0:
- return False
- window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) )
- return window_number != -1
- def GetBufferFilepath( buffer_object ):
- if buffer_object.name:
- return ToUnicode( buffer_object.name )
-
-
- return os.path.join( GetCurrentDirectory(), str( buffer_object.number ) )
- def GetCurrentBufferNumber():
- return vim.current.buffer.number
- def GetBufferChangedTick( bufnr ):
- return GetIntValue( 'getbufvar({0}, "changedtick")'.format( bufnr ) )
- def UnplaceSignInBuffer( buffer_number, sign_id ):
- if buffer_number < 0:
- return
- vim.command(
- 'try | exec "sign unplace {0} buffer={1}" | catch /E158/ | endtry'.format(
- sign_id, buffer_number ) )
- def PlaceSign( sign_id, line_num, buffer_num, is_error = True ):
-
-
- if line_num < 1:
- line_num = 1
- sign_name = 'YcmError' if is_error else 'YcmWarning'
- vim.command( 'sign place {0} name={1} line={2} buffer={3}'.format(
- sign_id, sign_name, line_num, buffer_num ) )
- def ClearYcmSyntaxMatches():
- matches = VimExpressionToPythonType( 'getmatches()' )
- for match in matches:
- if match[ 'group' ].startswith( 'Ycm' ):
- vim.eval( 'matchdelete({0})'.format( match[ 'id' ] ) )
- def AddDiagnosticSyntaxMatch( line_num,
- column_num,
- line_end_num = None,
- column_end_num = None,
- is_error = True ):
- """Highlight a range in the current window starting from
- (|line_num|, |column_num|) included to (|line_end_num|, |column_end_num|)
- excluded. If |line_end_num| or |column_end_num| are not given, highlight the
- character at (|line_num|, |column_num|). Both line and column numbers are
- 1-based. Return the ID of the newly added match."""
- group = 'YcmErrorSection' if is_error else 'YcmWarningSection'
- line_num, column_num = LineAndColumnNumbersClamped( line_num, column_num )
- if not line_end_num or not column_end_num:
- return GetIntValue(
- "matchadd('{0}', '\%{1}l\%{2}c')".format( group, line_num, column_num ) )
-
- line_end_num, column_end_num = LineAndColumnNumbersClamped(
- line_end_num, column_end_num - 1 )
- column_end_num += 1
- return GetIntValue(
- "matchadd('{0}', '\%{1}l\%{2}c\_.\\{{-}}\%{3}l\%{4}c')".format(
- group, line_num, column_num, line_end_num, column_end_num ) )
- def LineAndColumnNumbersClamped( line_num, column_num ):
- new_line_num = line_num
- new_column_num = column_num
- max_line = len( vim.current.buffer )
- if line_num and line_num > max_line:
- new_line_num = max_line
- max_column = len( vim.current.buffer[ new_line_num - 1 ] )
- if column_num and column_num > max_column:
- new_column_num = max_column
- return new_line_num, new_column_num
- def SetLocationList( diagnostics ):
- """Populate the location list with diagnostics. Diagnostics should be in
- qflist format; see ":h setqflist" for details."""
- vim.eval( 'setloclist( 0, {0} )'.format( json.dumps( diagnostics ) ) )
- def OpenLocationList( focus = False, autoclose = False ):
- """Open the location list to full width at the bottom of the screen with its
- height automatically set to fit all entries. This behavior can be overridden
- by using the YcmLocationOpened autocommand. When focus is set to True, the
- location list window becomes the active window. When autoclose is set to True,
- the location list window is automatically closed after an entry is
- selected."""
- vim.command( 'botright lopen' )
- SetFittingHeightForCurrentWindow()
- if autoclose:
-
-
- vim.command( 'au WinLeave <buffer> q' )
- if VariableExists( '#User#YcmLocationOpened' ):
- vim.command( 'doautocmd User YcmLocationOpened' )
- if not focus:
- JumpToPreviousWindow()
- def SetQuickFixList( quickfix_list ):
- """Populate the quickfix list and open it. List should be in qflist format:
- see ":h setqflist" for details."""
- vim.eval( 'setqflist( {0} )'.format( json.dumps( quickfix_list ) ) )
- def OpenQuickFixList( focus = False, autoclose = False ):
- """Open the quickfix list to full width at the bottom of the screen with its
- height automatically set to fit all entries. This behavior can be overridden
- by using the YcmQuickFixOpened autocommand.
- See the OpenLocationList function for the focus and autoclose options."""
- vim.command( 'botright copen' )
- SetFittingHeightForCurrentWindow()
- if autoclose:
-
-
- vim.command( 'au WinLeave <buffer> q' )
- if VariableExists( '#User#YcmQuickFixOpened' ):
- vim.command( 'doautocmd User YcmQuickFixOpened' )
- if not focus:
- JumpToPreviousWindow()
- def SetFittingHeightForCurrentWindow():
- window_width = GetIntValue( 'winwidth( 0 )' )
- fitting_height = 0
- for line in vim.current.buffer:
- fitting_height += len( line ) // window_width + 1
- vim.command( '{0}wincmd _'.format( fitting_height ) )
- def ConvertDiagnosticsToQfList( diagnostics ):
- def ConvertDiagnosticToQfFormat( diagnostic ):
-
-
-
-
-
-
- location = diagnostic[ 'location' ]
- line_num = location[ 'line_num' ]
-
-
- if line_num < 1:
- line_num = 1
- text = diagnostic[ 'text' ]
- if diagnostic.get( 'fixit_available', False ):
- text += ' (FixIt available)'
- return {
- 'bufnr' : GetBufferNumberForFilename( location[ 'filepath' ] ),
- 'lnum' : line_num,
- 'col' : location[ 'column_num' ],
- 'text' : text,
- 'type' : diagnostic[ 'kind' ][ 0 ],
- 'valid' : 1
- }
- return [ ConvertDiagnosticToQfFormat( x ) for x in diagnostics ]
- def GetVimGlobalsKeys():
- return vim.eval( 'keys( g: )' )
- 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 result
- try:
- return int( result )
- except ValueError:
- return ToUnicode( result )
- def HiddenEnabled( buffer_object ):
- if GetBufferOption( buffer_object, 'bh' ) == "hide":
- return True
- return GetBoolValue( '&hidden' )
- def BufferIsUsable( buffer_object ):
- return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object )
- def EscapedFilepath( filepath ):
- return filepath.replace( ' ' , r'\ ' )
- def TryJumpLocationInOpenedTab( filename, line, column ):
- filepath = os.path.realpath( filename )
- for tab in vim.tabpages:
- for win in tab.windows:
- if GetBufferFilepath( win.buffer ) == filepath:
- vim.current.tabpage = tab
- vim.current.window = win
- vim.current.window.cursor = ( line, column - 1 )
-
- vim.command( 'normal! zz' )
- return True
-
- return False
- def GetVimCommand( user_command, default = 'edit' ):
- vim_command = BUFFER_COMMAND_MAP.get( user_command, default )
- if vim_command == 'edit' and not BufferIsUsable( vim.current.buffer ):
- vim_command = 'split'
- return vim_command
- def JumpToLocation( filename, line, column ):
-
- vim.command( "normal! m'" )
- if filename != GetCurrentBufferFilepath():
-
-
-
-
-
-
- user_command = user_options_store.Value( 'goto_buffer_command' )
- if user_command == 'new-or-existing-tab':
- if TryJumpLocationInOpenedTab( filename, line, column ):
- return
- user_command = 'new-tab'
- vim_command = GetVimCommand( user_command )
- try:
- vim.command( 'keepjumps {0} {1}'.format( vim_command,
- EscapedFilepath( filename ) ) )
-
-
-
- except vim.error as e:
- if 'E325' not in str( e ):
- raise
-
- if filename != GetCurrentBufferFilepath():
- return
-
- except KeyboardInterrupt:
- return
- vim.current.window.cursor = ( line, column - 1 )
-
- vim.command( 'normal! zz' )
- def NumLinesInBuffer( buffer_object ):
-
- return len( buffer_object )
- def PostVimMessage( message, warning = True, truncate = False ):
- """Display a message on the Vim status line. By default, the message is
- highlighted and logged to Vim command-line history (see :h history).
- Unset the |warning| parameter to disable this behavior. Set the |truncate|
- parameter to avoid hit-enter prompts (see :h hit-enter) when the message is
- longer than the window width."""
- echo_command = 'echom' if warning else 'echo'
-
-
-
- vim.command( 'redraw' )
- if warning:
- vim.command( 'echohl WarningMsg' )
- message = ToUnicode( message )
- if truncate:
- vim_width = GetIntValue( '&columns' )
- message = message.replace( '\n', ' ' )
- if len( message ) > vim_width:
- message = message[ : vim_width - 4 ] + '...'
- old_ruler = GetIntValue( '&ruler' )
- old_showcmd = GetIntValue( '&showcmd' )
- vim.command( 'set noruler noshowcmd' )
- vim.command( "{0} '{1}'".format( echo_command,
- EscapeForVim( message ) ) )
- SetVariableValue( '&ruler', old_ruler )
- SetVariableValue( '&showcmd', old_showcmd )
- else:
- for line in message.split( '\n' ):
- vim.command( "{0} '{1}'".format( echo_command,
- EscapeForVim( line ) ) )
- if warning:
- vim.command( 'echohl None' )
- def PresentDialog( message, choices, default_choice_index = 0 ):
- """Presents the user with a dialog where a choice can be made.
- This will be a dialog for gvim users or a question in the message buffer
- for vim users or if `set guioptions+=c` was used.
- choices is list of alternatives.
- default_choice_index is the 0-based index of the default element
- that will get choosen if the user hits <CR>. Use -1 for no default.
- PresentDialog will return a 0-based index into the list
- or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc.
- If you are presenting a list of options for the user to choose from, such as
- a list of imports, or lines to insert (etc.), SelectFromList is a better
- option.
- See also:
- :help confirm() in vim (Note that vim uses 1-based indexes)
- Example call:
- PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"])
- Is this a nice example?
- [Y]es, (N)o, May(b)e:"""
- to_eval = "confirm('{0}', '{1}', {2})".format(
- EscapeForVim( ToUnicode( message ) ),
- EscapeForVim( ToUnicode( "\n" .join( choices ) ) ),
- default_choice_index + 1 )
- try:
- return GetIntValue( to_eval ) - 1
- except KeyboardInterrupt:
- return -1
- def Confirm( message ):
- """Display |message| with Ok/Cancel operations. Returns True if the user
- selects Ok"""
- return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 )
- def SelectFromList( prompt, items ):
- """Ask the user to select an item from the list |items|.
- Presents the user with |prompt| followed by a numbered list of |items|,
- from which they select one. The user is asked to enter the number of an
- item or click it.
- |items| should not contain leading ordinals: they are added automatically.
- Returns the 0-based index in the list |items| that the user selected, or a
- negative number if no valid item was selected.
- See also :help inputlist()."""
- vim_items = [ prompt ]
- vim_items.extend( [ "{0}: {1}".format( i + 1, item )
- for i, item in enumerate( items ) ] )
-
-
-
-
-
-
-
- vim.eval( 'inputsave()' )
- try:
-
-
-
-
-
-
-
-
-
-
-
- selected = GetIntValue( "inputlist( " + json.dumps( vim_items ) + " )" ) - 1
- except KeyboardInterrupt:
- selected = -1
- finally:
- vim.eval( 'inputrestore()' )
- if selected < 0 or selected >= len( items ):
-
- raise RuntimeError( NO_SELECTION_MADE_MSG )
- return selected
- def EscapeForVim( text ):
- return ToUnicode( text.replace( "'", "''" ) )
- def CurrentFiletypes():
- return VimExpressionToPythonType( "&filetype" ).split( '.' )
- def GetBufferFiletypes( bufnr ):
- command = 'getbufvar({0}, "&ft")'.format( bufnr )
- return VimExpressionToPythonType( command ).split( '.' )
- def FiletypesForBuffer( buffer_object ):
-
-
- return GetBufferOption( buffer_object, 'ft' ).split( '.' )
- def VariableExists( variable ):
- return GetBoolValue( "exists( '{0}' )".format( EscapeForVim( variable ) ) )
- def SetVariableValue( variable, value ):
- vim.command( "let {0} = {1}".format( variable, json.dumps( value ) ) )
- def GetVariableValue( variable ):
- return vim.eval( variable )
- def GetBoolValue( variable ):
- return bool( int( vim.eval( variable ) ) )
- def GetIntValue( variable ):
- return int( vim.eval( variable ) )
- def _SortChunksByFile( chunks ):
- """Sort the members of the list |chunks| (which must be a list of dictionaries
- conforming to ycmd.responses.FixItChunk) by their filepath. Returns a new
- list in arbitrary order."""
- chunks_by_file = defaultdict( list )
- for chunk in chunks:
- filepath = chunk[ 'range' ][ 'start' ][ 'filepath' ]
- chunks_by_file[ filepath ].append( chunk )
- return chunks_by_file
- def _GetNumNonVisibleFiles( file_list ):
- """Returns the number of file in the iterable list of files |file_list| which
- are not curerntly open in visible windows"""
- return len(
- [ f for f in file_list
- if not BufferIsVisible( GetBufferNumberForFilename( f, False ) ) ] )
- def _OpenFileInSplitIfNeeded( filepath ):
- """Ensure that the supplied filepath is open in a visible window, opening a
- new split if required. Returns the buffer number of the file and an indication
- of whether or not a new split was opened.
- If the supplied filename is already open in a visible window, return just
- return its buffer number. If the supplied file is not visible in a window
- in the current tab, opens it in a new vertical split.
- Returns a tuple of ( buffer_num, split_was_opened ) indicating the buffer
- number and whether or not this method created a new split. If the user opts
- not to open a file, or if opening fails, this method raises RuntimeError,
- otherwise, guarantees to return a visible buffer number in buffer_num."""
- buffer_num = GetBufferNumberForFilename( filepath, False )
-
-
-
-
- if BufferIsVisible( buffer_num ):
-
-
- return ( buffer_num, False )
-
-
-
- OpenFilename( filepath, {
- 'focus': True,
- 'fix': True,
- 'size': GetIntValue( '&previewheight' ),
- } )
-
-
-
- buffer_num = GetBufferNumberForFilename( filepath, False )
- if not BufferIsVisible( buffer_num ):
-
-
-
-
- raise RuntimeError(
- 'Unable to open file: {0}\nFixIt/Refactor operation '
- 'aborted prior to completion. Your files have not been '
- 'fully updated. Please use undo commands to revert the '
- 'applied changes.'.format( filepath ) )
-
- return ( buffer_num, True )
- def ReplaceChunks( chunks ):
- """Apply the source file deltas supplied in |chunks| to arbitrary files.
- |chunks| is a list of changes defined by ycmd.responses.FixItChunk,
- which may apply arbitrary modifications to arbitrary files.
- If a file specified in a particular chunk is not currently open in a visible
- buffer (i.e., one in a window visible in the current tab), we:
- - issue a warning to the user that we're going to open new files (and offer
- her the option to abort cleanly)
- - open the file in a new split, make the changes, then hide the buffer.
- If for some reason a file could not be opened or changed, raises RuntimeError.
- Otherwise, returns no meaningful value."""
-
-
- chunks_by_file = _SortChunksByFile( chunks )
-
- sorted_file_list = sorted( iterkeys( chunks_by_file ) )
-
-
- num_files_to_open = _GetNumNonVisibleFiles( sorted_file_list )
- if num_files_to_open > 0:
- if not Confirm(
- FIXIT_OPENING_BUFFERS_MESSAGE_FORMAT.format( num_files_to_open ) ):
- return
-
-
- locations = []
- for filepath in sorted_file_list:
- ( buffer_num, close_window ) = _OpenFileInSplitIfNeeded( filepath )
- ReplaceChunksInBuffer( chunks_by_file[ filepath ],
- vim.buffers[ buffer_num ],
- locations )
-
-
-
- if close_window:
-
-
-
- vim.command( 'lclose' )
-
-
- vim.command( 'hide' )
-
- if locations:
- SetQuickFixList( locations )
- OpenQuickFixList()
- PostVimMessage( 'Applied {0} changes'.format( len( chunks ) ),
- warning = False )
- def ReplaceChunksInBuffer( chunks, vim_buffer, locations ):
- """Apply changes in |chunks| to the buffer-like object |buffer|. Append each
- chunk's start to the list |locations|"""
-
-
- chunks.sort( key = lambda chunk: (
- chunk[ 'range' ][ 'start' ][ 'line_num' ],
- chunk[ 'range' ][ 'start' ][ 'column_num' ]
- ) )
-
-
-
- last_line = -1
- line_delta = 0
- for chunk in chunks:
- if chunk[ 'range' ][ 'start' ][ 'line_num' ] != last_line:
-
-
- last_line = chunk[ 'range' ][ 'end' ][ 'line_num' ]
- char_delta = 0
- ( new_line_delta, new_char_delta ) = ReplaceChunk(
- chunk[ 'range' ][ 'start' ],
- chunk[ 'range' ][ 'end' ],
- chunk[ 'replacement_text' ],
- line_delta, char_delta,
- vim_buffer,
- locations )
- line_delta += new_line_delta
- char_delta += new_char_delta
- def ReplaceChunk( start, end, replacement_text, line_delta, char_delta,
- vim_buffer, locations = None ):
-
-
- start_line = start[ 'line_num' ] - 1 + line_delta
- end_line = end[ 'line_num' ] - 1 + line_delta
- source_lines_count = end_line - start_line + 1
- start_column = start[ 'column_num' ] - 1 + char_delta
- end_column = end[ 'column_num' ] - 1
- if source_lines_count == 1:
- end_column += char_delta
-
-
- replacement_lines = ToBytes( replacement_text ).splitlines( False )
- if not replacement_lines:
- replacement_lines = [ bytes( b'' ) ]
- replacement_lines_count = len( replacement_lines )
-
-
- end_existing_text = ToBytes( vim_buffer[ end_line ] )[ end_column : ]
- start_existing_text = ToBytes( vim_buffer[ start_line ] )[ : start_column ]
- new_char_delta = ( len( replacement_lines[ -1 ] )
- - ( end_column - start_column ) )
- if replacement_lines_count > 1:
- new_char_delta -= start_column
- replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ]
- replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text
- vim_buffer[ start_line : end_line + 1 ] = replacement_lines[:]
- if locations is not None:
- locations.append( {
- 'bufnr': vim_buffer.number,
- 'filename': vim_buffer.name,
-
- 'lnum': start_line + 1,
- 'col': start_column + 1,
- 'text': replacement_text,
- 'type': 'F',
- } )
- new_line_delta = replacement_lines_count - source_lines_count
- return ( new_line_delta, new_char_delta )
- def InsertNamespace( namespace ):
- if VariableExists( 'g:ycm_csharp_insert_namespace_expr' ):
- expr = GetVariableValue( 'g:ycm_csharp_insert_namespace_expr' )
- if expr:
- SetVariableValue( "g:ycm_namespace_to_insert", namespace )
- vim.eval( expr )
- return
- pattern = '^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*'
- existing_indent = ''
- line = SearchInCurrentBuffer( pattern )
- if line:
- existing_line = LineTextInCurrentBuffer( line )
- existing_indent = re.sub( r"\S.*", "", existing_line )
- new_line = "{0}using {1};\n\n".format( existing_indent, namespace )
- replace_pos = { 'line_num': line + 1, 'column_num': 1 }
- ReplaceChunk( replace_pos, replace_pos, new_line, 0, 0, vim.current.buffer )
- PostVimMessage( 'Add namespace: {0}'.format( namespace ), warning = False )
- def SearchInCurrentBuffer( pattern ):
- """ Returns the 1-indexed line on which the pattern matches
- (going UP from the current position) or 0 if not found """
- return GetIntValue( "search('{0}', 'Wcnb')".format( EscapeForVim( pattern )))
- def LineTextInCurrentBuffer( line_number ):
- """ Returns the text on the 1-indexed line (NOT 0-indexed) """
- return vim.current.buffer[ line_number - 1 ]
- def ClosePreviewWindow():
- """ Close the preview window if it is present, otherwise do nothing """
- vim.command( 'silent! pclose!' )
- def JumpToPreviewWindow():
- """ Jump the vim cursor to the preview window, which must be active. Returns
- boolean indicating if the cursor ended up in the preview window """
- vim.command( 'silent! wincmd P' )
- return vim.current.window.options[ 'previewwindow' ]
- def JumpToPreviousWindow():
- """ Jump the vim cursor to its previous window position """
- vim.command( 'silent! wincmd p' )
- def JumpToTab( tab_number ):
- """Jump to Vim tab with corresponding number """
- vim.command( 'silent! tabn {0}'.format( tab_number ) )
- def OpenFileInPreviewWindow( filename ):
- """ Open the supplied filename in the preview window """
- vim.command( 'silent! pedit! ' + filename )
- def WriteToPreviewWindow( message ):
- """ Display the supplied message in the preview window """
-
-
-
-
-
-
- ClosePreviewWindow()
- OpenFileInPreviewWindow( vim.eval( 'tempname()' ) )
- if JumpToPreviewWindow():
-
-
-
- vim.current.buffer.options[ 'modifiable' ] = True
- vim.current.buffer.options[ 'readonly' ] = False
- vim.current.buffer[:] = message.splitlines()
- vim.current.buffer.options[ 'buftype' ] = 'nofile'
- vim.current.buffer.options[ 'bufhidden' ] = 'wipe'
- vim.current.buffer.options[ 'buflisted' ] = False
- vim.current.buffer.options[ 'swapfile' ] = False
- vim.current.buffer.options[ 'modifiable' ] = False
- vim.current.buffer.options[ 'readonly' ] = True
-
-
- vim.current.buffer.options[ 'modified' ] = False
- JumpToPreviousWindow()
- else:
-
-
-
- PostVimMessage( message, warning = False )
- def BufferIsVisibleForFilename( filename ):
- """Check if a buffer exists for a specific file."""
- buffer_number = GetBufferNumberForFilename( filename, False )
- return BufferIsVisible( buffer_number )
- def CloseBuffersForFilename( filename ):
- """Close all buffers for a specific file."""
- buffer_number = GetBufferNumberForFilename( filename, False )
- while buffer_number != -1:
- vim.command( 'silent! bwipeout! {0}'.format( buffer_number ) )
- new_buffer_number = GetBufferNumberForFilename( filename, False )
- if buffer_number == new_buffer_number:
- raise RuntimeError( "Buffer {0} for filename '{1}' should already be "
- "wiped out.".format( buffer_number, filename ) )
- buffer_number = new_buffer_number
- def OpenFilename( filename, options = {} ):
- """Open a file in Vim. Following options are available:
- - command: specify which Vim command is used to open the file. Choices
- are same-buffer, horizontal-split, vertical-split, and new-tab (default:
- horizontal-split);
- - size: set the height of the window for a horizontal split or the width for
- a vertical one (default: '');
- - fix: set the winfixheight option for a horizontal split or winfixwidth for
- a vertical one (default: False). See :h winfix for details;
- - focus: focus the opened file (default: False);
- - watch: automatically watch for changes (default: False). This is useful
- for logs;
- - position: set the position where the file is opened (default: start).
- Choices are start and end."""
-
- command = GetVimCommand( options.get( 'command', 'horizontal-split' ),
- 'horizontal-split' )
- size = ( options.get( 'size', '' ) if command in [ 'split', 'vsplit' ] else
- '' )
- focus = options.get( 'focus', False )
-
-
- if not focus and command == 'tabedit':
- previous_tab = GetIntValue( 'tabpagenr()' )
- else:
- previous_tab = None
-
- try:
- vim.command( '{0}{1} {2}'.format( size, command, filename ) )
-
-
-
-
- except vim.error as e:
- if 'E325' not in str( e ):
- raise
-
-
- if filename != GetCurrentBufferFilepath():
- return
- except KeyboardInterrupt:
-
- return
- _SetUpLoadedBuffer( command,
- filename,
- options.get( 'fix', False ),
- options.get( 'position', 'start' ),
- options.get( 'watch', False ) )
-
-
-
- if not focus:
- if command == 'tabedit':
- JumpToTab( previous_tab )
- if command in [ 'split', 'vsplit' ]:
- JumpToPreviousWindow()
- def _SetUpLoadedBuffer( command, filename, fix, position, watch ):
- """After opening a buffer, configure it according to the supplied options,
- which are as defined by the OpenFilename method."""
- if command == 'split':
- vim.current.window.options[ 'winfixheight' ] = fix
- if command == 'vsplit':
- vim.current.window.options[ 'winfixwidth' ] = fix
- if watch:
- vim.current.buffer.options[ 'autoread' ] = True
- vim.command( "exec 'au BufEnter <buffer> :silent! checktime {0}'"
- .format( filename ) )
- if position == 'end':
- vim.command( 'silent! normal! Gzz' )
|