@@ -292,13 +292,19 @@ public override void FormatLines(ITextEditor textArea)
292292 /// <returns><c>True</c>, if code has been formatted, <c>false</c> if auto-formatting is currently forbidden.</returns>
293293 private bool FormatCode ( ITextEditor textArea , int offset , int length , bool respectAutoFormattingSetting )
294294 {
295+ if ( ( offset > textArea . Document . TextLength ) || ( ( offset + length ) > textArea . Document . TextLength ) )
296+ return false ;
295297 if ( respectAutoFormattingSetting && ! CSharpFormattingOptionsPersistence . AutoFormatting )
296298 return false ;
297299
298300 using ( textArea . Document . OpenUndoGroup ( ) ) {
299- // In any other case: Simply format selection or whole document
300301 var formattingOptions = CSharpFormattingOptionsPersistence . GetProjectOptions ( SD . ProjectService . CurrentProject ) ;
301- CSharpFormatterHelper . Format ( textArea , offset , length , formattingOptions . OptionsContainer ) ;
302+ try {
303+ CSharpFormatterHelper . Format ( textArea , offset , length , formattingOptions . OptionsContainer ) ;
304+ } catch ( Exception ) {
305+ // Exceptions in formatting might happen if code contains syntax errors, we have to catch them
306+ return false ;
307+ }
302308 return true ;
303309 }
304310 }
@@ -313,8 +319,8 @@ private bool FormatCode(ITextEditor textArea, int offset, int length, bool respe
313319 bool FormatStatement ( ITextEditor textArea , int cursorOffset , int formattingStartOffset )
314320 {
315321 var line = textArea . Document . GetLineByOffset ( formattingStartOffset ) ;
316- int lineOffset = cursorOffset ;
317- // Walk up the lines until we arrive at previous statement or block
322+ int lineOffset = line . Offset ;
323+ // Walk up the lines until we arrive at previous statement, block, comment or preprocessor directive
318324 while ( line . PreviousLine != null ) {
319325 line = line . PreviousLine ;
320326 string lineText = textArea . Document . GetText ( line . Offset , line . Length ) ;
@@ -522,11 +528,15 @@ bool IsLineEndOfStatement(string lineText)
522528 int indexOfMultiLineCommentStart = normalizedLine . LastIndexOf ( "/*" ) ;
523529 if ( indexOfMultiLineCommentStart > - 1 ) {
524530 normalizedLine = normalizedLine . Substring ( 0 , indexOfMultiLineCommentStart ) ;
531+ } else {
532+ // Seems to be a multiline comment (no comment start on this line)
533+ return true ;
525534 }
526535 }
527536
528537 // Usual statement endings
529- if ( normalizedLine . EndsWith ( ";" )
538+ if ( normalizedLine . StartsWith ( "#" )
539+ || normalizedLine . EndsWith ( ";" )
530540 || normalizedLine . EndsWith ( "{" )
531541 || normalizedLine . EndsWith ( "}" ) )
532542 return true ;
0 commit comments