一千萬個為什麽

搜索

如果當前文件中不存在特定字符串,如何添加?

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

<?php
declare(strict_types=1);

如果文件已包含 declare(strict_types = 1); 則不執行任何操作。

也許有一個插件或什麽? 謝謝。

最佳答案

像這樣的東西應該工作:

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.

然後我們使用自動命令來在每次打開新的php文件時執行該函數。

要更好地理解功能,您可能需要閱讀

並更改自動命令:

轉載註明原文: 如果當前文件中不存在特定字符串,如何添加?