Skip to content

Instantly share code, notes, and snippets.

@kurohuku
Created October 6, 2010 08:07
Show Gist options
  • Save kurohuku/612997 to your computer and use it in GitHub Desktop.
Save kurohuku/612997 to your computer and use it in GitHub Desktop.
(defun normalize-curr (curr)
(let ((curr (member-if-not
(lambda (obj)
(= obj ?\ ))
curr)))
(if (every #'characterp curr)
(concatenate 'string (nreverse curr))
(if (stringp (car curr))
(car curr)
(error "Invalid element")))))
(defun csv-file->list (file)
(with-temp-buffer
(insert-file-contents file)
(csv-buffer->list (current-buffer))))
(defun csv-buffer->list (bufname)
(with-current-buffer bufname
(save-excursion
(let ((result nil)
(line-result nil)
(curr nil))
(do* ((pos 1 (1+ pos))
(ch (char-after pos) (char-after pos)))
((and (goto-char pos) (eobp)) 'loop-finish)
(cond
((= ch ?\n)
(unless (null curr)
(push (normalize-curr curr) line-result))
(push (nreverse line-result) result)
(setf curr nil)
(setf line-result nil))
((= ch ?\")
(goto-char pos)
(forward-sexp)
(push (buffer-substring-no-properties pos (point))
curr))
((and (null curr) (= ch ?\ ))
;; skip
)
((= ch ?,)
(when (null curr)
(setf curr '("")))
(push (normalize-curr curr)
line-result)
(setf curr nil))
(t
(push ch curr))))
(when curr
(push (normalize-curr curr)
line-result))
(when line-result
(push (nreverse line-result)
result))
(nreverse result)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment