1

I want to add this string "declare(strict_types=1);" after <?php when I save or open a file.

<?php
declare(strict_types=1);

If the file already contains declare(strict_types=1); don't do anything.

Maybe there is a plugin or something? Thank you.

2

Something like this should work:

function! AddPHPStrictTypes()
    " Save the cursor position
    let cursor_save = getpos('.')

    " Go to the begining of the file
    call cursor(1, 1)

    " Get the line containing "<?php"
    let phpLine = search('<?php')

    " If the declaration isn't in the buffer and there is one line containing "<?php"
    if search('<?php\ndeclare(strict_types=1);') == 0 && phpLine != 0
        " Add the declaration after the line
        call append(phpLine, "declare(strict_types=1);")
    endif

    " Restore cursor position
    call setpos('.', cursor_save)
endfunction


autocmd! BufReadPost *php call AddPHPStrictTypes()

We declare a function which searches for the declaration. If the declaration is not found it search for the line containing <?php and add the declaration after it.

Then we use an autocommand to execute the function each time you open a new php file.

To understand the function better you may want to read

And to change the autocommand:

  • 1
    use append(), instead of putting, be sure to set the cursor to the beginning of the file before searching and restore the position later – Christian Brabandt Feb 21 '18 at 10:59
  • 1
    @ChristianBrabandt Thanks for your comment, I updated my answer :) – statox Feb 21 '18 at 11:53
  • 1
    Thank you so much for your help, It works perfectly & I learned a lot. – whitesiroi Feb 22 '18 at 1:08

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.