Any way to auto-indent a c/c++ code with Kdevelop? - kdevelop

I've a source code that's not mine, there are not comment and it's completely not indented. Is it a really mess. Do you know if there is some option, addon for kdevelop that would auto-indent it?

Assuming you're using KDevelop 4 and not the (no longer supported) KDevelop 3...
You can use "Edit > Reformat Source" to format the current file source.
You can also right click on one or more files in Projects view on the left and select "Format Files"
You can configure your source formatting settings in "Settings > Configure KDevelop > Source Formatter".
KDevelop 4 uses AStyle to handle the formatting.
Edit:
It should be noted that there are also some settings in "Settings > Configure Editor" which configures the embedded KatePart.
These are the "as you edit" settings with no effect on the source formatting component detailed above. This would control the auto-indentation when inserting newlines after a bracket, for example.

Good old command line indent : http://linux.die.net/man/1/indent

In KDevelop if I remember correctly you can go to Settings -> Configure -> Indentation. (Or something similar). Though I can't remember if that's settings for Auto-Indentation as you write or whether its for formatting code in general.

Tools like indent are quite powerful but has tons of switches to be flexible enough to support all coding style.
If it's an editor you're after, vim does syntax-sensitive indention for C nicely. Open the file with Vim and do "gg=G" and you're done.

Related

Is there a way to get help for some C functions inside of vim/Neovim?

This question may be a little off topic. But I was wondering if there was a way for me to look at the descriptions of C functions using vim or neovim. Is it possible to look at their documentations by doing something like :help? This would really be helpful since I wouldn't need to lookup to my browser everytime.
I am unclear about these things:
Can :help be my friend here ?
Can I use LSPs to do something like this ?
I am using latest Neovim inside Ubunutu 20.04 in WSL. Is this helpful somehow ?
By pressing K, the keyword under the cursor is looked up using a configured keyword lookup program, the default being man. This works pretty much out of the box for the C standard library.
For C++, you might want to look at something like cppman.
Well yes, you can get the description of C functions by using a LSP (language server plugin)! Here is an image of me using clangd as my LSP:
You'd "just" need to install the LSP and start it. I don't know how familiar you're with neovim, but just in case if you don't know how to install a plugin or to be more specifique: If you don't know how you can install a LSP server, then you can do the following:
There're plenty videos how to set up a LSP-Server for your language. Here's an example.
If you don't want to set up on your own, you can pick up one of the preconfigured neovim setups (some of my friends are recommending lunarvim)
But yeah, that's it. If you have any further questions feel free to ask them in the comments.
Happy vimming c(^-^)c
Let's explain how "K" command works in more detail.
You can run external commands by prefixing them with :! command. So running man tool is as easy as
:!man <C-R><C-W>
Here <C-R><C-W> is a special key combination used to put word under cursor from text buffer down to command line.
Same for showing Vim's built-in help page
:help <C-R><C-W>
As it feels tedious to type that, Vim also defines K Normal mode command that does pretty much the same thing. Except the tool name is taken from value of an option named "keywordprg".
So doing set keywordprg=man (default for *nix systems) makes K to invoke !man tool; while set keywordprg=:help is for bultin help.
Also, the option :h 'keywordprg' is made global or local-to-buffer, so any Vim buffer is able to overwrite global setting. For example, this is already done by standard runtime for "vim" and "help" buffers, so they call ":help" instead of "man".
The problem with :!man command is that it shows "black console". It'd be nice if we could capture man's output and open it inside Vim just like a builtin help page. Then we could also apply some pretty highlighting, assign key macros and all such. This is a pretty common trick and it is already done by a standard plugin shipped with Vim/Neovim.
A command that the plugin provides is called :Man, so you can open :Man man instead of :!man man, for example. The plugin is preactivated in Neovim; for Vim you still need to source one file manually. So to make use of this plugin you'll need something like this
set keywordprg=:Man
if !has("nvim")
source $VIMRUNTIME/ftplugin/man.vim
endif
The previous answer recommending cppman is the way to go. There is no need to install a bulky language server just for the purpose of having the hover functionality. However, make sure you're caching the man pages via cppman -c. Otherwise, there will be a noticeable delay since cppman is fetching the page from cppreference.com on the fly.
If you like popups for displaying documentation, convert the uncompressed man pages (groff -t -e -mandoc -Tascii <man-page> | col -bx), and set keywordprg to your own wrapper to search for keywords according to your needs.

Is there a way to set EOL to LF in Visual Studio for whole solution or project?

In Visual Studio you can set file's EOL to CRLF, LF, or CR, however you can do it only to a single file. I'm looking for a way that will make sure that every new file made in my solution will automatically use LF. Any ideas? Thanks in advance!
Adding an .editorconfig file in the root directory of the project (or solution) with the following entry should set line endings to LF by default (for newly added lines, see the notes below).
[*]
end_of_line = lf
Quoting from the Create portable, custom editor settings with EditorConfig page.
You can add an EditorConfig file to your project or codebase to enforce consistent coding styles for everyone that works in the codebase.
The editor in Visual Studio supports the core set of EditorConfig properties: [...]   end_of_line
When you add an .editorconfig file to a folder in your file hierarchy, its settings apply to all applicable files at that level and below.
When you add an EditorConfig file to your project in Visual Studio, new lines of code are formatted according to the EditorConfig settings. The formatting of existing code is not changed unless you run one of the following commands:
Code Cleanup (Ctrl+K, Ctrl+E), which applies any white space settings, such as indent style, and selected code style settings, such as how to sort using directives.
Edit > Advanced > Format Document (or Ctrl+K, Ctrl+D in the default profile), which only applies white space settings, such as indent style.
Note
If you are looking for a way to control the default translation mode for opening files in Windows, you can use _set_mode() or set the _fmode global variable documented here:
int _fmode = _O_BINARY;
Or at run time:
_set_mode(_O_BINARY); // defined in `<stdlib.h>`
There seems to be a way to set this more globally by modifying the Global state in the CRT, but the details are beyond my skill level in this environment.
Because default settings.json contain "files.eol": "auto", you can browse this under VSCode documentation. You need set The default end of line character to appropriate value, e.g.:

vi/vim - custom formatting depending on presence of special file or tag inside code

