|
| 1 | +import { foldService } from '@codemirror/language'; |
| 2 | + |
| 3 | +function findRange(pair, state, startLine) { |
| 4 | + let depth = 1; |
| 5 | + const from = startLine.to; |
| 6 | + |
| 7 | + for (let i = startLine.number + 1; i <= state.doc.lines; i++) { |
| 8 | + const line = state.doc.line(i); |
| 9 | + const text = line.text.trim(); |
| 10 | + |
| 11 | + if (pair.start.test(text)) { |
| 12 | + depth++; |
| 13 | + } else if (pair.end.test(text)) { |
| 14 | + depth--; |
| 15 | + if (depth === 0) { |
| 16 | + // Only fold if there is at least one line between the start and end. |
| 17 | + if (i <= startLine.number + 1) { |
| 18 | + return null; |
| 19 | + } |
| 20 | + |
| 21 | + // leaving the closing keyword line visible after folding. |
| 22 | + const to = state.doc.line(i - 1).to; |
| 23 | + return { from, to }; |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + // No valid closing block found |
| 28 | + return null; |
| 29 | +} |
| 30 | + |
| 31 | + |
| 32 | +const plpgsqlFoldService = foldService.of((state, startPos) => { |
| 33 | + const startLine = state.doc.lineAt(startPos); |
| 34 | + const startText = startLine.text.trim(); |
| 35 | + |
| 36 | + const foldPairs = [ |
| 37 | + // Added 'i' flag for case-insensitivity |
| 38 | + { start: /^BEGIN\b/i, end: /^END\b\s*;$/i }, |
| 39 | + { start: /^IF\b/i, end: /^END IF\b\s*;$/i }, |
| 40 | + { start: /^FOR\b/i, end: /^END LOOP\b\s*;$/i }, |
| 41 | + { start: /^CASE\b/i, end: /^END CASE\b\s*;$/i } |
| 42 | + ]; |
| 43 | + |
| 44 | + for (let pair of foldPairs) { |
| 45 | + if (pair.start.test(startText)) { |
| 46 | + return findRange(pair, state, startLine); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return null; |
| 51 | +}); |
| 52 | + |
| 53 | +export default plpgsqlFoldService; |
0 commit comments