|
| 1 | +import Lean.Elab.Command |
| 2 | +import Lean.Linter.Util |
| 3 | + |
| 4 | +/-! |
| 5 | +# The "trailingWhitespace" linter |
| 6 | +
|
| 7 | +The "trailingWhitespace" linter emits a warning whenever a line ends with a space or a file |
| 8 | +does not end with a line break. |
| 9 | +-/ |
| 10 | + |
| 11 | +open Lean Elab |
| 12 | + |
| 13 | +namespace Mathlib.Linter |
| 14 | + |
| 15 | +/-- |
| 16 | +The "trailingWhitespace" linter emits a warning whenever a line ends with a space or a file |
| 17 | +does not end with a line break. |
| 18 | +-/ |
| 19 | +register_option linter.trailingWhitespace : Bool := { |
| 20 | + defValue := true |
| 21 | + descr := "enable the trailingWhitespace linter" |
| 22 | +} |
| 23 | + |
| 24 | +namespace TrailingWhitespace |
| 25 | + |
| 26 | +@[inherit_doc Mathlib.Linter.linter.trailingWhitespace] |
| 27 | +def trailingWhitespaceLinter : Linter where run := withSetOptionIn fun stx ↦ do |
| 28 | + unless Linter.getLinterValue linter.trailingWhitespace (← getOptions) do |
| 29 | + return |
| 30 | + if (← get).messages.hasErrors then |
| 31 | + return |
| 32 | + let srg := stx.getRange?.getD default |
| 33 | + let fm ← getFileMap |
| 34 | + for lb in fm.positions do |
| 35 | + if srg.contains lb then |
| 36 | + let last : Substring := { str := fm.source, startPos := ⟨lb.1 - 2⟩, stopPos := ⟨lb.1 - 1⟩ } |
| 37 | + if last.toString == " " then |
| 38 | + Linter.logLint linter.trailingWhitespace (.ofRange ⟨⟨lb.1 - 2⟩, ⟨lb.1 - 1⟩⟩) |
| 39 | + m!"Lines should not end with a space." |
| 40 | + unless Parser.isTerminalCommand stx do return |
| 41 | + let (backBack, back) := (fm.positions.pop.back, fm.positions.back) |
| 42 | + let rg : String.Range := ⟨back - ⟨1⟩, back⟩ |
| 43 | + if backBack != back then |
| 44 | + Linter.logLint linter.trailingWhitespace (.ofRange rg) m!"Files should end with a line-break." |
| 45 | + |
| 46 | +initialize addLinter trailingWhitespaceLinter |
| 47 | + |
| 48 | +end TrailingWhitespace |
| 49 | + |
| 50 | +end Mathlib.Linter |
0 commit comments