diff --git a/CHANGELOG.md b/CHANGELOG.md index 9194d24c..b55893f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master (unreleased) +### Changes + +* `clojure-find-ns`: add an option to never raise errors, returning nil instead on unparseable ns forms. + ## 5.16.1 (2023-06-26) ### Changes diff --git a/clojure-mode.el b/clojure-mode.el index 67ae3f59..42552992 100644 --- a/clojure-mode.el +++ b/clojure-mode.el @@ -2142,23 +2142,30 @@ DIRECTION is `forward' or `backward'." (setq candidate (string-remove-prefix "'" (thing-at-point 'symbol)))))))) candidate)) -(defun clojure-find-ns () - "Return the namespace of the current Clojure buffer. +(defun clojure-find-ns (&optional suppress-errors) + "Return the namespace of the current Clojure buffer, honor `SUPPRESS-ERRORS'. Return the namespace closest to point and above it. If there are no namespaces above point, return the first one in the buffer. +If `SUPPRESS-ERRORS' is t, errors during ns form parsing will be swallowed, +and nil will be returned instead of letting this function fail. + The results will be cached if `clojure-cache-ns' is set to t." (if (and clojure-cache-ns clojure-cached-ns) clojure-cached-ns - (let ((ns (save-excursion - (save-restriction - (widen) - - ;; Move to top-level to avoid searching from inside ns - (ignore-errors (while t (up-list nil t t))) - - (or (clojure--find-ns-in-direction 'backward) - (clojure--find-ns-in-direction 'forward)))))) + (let* ((f (lambda (direction) + (if suppress-errors + (ignore-errors (clojure--find-ns-in-direction direction)) + (clojure--find-ns-in-direction direction)))) + (ns (save-excursion + (save-restriction + (widen) + + ;; Move to top-level to avoid searching from inside ns + (ignore-errors (while t (up-list nil t t))) + + (or (funcall f 'backward) + (funcall f 'forward)))))) (setq clojure-cached-ns ns) ns))) diff --git a/test/clojure-mode-sexp-test.el b/test/clojure-mode-sexp-test.el index f82552a0..edec5803 100644 --- a/test/clojure-mode-sexp-test.el +++ b/test/clojure-mode-sexp-test.el @@ -167,7 +167,22 @@ (expect (clojure-find-ns) :to-equal expected) ;; After both namespaces (goto-char (point-max)) - (expect (clojure-find-ns) :to-equal expected))))))) + (expect (clojure-find-ns) :to-equal expected)))))) + + (describe "`suppress-errors' argument" + (let ((clojure-cache-ns nil)) + (describe "given a faulty ns form" + (let ((ns-form "(ns )")) + (describe "when the argument is `t'" + (it "causes `clojure-find-ns' to return nil" + (with-clojure-buffer ns-form + (expect (equal nil (clojure-find-ns t)))))) + + (describe "when the argument is `nil'" + (it "causes `clojure-find-ns' to return raise an error" + (with-clojure-buffer ns-form + (expect (clojure-find-ns nil) + :to-throw 'error))))))))) (describe "clojure-sexp-starts-until-position" (it "should return starting points for forms after POINT until POSITION"