diagnostic_interface.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. # Vim doesn't provide a way to update the matches for a different window
  99. # than the current one (which is a view of the current buffer).
  100. if vimsupport.GetCurrentBufferNumber() != self._bufnr:
  101. return
  102. matches_to_remove = vimsupport.GetDiagnosticMatchesInCurrentWindow()
  103. for diags in itervalues( self._line_to_diags ):
  104. # Insert squiggles in reverse order so that errors overlap warnings.
  105. for diag in reversed( diags ):
  106. group = ( 'YcmErrorSection' if _DiagnosticIsError( diag ) else
  107. 'YcmWarningSection' )
  108. for pattern in _ConvertDiagnosticToMatchPatterns( diag ):
  109. # The id doesn't matter for matches that we may add.
  110. match = vimsupport.DiagnosticMatch( 0, group, pattern )
  111. try:
  112. matches_to_remove.remove( match )
  113. except ValueError:
  114. vimsupport.AddDiagnosticMatch( match )
  115. for match in matches_to_remove:
  116. vimsupport.RemoveDiagnosticMatch( match )
  117. def _UpdateSigns( self ):
  118. signs_to_unplace = vimsupport.GetSignsInBuffer( self._bufnr )
  119. for line, diags in iteritems( self._line_to_diags ):
  120. if not diags:
  121. continue
  122. # We always go for the first diagnostic on the line because diagnostics
  123. # are sorted by errors in priority and Vim can only display one sign by
  124. # line.
  125. name = 'YcmError' if _DiagnosticIsError( diags[ 0 ] ) else 'YcmWarning'
  126. sign = vimsupport.CreateSign( line, name, self._bufnr )
  127. try:
  128. signs_to_unplace.remove( sign )
  129. except ValueError:
  130. vimsupport.PlaceSign( sign )
  131. for sign in signs_to_unplace:
  132. vimsupport.UnplaceSign( sign )
  133. def _ConvertDiagListToDict( self ):
  134. self._line_to_diags = defaultdict( list )
  135. for diag in self._diagnostics:
  136. location = diag[ 'location' ]
  137. bufnr = vimsupport.GetBufferNumberForFilename( location[ 'filepath' ] )
  138. if bufnr == self._bufnr:
  139. line_number = location[ 'line_num' ]
  140. self._line_to_diags[ line_number ].append( diag )
  141. for diags in itervalues( self._line_to_diags ):
  142. # We also want errors to be listed before warnings so that errors aren't
  143. # hidden by the warnings; Vim won't place a sign over an existing one.
  144. diags.sort( key = lambda diag: ( diag[ 'kind' ],
  145. diag[ 'location' ][ 'column_num' ] ) )
  146. _DiagnosticIsError = CompileLevel( 'error' )
  147. _DiagnosticIsWarning = CompileLevel( 'warning' )
  148. def _NormalizeDiagnostic( diag ):
  149. def ClampToOne( value ):
  150. return value if value > 0 else 1
  151. location = diag[ 'location' ]
  152. location[ 'column_num' ] = ClampToOne( location[ 'column_num' ] )
  153. location[ 'line_num' ] = ClampToOne( location[ 'line_num' ] )
  154. return diag
  155. def _ConvertDiagnosticToMatchPatterns( diagnostic ):
  156. patterns = []
  157. location_extent = diagnostic[ 'location_extent' ]
  158. if location_extent[ 'start' ][ 'line_num' ] <= 0:
  159. location = diagnostic[ 'location' ]
  160. patterns.append( vimsupport.GetDiagnosticMatchPattern(
  161. location[ 'line_num' ],
  162. location[ 'column_num' ] ) )
  163. else:
  164. patterns.append( vimsupport.GetDiagnosticMatchPattern(
  165. location_extent[ 'start' ][ 'line_num' ],
  166. location_extent[ 'start' ][ 'column_num' ],
  167. location_extent[ 'end' ][ 'line_num' ],
  168. location_extent[ 'end' ][ 'column_num' ] ) )
  169. for diagnostic_range in diagnostic[ 'ranges' ]:
  170. patterns.append( vimsupport.GetDiagnosticMatchPattern(
  171. diagnostic_range[ 'start' ][ 'line_num' ],
  172. diagnostic_range[ 'start' ][ 'column_num' ],
  173. diagnostic_range[ 'end' ][ 'line_num' ],
  174. diagnostic_range[ 'end' ][ 'column_num' ] ) )
  175. return patterns