I am struggling to find a way to deal with the following problem.
Suppose, I open 3 markdown files at once in separate tabs. Now I want some particular function for one of those files only. Like, I want to add time and date in front of each new line for that file. So I define a function to do so. But, that function is affecting other files too which I don't want.
Is there some way to achieve that?
On 31/05/20 6:18 am, Gary Johnson wrote:
From ":help local-function": There are only script-local functions, no buffer-local or window-local functions. However, you _can_ control how and when your function is executed. For example, mappings and autocommands can be local to a buffer.
You can also have your function look at the current buffer name or some other property of the buffer and decide whether to continue executing or to return immediately.
How are you executing your function and what is it doing to affect files or buffers that you don't want it to?
My function executes a bash command to get the current date and time, whenever I hit <ENTER> and prepends it to the line.
- a function can be assigned to a Funcref which is a variable (global, script-local, buffer-local, window-local, etc.) of a special type; that Funcref can then be used both as a variable (when not followed by () ) or as a function (followed by () ). I have a kind of hunch that there is something for you (Manas) in the above but I'm not sure what.
I found this the most optimum. What I did was:
1. define the function
2. create a buffer-local function reference
pointing to the function:
> let b:Fn = function("PrependTime")
`PrependTime` is my function name.
3. And now `:echo b:Fn()` in current buffer will prepend the timestamp and in other buffers, it will throw error (E117: Unknown function). Now I wanted to somehow suppress the error message but I could not find much.
I believe that as Gary hinted the best bet in this case is to inspect the file extension (".md" I guess) with the help of
if matchstr(bufname(), '\.md$')" do somethingendif
PS: Sorry for delayed response.
You wrote that you want to have <Enter> insert the date at the start of the next line, but only in one buffer. Wouldn't making that mapping buffer-local solve your problem? Something like this? inoremap <buffer> <CR> <CR><C-R>=PrependTime()<CR> function! PrependTime() return strftime("%c") endfunction See :help map-<buffer> You would just need to execute that mapping only in the one buffer where you wanted that behavior.
If other buffers are throwing error E117, then you have <Enter> (a.k.a. <CR>) mapped in buffers where it shouldn't be mapped. Regards, Gary
After unmapping and remapping I checked everything works fine.
Thanks a lot everyone.