2

I'm writing a snippet in which I need to get the current file name in vimscript. I can do this happily with expand('%:t:r') (as shown here). However, I'd like to not only exclude '.js' from the filename, but also '.test'.

e.g.

If in myName.test.js, I would like to grab 'myName'

If in myName.js, I would also like to grab 'myName'

I'm doing this to create an UltiSnips snippet so other methods (e.g. regex) would also be useful

Pang
  • 9,564
  • 146
  • 81
  • 122
James Mulholland
  • 1,782
  • 1
  • 14
  • 21
  • 1
    I don't know other parts of your question but here is how to grab the file name before the `.` using regex /^([^\.]++)/ also see the demo on regex 101 https://regex101.com/r/lHiwpQ/1 – JBone Jan 25 '19 at 12:51

1 Answers1

7

The :t and :r are filename modifiers. If you follow :help filename-modifiers, there's also a nifty (but little known) :s?pat?sub? modifier that can perform substitutions. As this can be combined with the other modifiers, all you need to do is match .test anchored to the end of the filename:

:echo expand('%:t:r:s?\.test$??')

There's no error if the substitution fails, so there's no need to make the match optional (via \?).

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324