diff --git a/elixir-format.el b/elixir-format.el index c3a718a9..e3753392 100644 --- a/elixir-format.el +++ b/elixir-format.el @@ -84,8 +84,16 @@ (setq buffer-read-only nil) (erase-buffer))) +(defun elixir-format--temp-file-path () + "Make a temp file in the current directory, because mix format +applies rules based on path patterns and looks for .formatter.exs +files in subdirectories." + (concat (file-name-sans-extension buffer-file-name) + "-emacs-elixir-format." + (file-name-extension buffer-file-name))) + (defun elixir-format--run-format (called-interactively-p) - (let ((tmpfile (make-temp-file "elixir-format" nil ".ex")) + (let ((tmpfile (elixir-format--temp-file-path)) (our-elixir-format-arguments (list (elixir-format--mix-executable) "format"))) (write-region nil nil tmpfile) @@ -95,7 +103,7 @@ (setq our-elixir-format-arguments (append our-elixir-format-arguments elixir-format-arguments))) (setq our-elixir-format-arguments (append our-elixir-format-arguments (list tmpfile))) - (if (zerop (apply #'call-process (elixir-format--elixir-executable) nil (elixir-format--errbuff) nil our-elixir-format-arguments)) + (if (zerop (elixir-format--from-mix-root (elixir-format--elixir-executable) (elixir-format--errbuff) our-elixir-format-arguments)) (elixir-format--call-format-command tmpfile) (elixir-format--failed-to-format called-interactively-p)) (delete-file tmpfile) @@ -194,6 +202,26 @@ Shamelessly stolen from go-mode (https://github.com/dominikh/go-mode.el)" (delete-region (progn (forward-visible-line 0) (point)) (progn (forward-visible-line arg) (point)))))) + +(defun elixir-format--from-mix-root (elixir-path errbuff format-arguments) + "Run mix format where `mix.exs' is located, because mix is +meant to be run from the project root. Otherwise, run in the +current directory." + (let ((original-default-directory default-directory) + (mix-dir (locate-dominating-file buffer-file-name "mix.exs"))) + + (when mix-dir + (setq default-directory (expand-file-name mix-dir))) + + (message (concat "Run " + (abbreviate-file-name default-directory) ": " + (mapconcat 'identity format-arguments " "))) + + (let ((result (apply #'call-process + elixir-path nil errbuff nil format-arguments))) + (setq default-directory original-default-directory) + result))) + (provide 'elixir-format) ;;; elixir-format.el ends here