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