summaryrefslogtreecommitdiff
path: root/str.lisp
blob: 3d88d11c74f163b099ad01dc61b24ac830fc4e62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
(in-package #:str)

(defun read-file (path)
  (with-open-file (file path)
    (let* ((size (file-length file))
           (buf (make-string size)))
      (read-sequence buf file)
      buf)))

(defun split (input delimiter)
  (declare (optimize speed)
           (simple-string input delimiter))
  (labels ((split-rec (result start)
                      (let ((next (search delimiter input :start2 start)))
                        (if next
                          (split-rec (queue:push result (subseq input start next))
                                     (min (the fixnum (+ (length delimiter) next))
                                          (the fixnum (length input))))
                          (queue:push result (subseq input start next))))))
    (queue:to-list (split-rec (queue:new) 0))))

(defun remove-prefix (str prefix)
  (if (and (> (length str) (length prefix))
             (string= str prefix :end1 (length prefix)))
    (subseq str (length prefix))
    str))

(defun underscore->hyphen (str)
  (let ((result (make-string-output-stream)))
    (dotimes (i (length str))
      (if (char= #\_ (char str i))
        (format result "-")
        (format result "~a" (char str i))))
    (get-output-stream-string result)))

(defun pascal->kebab (str)
  (let ((result (make-string-output-stream)))
    (dotimes (i (length str))
      (if (and (> i 0) (upper-case-p (char str i)))
        (format result "-~a" (char str i))
        (format result "~a" (char str i))))
    (get-output-stream-string result)))

(defun upcase->pascal (str)
  (let ((result (make-string-output-stream)))
    (dotimes (i (length str))
      (if (and (< 0 i)
               (upper-case-p (char str i))
               (not (lower-case-p (char str (1- i))))
               (or (= i (1- (length str)))
                   (not (lower-case-p (char str (1+ i))))))
        (format result "~a" (char-downcase (char str i)))
        (format result "~a" (char str i))))
    (get-output-stream-string result)))

(defun line-and-column (str index)
  (let ((line 1) (column 1))
    (dotimes (i index)
      (let ((c (char str i)))
        (case c
          (#\Newline
           (incf line)
           (setf column 1))
          (t (incf column)))))
    (cons line column)))

(defun context-window (str index &key (side-length 20))
  (let ((begin (max (- index side-length) 0))
        (end (min (+ index side-length) (length str)))
        (result '()))
    (push (subseq str begin index) result)
    (push (elt str index) result)
    (push (subseq str (1+ index) end) result)
    result))