Sunday, May 31, 2020

Re: function definition for only one file, not for other simultaneously opened files

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.
I looked up this. While reading the manual, I realized I wanted a buffer-local function but as it is not available so I think I would just copy that function to my .vimrc and as you suggested, invoke a mapping anytime I want to use that function in some 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.
Though, this can be done as I am working with some markdown files for note-taking etc. but I wanted to make the feature less hard coded. As in, I have many markdown files for notes on different topics (viz. current project, academics, reminders, etc.) but I wanted the timestamp feature to only apply in one of those files.
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.


On 31/05/20 2:13 pm, Tony Mechelynck wrote:
- 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.


On 31/05/20 3:48 pm, BPJ wrote:
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 something
endif
But again it will become hard-coded for that particular file. As I open multiple markdown files simultaneously, so I will need to go with the filename.


PS: Sorry for delayed response.

--
Manas
CSAM Undergraduate 2022

No comments: