diagnostic_interface.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. # Copyright (C) 2013-2018 YouCompleteMe contributors
  2. #
  3. # This file is part of YouCompleteMe.
  4. #
  5. # YouCompleteMe is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # YouCompleteMe is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  17. from __future__ import unicode_literals
  18. from __future__ import print_function
  19. from __future__ import division
  20. from __future__ import absolute_import
  21. # Not installing aliases from python-future; it's unreliable and slow.
  22. from builtins import * # noqa
  23. from future.utils import itervalues, iteritems
  24. from collections import defaultdict
  25. from ycm import vimsupport
  26. from ycm.diagnostic_filter import DiagnosticFilter, CompileLevel
  27. class DiagnosticInterface( object ):
  28. def __init__( self, bufnr, user_options ):
  29. self._bufnr = bufnr
  30. self._user_options = user_options
  31. self._diagnostics = []
  32. self._diag_filter = DiagnosticFilter.CreateFromOptions( user_options )
  33. # Line and column numbers are 1-based
  34. self._line_to_diags = defaultdict( list )
  35. self._previous_diag_line_number = -1
  36. self._diag_message_needs_clearing = False
  37. def OnCursorMoved( self ):
  38. if self._user_options[ 'echo_current_diagnostic' ]:
  39. line, _ = vimsupport.CurrentLineAndColumn()
  40. line += 1 # Convert to 1-based
  41. if line != self._previous_diag_line_number:
  42. self._EchoDiagnosticForLine( line )
  43. def GetErrorCount( self ):
  44. return self._DiagnosticsCount( _DiagnosticIsError )
  45. def GetWarningCount( self ):
  46. return self._DiagnosticsCount( _DiagnosticIsWarning )
  47. def PopulateLocationList( self ):
  48. # Do nothing if loc list is already populated by diag_interface
  49. if not self._user_options[ 'always_populate_location_list' ]:
  50. self._UpdateLocationLists()
  51. return bool( self._diagnostics )
  52. def UpdateWithNewDiagnostics( self, diags ):
  53. self._diagnostics = [ _NormalizeDiagnostic( x ) for x in
  54. self._ApplyDiagnosticFilter( diags ) ]
  55. self._ConvertDiagListToDict()
  56. if self._user_options[ 'echo_current_diagnostic' ]:
  57. self._EchoDiagnostic()
  58. if self._user_options[ 'enable_diagnostic_signs' ]:
  59. self._UpdateSigns()
  60. self.UpdateMatches()
  61. if self._user_options[ 'always_populate_location_list' ]:
  62. self._UpdateLocationLists()
  63. def _ApplyDiagnosticFilter( self, diags ):
  64. filetypes = vimsupport.GetBufferFiletypes( self._bufnr )
  65. diag_filter = self._diag_filter.SubsetForTypes( filetypes )
  66. return filter( diag_filter.IsAllowed, diags )
  67. def _EchoDiagnostic( self ):
  68. line, _ = vimsupport.CurrentLineAndColumn()
  69. line += 1 # Convert to 1-based
  70. self._EchoDiagnosticForLine( line )
  71. def _EchoDiagnosticForLine( self, line_num ):
  72. self._previous_diag_line_number = line_num
  73. diags = self._line_to_diags[ line_num ]
  74. if not diags:
  75. if self._diag_message_needs_clearing:
  76. # Clear any previous diag echo
  77. vimsupport.PostVimMessage( '', warning = False )
  78. self._diag_message_needs_clearing = False
  79. return
  80. first_diag = diags[ 0 ]
  81. text = first_diag[ 'text' ]
  82. if first_diag.get( 'fixit_available', False ):
  83. text += ' (FixIt)'
  84. vimsupport.PostVimMessage( text, warning = False, truncate = True )
  85. self._diag_message_needs_clearing = True
  86. def _DiagnosticsCount( self, predicate ):
  87. count = 0
  88. for diags in itervalues( self._line_to_diags ):
  89. count += sum( 1 for d in diags if predicate( d ) )
  90. return count
  91. def _UpdateLocationLists( self ):
  92. vimsupport.SetLocationListsForBuffer(
  93. self._bufnr,
  94. vimsupport.ConvertDiagnosticsToQfList( self._diagnostics ) )
  95. def UpdateMatches( self ):
  96. if not self._user_options[ 'enable_diagnostic_highlighting' ]:
  97. return
  98. with vimsupport.CurrentWindow():
  99. for window in vimsupport.GetWindowsForBufferNumber( self._bufnr ):
  100. vimsupport.SwitchWindow( window )
  101. matches_to_remove = vimsupport.GetDiagnosticMatchesInCurrentWindow()
  102. for diags in itervalues( self._line_to_diags ):
  103. # Insert squiggles in reverse order so that errors overlap warnings.
  104. for diag in reversed( diags ):
  105. group = ( 'YcmErrorSection' if _DiagnosticIsError( diag ) else
  106. 'YcmWarningSection' )
  107. for pattern in _ConvertDiagnosticToMatchPatterns( diag ):
  108. # The id doesn't matter for matches that we may add.
  109. match = vimsupport.DiagnosticMatch( 0, group, pattern )
  110. try:
  111. matches_to_remove.remove( match )
  112. except ValueError:
  113. vimsupport.AddDiagnosticMatch( match )
  114. for match in matches_to_remove:
  115. vimsupport.RemoveDiagnosticMatch( match )
  116. def _UpdateSigns( self ):
  117. signs_to_unplace = vimsupport.GetSignsInBuffer( self._bufnr )
  118. for line, diags in iteritems( self._line_to_diags ):
  119. if not diags:
  120. continue
  121. # We always go for the first diagnostic on the line because diagnostics
  122. # are sorted by errors in priority and Vim can only display one sign by
  123. # line.
  124. name = 'YcmError' if _DiagnosticIsError( diags[ 0 ] ) else 'YcmWarning'
  125. sign = vimsupport.CreateSign( line, name, self._bufnr )
  126. try:
  127. signs_to_unplace.remove( sign )
  128. except ValueError:
  129. vimsupport.PlaceSign( sign )
  130. for sign in signs_to_unplace:
  131. vimsupport.UnplaceSign( sign )
  132. def _ConvertDiagListToDict( self ):
  133. self._line_to_diags = defaultdict( list )
  134. for diag in self._diagnostics:
  135. location = diag[ 'location' ]
  136. bufnr = vimsupport.GetBufferNumberForFilename( location[ 'filepath' ] )
  137. if bufnr == self._bufnr:
  138. line_number = location[ 'line_num' ]
  139. self._line_to_diags[ line_number ].append( diag )
  140. for diags in itervalues( self._line_to_diags ):
  141. # We also want errors to be listed before warnings so that errors aren't
  142. # hidden by the warnings; Vim won't place a sign over an existing one.
  143. diags.sort( key = lambda diag: ( diag[ 'kind' ],
  144. diag[ 'location' ][ 'column_num' ] ) )
  145. _DiagnosticIsError = CompileLevel( 'error' )
  146. _DiagnosticIsWarning = CompileLevel( 'warning' )
  147. def _NormalizeDiagnostic( diag ):
  148. def ClampToOne( value ):
  149. return value if value > 0 else 1
  150. location = diag[ 'location' ]
  151. location[ 'column_num' ] = ClampToOne( location[ 'column_num' ] )
  152. location[ 'line_num' ] = ClampToOne( location[ 'line_num' ] )
  153. return diag
  154. def _ConvertDiagnosticToMatchPatterns( diagnostic ):
  155. patterns = []
  156. location_extent = diagnostic[ 'location_extent' ]
  157. if location_extent[ 'start' ][ 'line_num' ] <= 0:
  158. location = diagnostic[ 'location' ]
  159. patterns.append( vimsupport.GetDiagnosticMatchPattern(
  160. location[ 'line_num' ],
  161. location[ 'column_num' ] ) )
  162. else:
  163. patterns.append( vimsupport.GetDiagnosticMatchPattern(
  164. location_extent[ 'start' ][ 'line_num' ],
  165. location_extent[ 'start' ][ 'column_num' ],
  166. location_extent[ 'end' ][ 'line_num' ],
  167. location_extent[ 'end' ][ 'column_num' ] ) )
  168. for diagnostic_range in diagnostic[ 'ranges' ]:
  169. patterns.append( vimsupport.GetDiagnosticMatchPattern(
  170. diagnostic_range[ 'start' ][ 'line_num' ],
  171. diagnostic_range[ 'start' ][ 'column_num' ],
  172. diagnostic_range[ 'end' ][ 'line_num' ],
  173. diagnostic_range[ 'end' ][ 'column_num' ] ) )
  174. return patterns