Skip to content

Commit b86aab2

Browse files
authored
Merge pull request #420 from michaelvobrien/use-mix-root
Change to mix.exs directory before format
2 parents ad06579 + 60c4727 commit b86aab2

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

elixir-format.el

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,16 @@
8484
(setq buffer-read-only nil)
8585
(erase-buffer)))
8686

87+
(defun elixir-format--temp-file-path ()
88+
"Make a temp file in the current directory, because mix format
89+
applies rules based on path patterns and looks for .formatter.exs
90+
files in subdirectories."
91+
(concat (file-name-sans-extension buffer-file-name)
92+
"-emacs-elixir-format."
93+
(file-name-extension buffer-file-name)))
94+
8795
(defun elixir-format--run-format (called-interactively-p)
88-
(let ((tmpfile (make-temp-file "elixir-format" nil ".ex"))
96+
(let ((tmpfile (elixir-format--temp-file-path))
8997
(our-elixir-format-arguments (list (elixir-format--mix-executable) "format")))
9098

9199
(write-region nil nil tmpfile)
@@ -95,7 +103,7 @@
95103
(setq our-elixir-format-arguments (append our-elixir-format-arguments elixir-format-arguments)))
96104
(setq our-elixir-format-arguments (append our-elixir-format-arguments (list tmpfile)))
97105

98-
(if (zerop (apply #'call-process (elixir-format--elixir-executable) nil (elixir-format--errbuff) nil our-elixir-format-arguments))
106+
(if (zerop (elixir-format--from-mix-root (elixir-format--elixir-executable) (elixir-format--errbuff) our-elixir-format-arguments))
99107
(elixir-format--call-format-command tmpfile)
100108
(elixir-format--failed-to-format called-interactively-p))
101109
(delete-file tmpfile)
@@ -194,6 +202,26 @@ Shamelessly stolen from go-mode (https://github.com/dominikh/go-mode.el)"
194202
(delete-region (progn (forward-visible-line 0) (point))
195203
(progn (forward-visible-line arg) (point))))))
196204

205+
206+
(defun elixir-format--from-mix-root (elixir-path errbuff format-arguments)
207+
"Run mix format where `mix.exs' is located, because mix is
208+
meant to be run from the project root. Otherwise, run in the
209+
current directory."
210+
(let ((original-default-directory default-directory)
211+
(mix-dir (locate-dominating-file buffer-file-name "mix.exs")))
212+
213+
(when mix-dir
214+
(setq default-directory (expand-file-name mix-dir)))
215+
216+
(message (concat "Run "
217+
(abbreviate-file-name default-directory) ": "
218+
(mapconcat 'identity format-arguments " ")))
219+
220+
(let ((result (apply #'call-process
221+
elixir-path nil errbuff nil format-arguments)))
222+
(setq default-directory original-default-directory)
223+
result)))
224+
197225
(provide 'elixir-format)
198226

199227
;;; elixir-format.el ends here

0 commit comments

Comments
 (0)