Skip to content

Commit e8af086

Browse files
committed
Merge pull request hilkoc#12 from tommy9/master
Fix false positive with isOneLineIfStatemt
2 parents 5d3c87a + 0116e25 commit e8af086

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

src/vbaDeveloper.xlam/Formatter.bas

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,13 @@ Private Const INDENT = " "
6969
Private words As Dictionary 'Keys are Strings, Value is an Integer indicating change in indentation
7070
Private indentation(0 To 20) As Variant ' Prevent repeatedly building the same strings by looking them up in here
7171

72+
' 3-state data type for checking if part of code is within a string or not
73+
Private Enum StringStatus
74+
InString
75+
MaybeInString
76+
NotInString
77+
End Enum
78+
7279
Private Sub initialize()
7380
initializeWords
7481
initializeIndentation
@@ -308,5 +315,46 @@ End Function
308315

309316

310317
Private Function isOneLineIfStatemt(line As String) As Boolean
311-
isOneLineIfStatemt = (lineStartsWith(BEG_IF, line) And (Not lineEndsWith(THEN_KEYWORD, line)) And Not lineEndsWith(LINE_CONTINUATION, line))
318+
Dim trimmedLine As String
319+
trimmedLine = TrimComments(line)
320+
isOneLineIfStatemt = (lineStartsWith(BEG_IF, trimmedLine) And (Not lineEndsWith(THEN_KEYWORD, trimmedLine)) And Not lineEndsWith(LINE_CONTINUATION, trimmedLine))
321+
End Function
322+
323+
324+
' Trims trailing comments (and whitespace before a comment) from a line of code
325+
Private Function TrimComments(ByVal line As String) As String
326+
Dim c As Long
327+
Dim inQuotes As StringStatus
328+
Dim inComment As Boolean
329+
330+
inQuotes = NotInString
331+
inComment = False
332+
For c = 1 To Len(line)
333+
If Mid(line, c, 1) = Chr(34) Then
334+
' Found a double quote
335+
Select Case inQuotes
336+
Case NotInString:
337+
inQuotes = InString
338+
Case InString:
339+
inQuotes = MaybeInString
340+
Case MaybeInString:
341+
inQuotes = InString
342+
End Select
343+
Else
344+
' Resolve uncertain string status
345+
If inQuotes = MaybeInString Then
346+
inQuotes = NotInString
347+
End If
348+
End If
349+
' Now know as much about status inside double quotes as possible, can test for comment
350+
If inQuotes = NotInString And Mid(line, c, 1) = "'" Then
351+
inComment = True
352+
Exit For
353+
End If
354+
Next c
355+
If inComment Then
356+
TrimComments = Trim(Left(line, c - 1))
357+
Else
358+
TrimComments = line
359+
End If
312360
End Function

0 commit comments

Comments
 (0)