hanschen/vim-ipython-cell

[feature request] Replace __file__ with the path to the vim buffer

MarcelRobitaille opened this issue · 6 comments

What do you think about replacing __file__ with the path to the vim buffer? I often find myself wishing this would "just work" instead of giving name '__file__' not defined.

I guess the proper way would be to parse the Python into an AST and figure out that it's really the variable __file__ and not some text inside a string, use the proper quotes if __file__ is in an f-string, etc. But for now, I have the following in ipython_cell.py:69:

f = vim.eval("expand('%:p')")
cell = cell.replace('__file__', f'"{f}"')

PS: I love this plugin. I use it almost every day.

Unfortunately I can't think of an easy way to do it the proper way that you mention. I can add an option to do a simple substitution, similar to your modification.

Glad to hear that the plugin is useful to you. :)

I thought of a really easy solution that doesn't require AST and shouldn't have the side effects discussed previously. Do it the way Python does it; define __file__.

f = vim.eval("expand('%:p')")
cell = "\n".join(
    [f'__file__ = "{f}"'] + vim.current.buffer[start_row-1:end_row])

It's really obvious in hindsight.

What do you think?

Ha, I didn't think about that solution but it sounds nice - I like it more than the substitute method. So I plan to go for this solution (still making it an option, as it will overwrite any __file__ variable).

Awesome, thanks.

it will overwrite any __file__ variable

That is true, but I don't think it is good practice to overwrite these global magic variables. I think it is a sane default, but maybe I am biased.

This feature has now been implemented. Update the plugin and set

let g:ipython_cell_update_file_variable = 1

in your config file. Let me know if you encounter any issues!

Awesome! I will try it. Thank you so much!