1

I am traversing through a C code in Vim using cscope. Sometimes while traversing, some key gets pressed or mouse gets right-clicked and the Vim enters in insert mode, and it creates a mess to undo the changes and all. I just want to read the code, and hence want to open Vim in read-only mode. Is it possible? How can it be done so?

  • Check :h view – Maxim Kim Mar 1 at 10:13
  • @MaximKim should I append it after cscope command? – maverick_devil Mar 1 at 10:14
  • Nope, just read about it in help. It will tell you how to run vim in readonly mode (which might be what you want). – Maxim Kim Mar 1 at 10:17
1

Invoke vim as view on the command line:

view myfile.c

This will automatically set the appropriate “readonly” flags.

  • Actually I am using cscope to search a particular keyword and not opening a particular file. So I was thinking if I could open the vim only for reading the code and edit option being disabled. Also I am traversing through multiple files. – maverick_devil Mar 4 at 5:01
  • Simply view should work... vim will be readonly. To completely prevent editing you may want the modifiable flag – D. Ben Knoble Mar 4 at 13:47
0

You can try to reuse modifiable setting (:h mo)

If you set noma (nomodifiable) for a current buffer -- it will prevent any modifications you will try to do for that buffer.

Not sure how to connect it with cscope -- I have never used it and I don't know what is your workflow...

Just an idea -- to use autocommand

autocmd! BufEnter * :set noma

this will turn on no modifiable setting for all your buffers.

To revert do the same with :set ma:

autocmd! BufEnter * :set ma

PS

You can limit it to c buffers:

autocmd! BufEnter *.c,*.h :set noma

PPS

Create mappings (add to your .vimrc):

nnoremap <f5> :set noma<CR>:autocmd! BufEnter *.cpp,*.c,*.h :set noma<CR>
nnoremap <f6> :set ma<CR>:autocmd! BufEnter *.cpp,*.c,*.h :set ma<CR>
  • Press <f5> when you want to do your cscope.
  • Press <f6> when done.

PPPS

Then again, to be more safe you have to check if it was you who set nomodifiable flag before removing it.

Probably it would be better to use :bufdo to remove nomodifiable flag instead of autocommand. (Plus don't forget to turnoff autocommand from <f5> ...)

  • I have to understand C codebase without making modifications to the code and need to traverse through various files for which cscope is efficient method. – maverick_devil Mar 1 at 10:28
  • 1
    Maxim, cscope (like ctags and other similar programs) generates tags in a file, which can be used to jump around a code base in vim using the appropriate keys. Its almost irrelevant to the question, which is how to make vim read-only – D. Ben Knoble Mar 1 at 22:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.