]> code.delx.au - gnu-emacs/blob - lisp/progmodes/project.el
Add project-find-file and project-or-external-find-file
[gnu-emacs] / lisp / progmodes / project.el
1 ;;; project.el --- Operations on the current project -*- lexical-binding: t; -*-
2
3 ;; Copyright (C) 2015-2016 Free Software Foundation, Inc.
4
5 ;; This file is part of GNU Emacs.
6
7 ;; GNU Emacs is free software: you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
11
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
16
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
19
20 ;;; Commentary:
21
22 ;; This file contains generic infrastructure for dealing with
23 ;; projects, some utility functions, and commands using that
24 ;; infrastructure.
25 ;;
26 ;; The goal is to make it easier for Lisp programs to operate on the
27 ;; current project, without having to know which package handles
28 ;; detection of that project type, parsing its config files, etc.
29 ;;
30 ;; Infrastructure:
31 ;;
32 ;; Function `project-current', to determine the current project
33 ;; instance, and 3 (at the moment) generic functions that act on it.
34 ;; This list is to be extended in future versions.
35 ;;
36 ;; Utils:
37 ;;
38 ;; `project-combine-directories' and `project-subtract-directories',
39 ;; mainly for use in the abovementioned generics' implementations.
40 ;;
41 ;; Commands:
42 ;;
43 ;; `project-find-regexp' and `project-or-external-find-regexp' use the
44 ;; current API, and thus will work in any project that has an adapter.
45
46 ;;; TODO:
47
48 ;; * Reliably cache the list of files in the project, probably using
49 ;; filenotify.el (if supported) to invalidate. And avoiding caching
50 ;; if it's not available (manual cache invalidation is not nice).
51 ;;
52 ;; * Allow the backend to override the file-listing logic? Maybe also
53 ;; to delegate file name completion to an external tool.
54 ;;
55 ;; * Build tool related functionality. Start with a `project-build'
56 ;; command, which should provide completions on tasks to run, and
57 ;; maybe allow entering some additional arguments. This might
58 ;; be handled better with a separate API, though. Then we won't
59 ;; force every project backend to be aware of the build tool(s) the
60 ;; project is using.
61 ;;
62 ;; * Command to (re)build the tag files in all project roots. To that
63 ;; end, we might need to add a way to provide file whitelist
64 ;; wildcards for each root to limit etags to certain files (in
65 ;; addition to the blacklist provided by ignores), and/or allow
66 ;; specifying additional tag regexps.
67 ;;
68 ;; * UI for the user to be able to pick the current project for the
69 ;; whole Emacs session, independent of the current directory. Or,
70 ;; in the more advanced case, open a set of projects, and have some
71 ;; project-related commands to use them all. E.g., have a command
72 ;; to search for a regexp across all open projects. Provide a
73 ;; history of projects that were opened in the past (storing it as a
74 ;; list of directories should suffice).
75 ;;
76 ;; * Support for project-local variables: a UI to edit them, and a
77 ;; utility function to retrieve a value. Probably useless without
78 ;; support in various built-in commands. In the API, we might get
79 ;; away with only adding a `project-configuration-directory' method,
80 ;; defaulting to the project root the current file/buffer is in.
81 ;; And prompting otherwise. How to best mix that with backends that
82 ;; want to set/provide certain variables themselves, is up for
83 ;; discussion.
84
85 ;;; Code:
86
87 (require 'cl-generic)
88
89 (defvar project-find-functions (list #'project-try-vc)
90 "Special hook to find the project containing a given directory.
91 Each functions on this hook is called in turn with one
92 argument (the directory) and should return either nil to mean
93 that it is not applicable, or a project instance.")
94
95 ;;;###autoload
96 (defun project-current (&optional maybe-prompt dir)
97 "Return the project instance in DIR or `default-directory'.
98 When no project found in DIR, and MAYBE-PROMPT is non-nil, ask
99 the user for a different directory to look in."
100 (unless dir (setq dir default-directory))
101 (let ((pr (project--find-in-directory dir)))
102 (cond
103 (pr)
104 (maybe-prompt
105 (setq dir (read-directory-name "Choose the project directory: " dir nil t)
106 pr (project--find-in-directory dir))
107 (unless pr
108 (user-error "No project found in `%s'" dir))))
109 pr))
110
111 (defun project--find-in-directory (dir)
112 (run-hook-with-args-until-success 'project-find-functions dir))
113
114 (cl-defgeneric project-roots (project)
115 "Return the list of directory roots of the current project.
116
117 Most often it's just one directory which contains the project
118 build file and everything else in the project. But in more
119 advanced configurations, a project can span multiple directories.
120
121 The directory names should be absolute.")
122
123 ;; FIXME: Add MODE argument, like in `ede-source-paths'?
124 (cl-defgeneric project-external-roots (_project)
125 "Return the list of external roots for PROJECT.
126
127 It's the list of directories outside of the project that are
128 still related to it. If the project deals with source code then,
129 depending on the languages used, this list should include the
130 headers search path, load path, class path, and so on.
131
132 The rule of thumb for whether to include a directory here, and
133 not in `project-roots', is whether its contents are meant to be
134 edited together with the rest of the project."
135 nil)
136
137 (cl-defgeneric project-ignores (_project _dir)
138 "Return the list of glob patterns to ignore inside DIR.
139 Patterns can match both regular files and directories.
140 To root an entry, start it with `./'. To match directories only,
141 end it with `/'. DIR must be one of `project-roots' or
142 `project-external-roots'."
143 (require 'grep)
144 (defvar grep-find-ignored-files)
145 (nconc
146 (mapcar
147 (lambda (dir)
148 (concat dir "/"))
149 vc-directory-exclusion-list)
150 grep-find-ignored-files))
151
152 (defgroup project-vc nil
153 "Project implementation using the VC package."
154 :group 'tools)
155
156 (defcustom project-vc-ignores nil
157 "List ot patterns to include in `project-ignores'."
158 :type '(repeat string)
159 :safe 'listp)
160
161 ;; FIXME: Using the current approach, major modes are supposed to set
162 ;; this variable to a buffer-local value. So we don't have access to
163 ;; the "external roots" of language A from buffers of language B, which
164 ;; seems desirable in multi-language projects, at least for some
165 ;; potential uses, like "jump to a file in project or external dirs".
166 ;;
167 ;; We could add a second argument to this function: a file extension,
168 ;; or a language name. Some projects will know the set of languages
169 ;; used in them; for others, like VC-based projects, we'll need
170 ;; auto-detection. I see two options:
171 ;;
172 ;; - That could be implemented as a separate second hook, with a
173 ;; list of functions that return file extensions.
174 ;;
175 ;; - This variable will be turned into a hook with "append" semantics,
176 ;; and each function in it will perform auto-detection when passed
177 ;; nil instead of an actual file extension. Then this hook will, in
178 ;; general, be modified globally, and not from major mode functions.
179 ;;
180 ;; The second option seems simpler, but the first one has the
181 ;; advantage that the user could override the list of languages used
182 ;; in a project via a directory-local variable, thus skipping
183 ;; languages they're not working on personally (in a big project), or
184 ;; working around problems in language detection (the detection logic
185 ;; might be imperfect for the project in question, or it might work
186 ;; too slowly for the user's taste).
187 (defvar project-vc-external-roots-function (lambda () tags-table-list)
188 "Function that returns a list of external roots.
189
190 It should return a list of directory roots that contain source
191 files related to the current buffer.
192
193 The directory names should be absolute. Used in the VC project
194 backend implementation of `project-external-roots'.")
195
196 (defun project-try-vc (dir)
197 (let* ((backend (ignore-errors (vc-responsible-backend dir)))
198 (root (and backend (ignore-errors
199 (vc-call-backend backend 'root dir)))))
200 (and root (cons 'vc root))))
201
202 (cl-defmethod project-roots ((project (head vc)))
203 (list (cdr project)))
204
205 (cl-defmethod project-external-roots ((project (head vc)))
206 (project-subtract-directories
207 (project-combine-directories
208 (mapcar
209 #'file-name-as-directory
210 (funcall project-vc-external-roots-function)))
211 (project-roots project)))
212
213 (cl-defmethod project-ignores ((project (head vc)) dir)
214 (let* ((root (cdr project))
215 backend)
216 (append
217 (when (file-equal-p dir root)
218 (setq backend (vc-responsible-backend root))
219 (mapcar
220 (lambda (entry)
221 (if (string-match "\\`/" entry)
222 (replace-match "./" t t entry)
223 entry))
224 (vc-call-backend backend 'ignore-completion-table root)))
225 (project--value-in-dir 'project-vc-ignores root)
226 (cl-call-next-method))))
227
228 (defun project-combine-directories (&rest lists-of-dirs)
229 "Return a sorted and culled list of directory names.
230 Appends the elements of LISTS-OF-DIRS together, removes
231 non-existing directories, as well as directories a parent of
232 whose is already in the list."
233 (let* ((dirs (sort
234 (mapcar
235 (lambda (dir)
236 (file-name-as-directory (expand-file-name dir)))
237 (apply #'append lists-of-dirs))
238 #'string<))
239 (ref dirs))
240 ;; Delete subdirectories from the list.
241 (while (cdr ref)
242 (if (string-prefix-p (car ref) (cadr ref))
243 (setcdr ref (cddr ref))
244 (setq ref (cdr ref))))
245 (cl-delete-if-not #'file-exists-p dirs)))
246
247 (defun project-subtract-directories (files dirs)
248 "Return a list of elements from FILES that are outside of DIRS.
249 DIRS must contain directory names."
250 ;; Sidestep the issue of expanded/abbreviated file names here.
251 (cl-set-difference files dirs :test #'file-in-directory-p))
252
253 (defun project--value-in-dir (var dir)
254 (with-temp-buffer
255 (setq default-directory dir)
256 (hack-dir-local-variables-non-file-buffer)
257 (symbol-value var)))
258
259 (declare-function grep-read-files "grep")
260 (declare-function xref-collect-matches "xref")
261 (declare-function xref--show-xrefs "xref")
262 (declare-function xref-backend-identifier-at-point "xref")
263 (declare-function xref--find-ignores-arguments "xref")
264
265 ;;;###autoload
266 (defun project-find-regexp (regexp)
267 "Find all matches for REGEXP in the current project's roots.
268 With \\[universal-argument] prefix, you can specify the directory
269 to search in, and the file name pattern to search for."
270 (interactive (list (project--read-regexp)))
271 (let* ((pr (project-current t))
272 (dirs (if current-prefix-arg
273 (list (read-directory-name "Base directory: "
274 nil default-directory t))
275 (project-roots pr))))
276 (project--find-regexp-in dirs regexp pr)))
277
278 ;;;###autoload
279 (defun project-or-external-find-regexp (regexp)
280 "Find all matches for REGEXP in the project roots or external roots.
281 With \\[universal-argument] prefix, you can specify the file name
282 pattern to search for."
283 (interactive (list (project--read-regexp)))
284 (let* ((pr (project-current t))
285 (dirs (append
286 (project-roots pr)
287 (project-external-roots pr))))
288 (project--find-regexp-in dirs regexp pr)))
289
290 (defun project--read-regexp ()
291 (read-regexp "Find regexp"
292 (xref-backend-identifier-at-point (xref-find-backend))))
293
294 (defun project--find-regexp-in (dirs regexp project)
295 (require 'grep)
296 (let* ((files (if current-prefix-arg
297 (grep-read-files regexp)
298 "*"))
299 (xrefs (cl-mapcan
300 (lambda (dir)
301 (xref-collect-matches regexp files dir
302 (project-ignores project dir)))
303 dirs)))
304 (unless xrefs
305 (user-error "No matches for: %s" regexp))
306 (xref--show-xrefs xrefs nil)))
307
308 (defun project-find-file ()
309 (interactive)
310 (let* ((pr (project-current t))
311 (dirs (project-roots pr)))
312 (project--find-file-in dirs pr)))
313
314 (defun project-or-external-find-file ()
315 (interactive)
316 (let* ((pr (project-current t))
317 (dirs (append
318 (project-roots pr)
319 (project-external-roots pr))))
320 (project--find-file-in dirs pr)))
321
322 ;; FIXME: Uniquely abbreviate the roots?
323 (defun project--find-file-in (dirs project)
324 (let* ((all-files
325 (cl-mapcan
326 (lambda (dir)
327 (let ((command
328 (format "%s %s %s -type f -print0"
329 find-program
330 dir
331 (xref--find-ignores-arguments
332 (project-ignores project dir)
333 (expand-file-name dir)))))
334 (split-string (shell-command-to-string command) "\0" t)))
335 dirs))
336 (table (lambda (string pred action)
337 (cond
338 ((eq action 'metadata)
339 '(metadata . ((category . project-file))))
340 (t
341 (complete-with-action action all-files string pred))))))
342 (find-file
343 (completing-read "Find file: " table nil t))))
344
345 (provide 'project)
346 ;;; project.el ends here