diagnostic_interface.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 collections import defaultdict
  18. from ycm import vimsupport
  19. from ycm.diagnostic_filter import DiagnosticFilter, CompileLevel
  20. from ycm import text_properties as tp
  21. import vim
  22. YCM_VIM_PROPERTY_ID = 0
  23. class DiagnosticInterface:
  24. def __init__( self, bufnr, user_options ):
  25. self._bufnr = bufnr
  26. self._user_options = user_options
  27. self._diagnostics = []
  28. self._diag_filter = DiagnosticFilter.CreateFromOptions( user_options )
  29. # Line and column numbers are 1-based
  30. self._line_to_diags = defaultdict( list )
  31. self._previous_diag_line_number = -1
  32. self._diag_message_needs_clearing = False
  33. def OnCursorMoved( self ):
  34. if self._user_options[ 'echo_current_diagnostic' ]:
  35. line, _ = vimsupport.CurrentLineAndColumn()
  36. line += 1 # Convert to 1-based
  37. if line != self._previous_diag_line_number:
  38. self._EchoDiagnosticForLine( line )
  39. def GetErrorCount( self ):
  40. return self._DiagnosticsCount( _DiagnosticIsError )
  41. def GetWarningCount( self ):
  42. return self._DiagnosticsCount( _DiagnosticIsWarning )
  43. def PopulateLocationList( self, open_on_edit = False ):
  44. # Do nothing if loc list is already populated by diag_interface
  45. if not self._user_options[ 'always_populate_location_list' ]:
  46. self._UpdateLocationLists( open_on_edit )
  47. return bool( self._diagnostics )
  48. def UpdateWithNewDiagnostics( self, diags, open_on_edit = False ):
  49. self._diagnostics = [ _NormalizeDiagnostic( x ) for x in
  50. self._ApplyDiagnosticFilter( diags ) ]
  51. self._ConvertDiagListToDict()
  52. if ( self._user_options[ 'update_diagnostics_in_insert_mode' ] or
  53. 'i' not in vim.eval( 'mode()' ) ):
  54. self.RefreshDiagnosticsUI( open_on_edit )
  55. def RefreshDiagnosticsUI( self, open_on_edit = False ):
  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( open_on_edit )
  63. def DiagnosticsForLine( self, line_number ):
  64. return self._line_to_diags[ line_number ]
  65. def _ApplyDiagnosticFilter( self, diags ):
  66. filetypes = vimsupport.GetBufferFiletypes( self._bufnr )
  67. diag_filter = self._diag_filter.SubsetForTypes( filetypes )
  68. return filter( diag_filter.IsAllowed, diags )
  69. def _EchoDiagnostic( self ):
  70. line, _ = vimsupport.CurrentLineAndColumn()
  71. line += 1 # Convert to 1-based
  72. self._EchoDiagnosticForLine( line )
  73. def _EchoDiagnosticForLine( self, line_num ):
  74. self._previous_diag_line_number = line_num
  75. diags = self._line_to_diags[ line_num ]
  76. text = None
  77. if diags:
  78. first_diag = diags[ 0 ]
  79. text = first_diag[ 'text' ]
  80. if first_diag.get( 'fixit_available', False ):
  81. text += ' (FixIt)'
  82. if self._user_options[ 'echo_current_diagnostic' ] == 'virtual-text':
  83. if self._diag_message_needs_clearing:
  84. # Clear any previous diag echo
  85. tp.ClearTextProperties( self._bufnr, type = 'YcmVirtError' )
  86. tp.ClearTextProperties( self._bufnr, type = 'YcmVirtWarning' )
  87. self._diag_message_needs_clearing = False
  88. if not text:
  89. return
  90. def MakeVritualTextProperty( prop_type, text, position='after' ):
  91. vimsupport.AddTextProperty( self._bufnr,
  92. line_num,
  93. 0,
  94. prop_type,
  95. {
  96. 'text': text,
  97. 'text_align': position,
  98. 'text_wrap': 'wrap'
  99. } )
  100. MakeVritualTextProperty(
  101. 'YcmPadding',
  102. ' ' * vim.buffers[ self._bufnr ].options[ 'shiftwidth' ] ),
  103. MakeVritualTextProperty(
  104. 'YcmVirtError' if _DiagnosticIsError( first_diag )
  105. else 'YcmVirtWarning',
  106. [ line for line in text.splitlines() if line ][ 0 ] )
  107. else:
  108. if not text:
  109. if self._diag_message_needs_clearing:
  110. # Clear any previous diag echo
  111. vimsupport.PostVimMessage( '', warning = False )
  112. self._diag_message_needs_clearing = False
  113. return
  114. vimsupport.PostVimMessage( text, warning = False, truncate = True )
  115. self._diag_message_needs_clearing = True
  116. def _DiagnosticsCount( self, predicate ):
  117. count = 0
  118. for diags in self._line_to_diags.values():
  119. count += sum( 1 for d in diags if predicate( d ) )
  120. return count
  121. def _UpdateLocationLists( self, open_on_edit = False ):
  122. vimsupport.SetLocationListsForBuffer(
  123. self._bufnr,
  124. vimsupport.ConvertDiagnosticsToQfList( self._diagnostics ),
  125. open_on_edit )
  126. def UpdateMatches( self ):
  127. if not self._user_options[ 'enable_diagnostic_highlighting' ]:
  128. return
  129. props_to_remove = vimsupport.GetTextProperties( self._bufnr )
  130. for diags in self._line_to_diags.values():
  131. # Insert squiggles in reverse order so that errors overlap warnings.
  132. for diag in reversed( diags ):
  133. for line, column, name, extras in _ConvertDiagnosticToTextProperties(
  134. self._bufnr,
  135. diag ):
  136. global YCM_VIM_PROPERTY_ID
  137. # Note the following .remove() works because the __eq__ on
  138. # DiagnosticProperty does not actually check the IDs match...
  139. diag_prop = vimsupport.DiagnosticProperty(
  140. YCM_VIM_PROPERTY_ID,
  141. name,
  142. line,
  143. column,
  144. extras[ 'end_col' ] - column if 'end_col' in extras else column )
  145. try:
  146. props_to_remove.remove( diag_prop )
  147. except ValueError:
  148. extras.update( {
  149. 'id': YCM_VIM_PROPERTY_ID
  150. } )
  151. vimsupport.AddTextProperty( self._bufnr,
  152. line,
  153. column,
  154. name,
  155. extras )
  156. YCM_VIM_PROPERTY_ID += 1
  157. for prop in props_to_remove:
  158. vimsupport.RemoveDiagnosticProperty( self._bufnr, prop )
  159. def _UpdateSigns( self ):
  160. signs_to_unplace = vimsupport.GetSignsInBuffer( self._bufnr )
  161. signs_to_place = []
  162. for line, diags in self._line_to_diags.items():
  163. if not diags:
  164. continue
  165. # We always go for the first diagnostic on the line because diagnostics
  166. # are sorted by errors in priority and Vim can only display one sign by
  167. # line.
  168. name = 'YcmError' if _DiagnosticIsError( diags[ 0 ] ) else 'YcmWarning'
  169. sign = {
  170. 'lnum': line,
  171. 'name': name,
  172. 'buffer': self._bufnr,
  173. 'group': 'ycm_signs'
  174. }
  175. try:
  176. signs_to_unplace.remove( sign )
  177. except ValueError:
  178. signs_to_place.append( sign )
  179. vim.eval( f'sign_placelist( { signs_to_place } )' )
  180. vim.eval( f'sign_unplacelist( { signs_to_unplace } )' )
  181. def _ConvertDiagListToDict( self ):
  182. self._line_to_diags = defaultdict( list )
  183. for diag in self._diagnostics:
  184. location = diag[ 'location' ]
  185. bufnr = vimsupport.GetBufferNumberForFilename( location[ 'filepath' ] )
  186. if bufnr == self._bufnr:
  187. line_number = location[ 'line_num' ]
  188. self._line_to_diags[ line_number ].append( diag )
  189. for diags in self._line_to_diags.values():
  190. # We also want errors to be listed before warnings so that errors aren't
  191. # hidden by the warnings; Vim won't place a sign over an existing one.
  192. diags.sort( key = lambda diag: ( diag[ 'kind' ],
  193. diag[ 'location' ][ 'column_num' ] ) )
  194. _DiagnosticIsError = CompileLevel( 'error' )
  195. _DiagnosticIsWarning = CompileLevel( 'warning' )
  196. def _NormalizeDiagnostic( diag ):
  197. def ClampToOne( value ):
  198. return value if value > 0 else 1
  199. location = diag[ 'location' ]
  200. location[ 'column_num' ] = ClampToOne( location[ 'column_num' ] )
  201. location[ 'line_num' ] = ClampToOne( location[ 'line_num' ] )
  202. return diag
  203. def _ConvertDiagnosticToTextProperties( bufnr, diagnostic ):
  204. properties = []
  205. name = ( 'YcmErrorProperty' if _DiagnosticIsError( diagnostic ) else
  206. 'YcmWarningProperty' )
  207. if vimsupport.VimIsNeovim():
  208. name = name.replace( 'Property', 'Section' )
  209. location_extent = diagnostic[ 'location_extent' ]
  210. if location_extent[ 'start' ][ 'line_num' ] <= 0:
  211. location = diagnostic[ 'location' ]
  212. line, column = vimsupport.LineAndColumnNumbersClamped(
  213. bufnr,
  214. location[ 'line_num' ],
  215. location[ 'column_num' ]
  216. )
  217. properties.append( ( line, column, name, {} ) )
  218. else:
  219. start_line, start_column = vimsupport.LineAndColumnNumbersClamped(
  220. bufnr,
  221. location_extent[ 'start' ][ 'line_num' ],
  222. location_extent[ 'start' ][ 'column_num' ]
  223. )
  224. end_line, end_column = vimsupport.LineAndColumnNumbersClamped(
  225. bufnr,
  226. location_extent[ 'end' ][ 'line_num' ],
  227. location_extent[ 'end' ][ 'column_num' ]
  228. )
  229. properties.append( (
  230. start_line,
  231. start_column,
  232. name,
  233. { 'end_lnum': end_line,
  234. 'end_col': end_column } ) )
  235. for diagnostic_range in diagnostic[ 'ranges' ]:
  236. start_line, start_column = vimsupport.LineAndColumnNumbersClamped(
  237. bufnr,
  238. diagnostic_range[ 'start' ][ 'line_num' ],
  239. diagnostic_range[ 'start' ][ 'column_num' ]
  240. )
  241. end_line, end_column = vimsupport.LineAndColumnNumbersClamped(
  242. bufnr,
  243. diagnostic_range[ 'end' ][ 'line_num' ],
  244. diagnostic_range[ 'end' ][ 'column_num' ]
  245. )
  246. if not _IsValidRange( start_line, start_column, end_line, end_column ):
  247. continue
  248. properties.append( (
  249. start_line,
  250. start_column,
  251. name,
  252. { 'end_lnum': end_line,
  253. 'end_col': end_column } ) )
  254. return properties
  255. def _IsValidRange( start_line, start_column, end_line, end_column ):
  256. # End line before start line - invalid
  257. if start_line > end_line:
  258. return False
  259. # End line after start line - valid
  260. if start_line < end_line:
  261. return True
  262. # Same line, start colum after end column - invalid
  263. if start_column > end_column:
  264. return False
  265. # Same line, start column before or equal to end column - valid
  266. return True