开发者

Can I affect quoting in a Powershell tab expansion function?

开发者 https://www.devze.com 2023-01-18 15:35 出处:网络
Powershell tab expansion functions take 2 parameters, the line so far, and the \"current word\". The function should return a replacement for the current word.

Powershell tab expansion functions take 2 parameters, the line so far, and the "current word". The function should return a replacement for the current word.

From experiment, it seems to me that the current word is passed to the function without any quotes, and the returned word is inserted into the line with the same quoting as the original. So, for example, if I type

PS> foo "bar"<TAB>

I will get the string bar passed to my tab expansion fu开发者_开发技巧nction (without quotes), and my returned value will be placed back on the line in double quotes.

This behaviour causes problems in certain cases. For example, partial completion of file names, where I might type C:\Pro<TAB> to get "C:\Program Files", but I then need to delete the final quote to expand further (say, by typing \Micro and then hitting TAB again.

Also, returning an expanded value containing quotes can be very messy:

PS> function TabExpansion($line, $lastword) {
PS>    "looks like '" + $lastword + "' when quoted"
PS> }
PS>
PS> Silly 'example'<TAB>

This results in unbalanced quotes.

Is there any way of avoiding or working around this behaviour?

Paul.


First off, this is not true:

This behaviour causes problems in certain cases. For example, partial completion of file names, where I might type C:\Pro to get "C:\Program Files", but I then need to delete the final quote to expand further (say, by typing \Micro and then hitting TAB again.

You can continue typing the \Micro after the quote and it will take care of it for you.

If you really need to return a value containing quotes, you can inject the escape character (`) into your string. Note that you will need to escape the escape character itself so it doesn't get eaten:

function TabExpansion($line, $lastword){
    "looks like ``'" + $lastword + "``' when quoted"
}

After Tab expansion, your example will look like:

Silly "looks like `'example`' when quoted"

and the parser should have no problem with it.

0

精彩评论

暂无评论...
验证码 换一张
取 消