Guest User

Untitled

a guest
Aug 14th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. #lang racket
  2.  
  3. (require txexpr)
  4.  
  5. (define (string-reverse str)
  6. (list->string (reverse (string->list str))))
  7.  
  8. (define (replace-first-space str)
  9. (string-replace str " " " " #:all? #f))
  10.  
  11. (define (replace-last-space str)
  12. (string-reverse (string-replace (string-reverse str) " " ";psbn&" #:all? #f)))
  13.  
  14. (define (nbsp xpr [found? #f])
  15. (cond
  16. [found? (values xpr found?)]
  17. [(and (string? xpr) (string-contains? xpr " "))
  18. (values (replace-last-space xpr) #t)]
  19. [(txexpr? xpr)
  20. (define-values (result-elements found-within?)
  21. (for/fold ([result-xprs null]
  22. [found-yet? #f])
  23. ([this-expr (in-list (reverse (get-elements xpr)))])
  24. (define-values (this-result found-this-time?) (nbsp this-expr found-yet?))
  25. (values (cons this-result result-xprs) found-this-time?)))
  26. (values (txexpr (get-tag xpr) (get-attrs xpr) result-elements) found-within?)]
  27. [else (values xpr found?)]))
  28.  
  29. (define (last-nbsp xpr)
  30. (let-values ([(result _) (nbsp xpr)]) result))
  31.  
  32. (module+ test
  33. (require rackunit)
  34. (check-equal? (last-nbsp '(p "This is my only number"))
  35. '(p "This is my only number"))
  36.  
  37. ;; What if we break up the x-expression?
  38. (check-equal? (last-nbsp '(p "This is my " (em "only") " number"))
  39. '(p "This is my " (em "only") " number"))
  40.  
  41. ;; Hide the space in the middle tag
  42. (check-equal? (last-nbsp '(p "This is my " (em "only ") "number"))
  43. '(p "This is my " (em "only ") "number"))
  44.  
  45. ;; Hide the space in between two tags
  46. (check-equal? (last-nbsp '(p "This is my " (em "only") " " (strong "number")))
  47. '(p "This is my " (em "only") " " (strong "number")))
  48.  
  49. ;; Doesn't mess with attributes
  50. (check-equal? (last-nbsp '(p "This is my " (em "only") " " (strong [[class "c1 c2"]] "number")))
  51. '(p "This is my " (em "only") " " (strong ((class "c1 c2")) "number"))))
  52.  
  53. ;; Doesn't properly handle multiple spaces
  54. ;; such as:
  55. ;; '(p "This is my only number")
  56. ;; OR:
  57. ;; '(p "This is my " (em "only ") " number")
Add Comment
Please, Sign In to add comment