Question
Is there a simple/reliable way to have VIM, on a project/directory specific base, either detect a special file (ie: custom .vimrc with a couple settings), or to change run-time settings based on the presence of a special tag/string/hash in a comment at the beginning of a c source (.c) or header (.h) file? The string/hash must map to a function/setting in the .vimrc file, and must not contain the actual settings themselves.
Background
I have a mutli-developer project where we all have a common set of code style settings for our various editors (emacs and vim, primarily), and we all adhere strictly to these settings, such as newline style (CR versus CR+LF), indentation (length, hard-tabs versus expanded-as-spaces), and so on.
Problem
I'm creating a few new projects that, for reasons beyond our control (ie: static code analysis tool we have to use), will require different style settings than ours. There are ways to bypass this in the static code analysis tool, but there's a non-technical/legal requirement that we avoid disabling "features" of this tool.
For each of these new projects, I would like to somehow make vi/vim aware of some special flag, either by the presence of a special file in the root of the project's directory structure, or by a special keyword/tag/hash/etc I could put inside a /* C-style block comment */. When vi/vim is aware of the presence of this "trigger", I would want it to invoke a function to override the style settings for newlines, indentation, etc. If this is possible, is it also possible to have several, mutually exclusive such "triggers" so that everyone has a common .vimrc and the project determines which style to utilize?
Question - redux
Is there a straightforward way to accomplish this?
One solution: modelines (:help modeline) for Vim and file variables for Emacs.
Those are special comments you put in your files that are interpreted by your editor. You can use them to set indent style, file encoding, etc.
In my opinion, modelines are ugly noise.
One solution for Vim: .exrc (:help 'exrc').
You can put your project-specific settings in a .exrc file at the root of your project. The manual claims this solution is insecure but I fail to see how normal functioning adult could be beaten by it. YMMV.
One solution for Vim: directory-specific autocommands.
That's the safer alternative mentioned at the end of :help 'exrc' but it requires each contributor to add stuff to his own vimrc so… not that useful I guess.
The definitive solution: editorconfig.
You put your settings in a .editorconfig at the root of your project and let each contributor's IDE/editor deal with it.
... to change run-time settings based on the presence of a special
tag/string/hash in a comment at the beginning of a c source (.c) or
header (.h) file?
Yes, they're called modelines. http://vim.wikia.com/wiki/Modeline_magic
They can appear at the start or end of files.
An example from some C sources of mine:
/* vim:ft=c:expandtab:sw=4:ts=4:sts=4:
*/
See :help modeline in vim for more info.
Central configuration
If it's okay to configure the specific commands / local exceptions centrally, you can put such autocmds into your ~/.vimrc:
:autocmd BufRead,BufNewFile /path/to/dir/* setlocal ts=4 sw=4
It is important to use :setlocal instead of :set, and likewise :map <buffer> ... and :command! -buffer ....
On the other hand, if you want the specific configuration stored with the project (and don't want to embed this in all files via modelines), you have the following two options:
Local config with built-in functionality
If you always start Vim from the project root directory, the built-in
:set exrc
enables the reading of a .vimrc file from the current directory. You can place the :set ts=4 sw=4 commands in there.
Local config through plugin
Otherwise, you need the help of a plugin; there are several on vim.org; I can recommend the localrc plugin (especially with my own enhancements), which even allows local filetype-specific configuration.
Note that reading configuration from the file system has security implications; you may want to :set secure.
I've covered the main alternatives in this answer : https://stackoverflow.com/a/456889/15934 (Yes, your question is almost a duplicate: different formulation, but same solutions).
Modelines are really limited: you have to use a plugin to set things that are not vim options.
.exrc doesn't look behind the current directory
editorconfig is restricted to very specific options: don't expect to forward plugin specifications like where compilation directories are (this is how I support multiple compilation modes with CMake -- others prefer playing with ccache and tuning the CMakeCache, but this doesn't work well when using g++ and clang++ one after the other), how the linter shall be called, your naming conventions...
autocommand don't scale and cannot be ported easily from one directory to the other.
In the end, the best solutions are plugin based IMO: There a plenty plugin solutions see the non exhaustive list at the end of my local_vimrc plugin's README
Note also that since my previous answer, I've initiated another experiment to simplify project management. For instance, I introduce p:variables which are variables shared among all buffers belonging to a project.

Vim autocomplete from ctags for system headers only works when popup is triggered manually

On OS X, I generated a set of ctags for the system includes using the following command:
ctags -f c -h ".h" -R --c-kinds=+p --fields=+iaS --extra=+q /usr/include
This was run inside of a ~/.vim/ctags/ directory, where I put all of the ctags I generate for system-wide header files (I also have stuff for ROS and CPP that I load conditionally, but that's neither here nor there).
Anyway. The ctags file is set correctly in my .vimrc, and vim can definitely see the ctags, but for some reason the autocomplete popup will only display results from #included header files if I write out the entire symbol and then start backspacing. As an example, if I #include <string.h> in a project, and then I want to call strlen(), and I start to type str in to the active vim buffer, I will only get results for symbols that are currently in the vim buffer. But, if I type out strlen and then start backspacing one or two characters and hit <C-n>, the popup menu will be populated with matches from any other included header files.
EDIT: Turns out, if I just hit "s" then <C-n>, it works as well. So the problem seems to be that it only works if the popup menu is launched manually. Which makes me think that it's a plugin problem (see below)
Additional information:
completeopt is set to completeopt=menuone,menu,preview,longest
I have OmniCppComplete, which I suppose could be interfering with the behavior. It is currently not being conditionally loaded for C++ files only. If you want me to edit and post my OmniCppComplete settings from my .vimrc, just ask.
I also have AutoComplPop installed, but I haven't done anything to configure it, so it's running with its default settings. Haven't really researched the plugin, so no idea if some of it's behavior could be interfering with the results.
I have AutoTag and TagBar installed, but those should only be fiddling with the current directory's local tagfile.
I'm honestly pretty new to Vim, and I just have no idea where to start debugging this issue, whether it be with a random plugin or with my .vimrc settings.
Vim has many specific completion mechanisms.
<C-n> and <C-p> use many sources defined by the complete option. By default, they will provide completion using the current and all loaded and unloaded buffers, tags and included files. While you can usually get quite useful suggestions with these, it is a bit of a "catch-all" solution: it is not reliable at all if you work on reasonably large projects.
<C-x><C-]> uses only tags so it may be a little more useful to you.
And there are many more, see :h ins-completion.
Omni completion is smarter: it typically runs a custom filetype-specific script that tries hard to provide meaningful completion. It is triggered by <C-x><C-o> and you can read about it in :h ft-c-omni. Omni completion is often a better choice when working with code.
Because you have two overlaping "auto"-completion plugins it's hard to say what completion mechanism is at work. You should disable those plugins and play around with the different completion mechanisms available to you.
I have not mastered this yet, but I do think the following observation may be of help.
Vim's default auto complete which can be quite noisy, often gets in the way of what you call with <C-x><C-o>. Specifically, I found myself calling up my tags based completions with <C-x><C-o> only to have them replaced with continued typing with Vim's default suggestions using my open buffers.
The suggestion of shutting off one of the plugins makes sense. In my case the key was how to shut down Vim's default behavior. I have seen several people (and to which I now include myself), set the length of the expression to a high number before triggering Vim's default. For me that is:
let g:deoplete#auto_complete_start_length = 99
... this way you eliminate the default layer of completions that comes and goes regardless of the commands you intended to inform your work.
This still feels like a hack but it helps keep my work focused on the tag-based completions.
FYI: I use NVIM on a Mac.

How can I get Eclipse to index code inside #ifdef .... #endif

I'm using eclipse to work on some c code and it is not indexing code inside conditional compilation blocks like this:
#ifdef USE_FEATURE_A
int feature_a(...) {
some = code(here);
}
#endif
How can I get eclipse to index the feature_a function?
You could tell eclipse that USE_FEATURE_A is defined. Open your project properties and go to the "C/C++ General->Paths and Symbols" page, under the "Symbols" tab click the "Add" button and put USE_FEATURE_A in the name feild and click OK.
Note: this will cause it not to index any #else sides to your preprocessor stuff... so unless they are all like the one in question you can't AFAIK, but if they are they you're good. (Eclipse contains a C preprocessor that it uses to analyize your code all the stuff above does is essentially the same as adding -DUSE_FEATURE_A to your command line so Eclipse's preprocessor will behave differently from the one in your compiler)
This is an easier and in my opinion more elegant solution to the one selected as the solution:
If someone has the same problem (as I had), this can (now?) easily be solved by going to Window->Preference->C/C++/Indexer and enable "Index all header variants".
Then click Project->C/C++ Indexer->rebuild and clean and build your project. This should resolve all error originating from preprocessor commands.
For what it's worth, getting eclipse to parse conditionally compiled code is much harder to do than would appear at first glance. I found a paper on by IBM from 2007 where they said they will prioritize for the "next release".
Handling Conditional Compilation in CDT's Core
I had this same problem, but the code conditionally eliminated by preprocessing was perfectly valid c code and I wanted it formatted... This was my solution:
1) Global find/replace of #if to #JUNKif
2) Ctrl-Shift-F to reformat the source
3) Another global find/replace of #JUNKif to #if
One way to index code under flag in Eclipse(Kepler) c/c++Editor.
You can enable the compilation flags in Eclipse editor so that code under them can be indexed.
Properties > Preprocessor Include Paths > CDT User settings Entries
Click on ADD and add the Preprocessor Macro and you can specify its value.
Best way I guess is to use the Indexer option : Project Properties>C/C++ General>Indexer.
You can choose Enable project specific settings
I prefer choosing "Use active build configuration" so that all files which are actually built in the project are indexed.
Anyhow you can also choose to index all files in the project even if they are not included in the build ...

Resources