You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.3 KiB
Racket
50 lines
1.3 KiB
Racket
8 years ago
|
#lang br
|
||
8 years ago
|
(require br/indent racket/gui/base)
|
||
8 years ago
|
(provide indent-jsonic)
|
||
8 years ago
|
|
||
8 years ago
|
(define indent-width 2)
|
||
8 years ago
|
(define (left-bracket? c) (member c (list #\{ #\[)))
|
||
|
(define (right-bracket? c) (member c (list #\} #\])))
|
||
8 years ago
|
|
||
8 years ago
|
;; if this line begins with } or ], outdent.
|
||
|
;; if last line begins with { or [, indent.
|
||
|
;; otherwise use previous indent
|
||
8 years ago
|
(define/contract (indent-jsonic tbox [posn 0])
|
||
8 years ago
|
((is-a?/c text%) exact-nonnegative-integer? . -> .
|
||
|
(or/c exact-nonnegative-integer? #f))
|
||
8 years ago
|
(define prev-line (previous-line tbox posn))
|
||
|
(define current-line (line tbox posn))
|
||
|
(define prev-indent (or (line-indent tbox prev-line) 0))
|
||
|
(define current-indent
|
||
8 years ago
|
(cond
|
||
8 years ago
|
[(left-bracket?
|
||
|
(line-first-visible-char tbox prev-line))
|
||
8 years ago
|
(+ prev-indent indent-width)]
|
||
8 years ago
|
[(right-bracket?
|
||
|
(line-first-visible-char tbox current-line))
|
||
8 years ago
|
(- prev-indent indent-width)]
|
||
8 years ago
|
[else prev-indent]))
|
||
8 years ago
|
(and (exact-positive-integer? current-indent) current-indent))
|
||
8 years ago
|
|
||
|
(module+ test
|
||
|
(require rackunit)
|
||
8 years ago
|
(define test-str #<<HERE
|
||
|
#lang jsonic
|
||
8 years ago
|
{
|
||
8 years ago
|
"value",
|
||
|
"string":
|
||
|
[
|
||
8 years ago
|
{
|
||
|
"array": @$(range 5)$@,
|
||
8 years ago
|
"object": @$(hash 'k1 "valstring")$@
|
||
8 years ago
|
}
|
||
8 years ago
|
]
|
||
|
// "bar"
|
||
8 years ago
|
}
|
||
8 years ago
|
HERE
|
||
8 years ago
|
)
|
||
8 years ago
|
(check-equal?
|
||
|
(string-indents (apply-indenter indent-jsonic test-str))
|
||
|
'(#f #f 2 2 2 4 6 6 4 2 2 #f)))
|
||
|
|