bash中的Makefile变量自动完成

时间:2014-09-10 13:34:29

标签: bash variables autocomplete makefile

让我们说Makefile就像:

DIR :=#

foobar:

   ls ${DIR}

当我输入

mak[tab] f[tab]

它正确地给出了

make foobar

但是

make foobar D[tab]

不做魔术

make foobar DIR=

所以我的问题是:有没有办法在bash中自动完成Makefile变量(除了目标)?

1 个答案:

答案 0 :(得分:2)

这个答案远非完整。要在Makefile中grep所有变量,我们使用make -p来打印 Makefile数据库

# GNU Make 3.81
# Copyright (C) 2006  Free Software Foundation, Inc.
# This is free software; see the source for copying conditions.
# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.

# This program built for x86_64-pc-linux-gnu

# Make data base, printed on Mon Oct 13 13:36:12 2014

# Variables

# automatic
<D = $(patsubst %/,%,$(dir $<))
# automatic
?F = $(notdir $?)
# environment
DESKTOP_SESSION = kde-plasma
# ...
# makefile (from `Makefile', line 1)
DIR := 

我们正在寻找以# makefile (from 'Makefile', line xy)开头的行,并提取以下变量的名称:

$ make -p | sed -n '/# makefile (from/ {n; p;}'
MAKEFILE_LIST :=  Makefile
DIR :=

在下一步中,我们删除除变量名称之外的所有内容(:=之后的所有内容):

$ make -p Makefile | sed -n '/# makefile (from/ {n; s/^\([^.#:= ]\+\) *:\?=.*$/\1/p;}'
MAKEFILE_LIST
DIR

以下几行演示了如何完成:

_make_variables()
{
  # get current completion
  local cur=${COMP_WORDS[COMP_CWORD]}
  # get list of possible makefile variables
  local var=$(make -p Makefile | sed -n '/# makefile (from/ {n; s/^\([^.#:= ]\+\) *:\?=.*$/\1=/p;}')
  # don't add a space after completion
  compopt -o nospace

  # find possible matches
  COMPREPLY=( $(compgen -W "${var}" -- ${cur}) )
}

# use _make_variables to complete make arguments
complete -F _make_variables make

现在make D[tab]会产生make DIR=

遗憾的是,您将使用此方法完成所有文件和目标的完成。另外,从完成输出中删除一些更多变量(例如MAKEFILE_LIST)会很有用。

也许值得填写针对bash-completion project的愿望/错误报告来添加此功能。