0
function! g:insert_date()

    let l:pattern="\\d\\{2}:\\d\\{2}"

    let l:match=match(getline('.'),l:pattern)

    let l:curline=getline('.')

    echo "Current line: ". l:curline

    normal gg

    let l:time=system("time /t")

    let l:date=system("date /t")

    let l:date_time=l:date."\t".l:time

    if l:match!=-1

        echo match

        normal dd

        "call setline('.',system('time /t')."<<>>")

        call setline('.',l:date_time)

    else

        echo match ." ". l:curline." ".l:pattern

        sleep 2

        normal O

        "call setline('.',system("time /t")."\r")

        call setline('.',l:date_time)

        normal dd

    endif

endfunction

I have this code above that is supposed to insert the date and time in the first line of the file.

I was going to assign it to a BufRead autocommand but it's not perfect, yet. Basically, it checks if there is a time string in the first line of the file and if found it updates it. If not, it opens a newline above and inserts the date. The problem is that it does not open a newline when the string is not found. normal 0 is the culprit. It works when I type it in the command line but fails when the function is called. Also, I don't why you have to escape the regExp twice in the script while it works fine with one backslash with ? and /.

As you can see, I have commented the line with the system() function because it keeps inserting visible null bytes(ascii 0) and carriage returns(ascii 13). What is system() doing that makes them visible. I haven't found a workaround for this( read! does not store in a variable. I need the date and time in
one line).

call setline('.',system("time /t")."\r")

call setline('.',system("time /t")."\n\n\n\n\n")  ^@^@^@^@^@^@^@

call setline('.',system("time /t")."\n\n\n\n\n")  ^@^@^@^@^@^@^@ (0)

call setline('.',system('time /t')."\r\r\r\r\r\r") ^M^M^M^M (13)

read! time\ /t

Additional details:

  1. encoding=utf-8
  2. set list is off
  3. Font is consolas:h10
  4. file format is dos
  5. version=7.3

1 Answer 1

0

I have found the answer. The system function reads from the windows date function into the file. The date function outputs text with CRLF as its ending while the file had LF line endings. Vim spots the difference and displays it. I replaced all the line endings to CRLF and they disappeared.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .