;; String chomp that copies behavior from Ruby programming language.
(define (delete-match-right s pat)
(string-drop-right s (string-suffix-length s pat)))
(define (chomp-chars s lc)
(if (null? lc)
s
(chomp-chars (delete-match-right s (string (car lc))) (cdr lc))))
(define (chomp-trailing-nl s)
(let ((n (string-suffix-length s "\r\n")))
(if (zero? n)
s
(chomp-trailing-nl (string-drop-right s n)))))
(define* (chomp s #:optional (sep '(#\newline #\return)))
(cond
((list? sep)
(chomp-chars s sep))
((string-null? sep)
(chomp-trailing-nl s))
(else
(delete-match-right s sep))))
;; Show.
(format #t "~S~%" (chomp "hello")) ;=> "hello"
(format #t "~S~%" (chomp "hello\n")) ;=> "hello"
(format #t "~S~%" (chomp "hello\r\n")) ;=> "hello"
(format #t "~S~%" (chomp "hello\n\r")) ;=> "hello\n"
(format #t "~S~%" (chomp "hello\r")) ;=> "hello"
(format #t "~S~%" (chomp "hello \n there")) ;=> "hello \n there"
(format #t "~S~%" (chomp "hello" "llo")) ;=> "he"
(format #t "~S~%" (chomp "hello\r\n\r\n\n" "")) ;=> "hello"
(format #t "~S~%" (chomp "hello\r\n\r\r\n" "")) ;=> "hello\r\n\r"