Skip to content

Commit

Permalink
feat: better slugify function
Browse files Browse the repository at this point in the history
The new version can now find anything that isn't considered an
alphanumeric character and replace it with appropriate dashes.  We
also clean up repeated dashes and trim dashes from both start and end
of the string.
  • Loading branch information
clarete committed Jan 30, 2021
1 parent daa5701 commit a935127
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
4 changes: 4 additions & 0 deletions t/weblorg-tests.el
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@
(require 'cl-lib)
(require 'weblorg)

(ert-deftest weblorg--slugify ()
(should (equal (weblorg--slugify "!v0.1.1 - We've come a long way, friend!")
"v0-1-1-we-ve-come-a-long-way-friend")))

(ert-deftest weblorg--collect-n-aggr ()
(weblorg-route
:base-dir (expand-file-name "t/fixtures/test1/" default-directory)
Expand Down
26 changes: 18 additions & 8 deletions weblorg.el
Original file line number Diff line number Diff line change
Expand Up @@ -955,11 +955,7 @@ be added ad an entry to the returned assoc."
;; Don't override existing value, so users can still put
;; whatever they want
(unless (org-element-property :CUSTOM_ID headline)
(let ((headline-slug
(weblorg--slugify
;; Add ".0" suffix because weblorg--slugify strips
;; away the file extension
(format "%s.0" (org-element-property :raw-value headline)))))
(let ((headline-slug (weblorg--slugify (org-element-property :raw-value headline))))
(org-element-put-property headline :CUSTOM_ID headline-slug)))
;; Replace these IDs that don't have much use within weblorg. That
;; will cause way less noise when re-generating a project without
Expand Down Expand Up @@ -1023,10 +1019,24 @@ expression (not a glob)."
result))))))

(defun weblorg--slugify (s)
"Make slug of S."
"Make slug of S.
It replaces anything that isn't between a-z and 0-9 with dashes
return the lower case version of the string. e.g.:
#+BEGIN_SRC emacs-lisp
(weblorg--slugify \"We've come a long way, friend!\")
\"we-ve-come-a-long-way-friend\"
#+END_SRC"
(downcase
(replace-regexp-in-string
"\s" "-" (file-name-sans-extension (file-name-nondirectory s)))))
(seq-reduce
(lambda(accum item)
(replace-regexp-in-string (car item) (cdr item) accum))
'(("[^[:alnum:]]" . "-")
("--+" . "-")
("^-" . "")
("-$" . ""))
s)))

(defun weblorg--get (seq item &optional default)
"Pick ITEM from SEQ or return DEFAULT from list of cons."
Expand Down

0 comments on commit a935127

Please sign in to comment.