3

I'm trying to make a function to insert license header from external file on first line in the buffer. The script is:

    fun InsertLicense()
        if filereadable('LICENSE')
            let license = 'LICENSE'
        elseif filereadable('LICENSE.txt')
            let license = 'LICENSE.txt'
        else
            let license = ''
        endif
      if line('$') < 3 && len(license) > 0
          echo 'inserting license from ' . license
          call append(0, readfile(license))
      endif
    endfun

It's working fine except one problem: LICENSE file is a plaintext file, e.g.:

Copyright 2019 OrgName

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated
...

but I need to wrap it as Java multiline comment:

/*
 * Copyright 2019 OrgName
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated
...
 */

Is it possible to insert * before each line of license file using vim scripting language?

4

readfile() returns a list, each line being in a separate list item.

You can therefore make use of map() to change the list inplace:

let a=map(readfile('LICENSE'), { i,v -> '/* ' . v. ' */'})

This makes use of lambda expression and wraps a the comment characters /* and */ around it.

Alternatively, you can do this:

 :let a=['/* '] + map(readfile('LICENSE'), { i,v -> '* ' . v}) + ['*/']

which adds only /* at the start of the file and */ at the end of the file and for each line simply prepends the *.

  • 1
    Damn, it took me 4 more minutes to come up with a much less elegant solution! :) – statox Jun 7 at 12:21
  • 1
    Upps, Sorry for that ;) – Christian Brabandt Jun 7 at 12:22
2

Christian’s answer is great—for java files. But it requires some care for different filetypes.

One alternative would be to lean on the machinery of tpope’s commentary and do something like

" Go comment a paragraph
normal gcap

After you insert the license text.

Note that commentary comments each line individually, which can look less pretty for large chunks of text, but makes uncommenting lines (of code) easier in terms of the plugin code. You may or may not be able to live with this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.