Emacs as an IDE for large C++ projects - c++

I am a Emacs newbie. I have to trying to search on how to use Emacs for use with large C++ projects particularly to index code and auto-complete function names and behave Eclipse-like. I had been using Vim for some time where I used ctags to index code in my project and Vim used to try auto-completing my code using a drop down menu of options. I am trying to achieve the same with Emacs now. But, during my search, results pointed to CEDET and auto-complete and other 3rd party plugins.
I tried to use ctags with ctags -e -R . and etags, but with no success.
Am I missing a default way of Emacs to achieve the same behavior? Which is the best and easiest way to achieve what I want?

I use CEDET with autocomplete successfully. Basically, autocomplete is the drop-down box provider, and it takes its sources from various things, most interestingly from CEDET (but also from etags and Gnu Global, which I recommend too).
A good starting point for CEDET is http://alexott.net/en/writings/emacs-devenv/EmacsCedet.html
Alex Ott's emacs config is there: https://github.com/alexott/emacs-configs -- it's an useful resource.
Note that you'll need to grab CEDET from bzr, and install/configure autocomplete correctly. I strongly recommend el-get to install autocomplete (and some other stuff too). You'll need to set up generic projects for EDE to have autocompletion working for random C/C++ files not part of a structured EDE project.
You'll have to spend some time to configure emacs, but it pays off. The tool is amazingly productive once set up correctly.

Indexing
You might want to use GNU/global instead of ctags: it supports C++ and is in my opinion more efficient with large projects (especially since you can update the index instead of rebuilding it from scratch). And it still is a lot simpler to use that CEDET/Semantic (which is also a fantastic tool if you spend the time to set it up).
Example use:
$ cd sources
$ gtags -v # create the index
$ cd subdirectory
$ [hack hack hack]
$ global -u # update the index (can be called from anywhere in the project)
In Emacs, activate gtags-mode in the source code buffers to get access to the gtags commands:
gtags-find-tag (M-.) : find the definition of the specified tag in your source files (gtags lets you choose between all possible definitions if there are several, or directly jumps if there is only one possibility)
gtags-pop-stack (M-*) : return to the previous location
gtags-find-rtag : find all uses of the specified tag in the source files
Below is my configuration for gtags, which automatically activates gtags-mode if an index is found:
;; gtags-mode
(eval-after-load "gtags"
'(progn
(define-key gtags-mode-map (kbd "M-,") 'gtags-find-rtag)))
(defun ff/turn-on-gtags ()
"Turn `gtags-mode' on if a global tags file has been generated.
This function asynchronously runs 'global -u' to update global
tags. When the command successfully returns, `gtags-mode' is
turned on."
(interactive)
(let ((process (start-process "global -u"
"*global output*"
"global" "-u"))
(buffer (current-buffer)))
(set-process-sentinel
process
`(lambda (process event)
(when (and (eq (process-status process) 'exit)
(eq (process-exit-status process) 0))
(with-current-buffer ,buffer
(message "Activating gtags-mode")
(gtags-mode 1)))))))
(add-hook 'c-mode-common-hook 'ff/turn-on-gtags)
Automatic completion
I don't know of any better tool than auto-complete. Even if it is not included within Emacs, it is very easily installable using the packaging system (for example in the marmalade or melpa repositories).

It depends what you are looking for in an IDE. I have been using Emacs for a fairly large C++ project. Of course you need to configure emacs to work as you want it to work in a greater extent they any other IDE.
But yes CEDET is a start, even though it is not perfect.
However there is a very good auto complete mode for Emacs http://cx4a.org/software/auto-complete/ it is not intelisense but it should integrate with CEDET in some way to give you a farily good auto complete.
Another important feature that I often use is the function ff-find-other-file to easy jump from header and implementation files.
Then of course you need to roll your own bulid. CEDET has some support for projects, but I have not tested it. However Emacs integrate well with command-line build tools such as make. Errors are printed in a buffer and you can jump to the correct line easily within Emacs.
GDB is also integrates well with Emacs M-x gdb, then just remember the gdb-many-windows command.

I recommend to watch Atila Neves lightning talk at CppCon 2015 titled Emacs as a C++ IDE.
For for details, see my answer to this related question.

See https://emacs.stackexchange.com/questions/26518/sequence-of-packages-to-be-installed-to-make-emacs-an-ide-for-c-c
I use GNU Global and two popular Emacs plugins:
company for code completion
emacs-helm-gtags for code navigation

Related

Custom autoformat in Xcode [duplicate]

As a C# developer, I have become highly dependent on the automatic formatting in Visual Studio 2008. Specifically, I will use the CTRL + K , D keyboard shortcut to force things back into shape after my sloppy implementation.
I am now trying to learn Objective-C and am missing certain features in Xcode, but probably none are quite as painful as the formatting shortcut. My Google searches have yielded nothing built in, though it seems there are some hacks. Am I missing something or does this feature not exist natively in Xcode?
That's Ctrl + i.
Or for low-tech, cut and then paste. It'll reformat on paste.
Unfortunately, Xcode doesn't have anything nearly as extensive as VS or Jalopy for Eclipse available. There are SOME disparate features, such as Structure > Re-Indent as well as the auto-formatting used when you paste code into your source file. I am totally with you, though; there definitely should be something in there to help with formatting issues.
I'd like to recommend two options worth considering. Both quite new and evolving.
ClangFormat-Xcode (free) - on each cmd+s file is reformatted to specific style and saved, easy to deploy within team
An Xcode plug-in to format your code using Clang's format tools, by
#travisjeffery.
With clang-format you can use Clang to format your code to styles such
as LLVM, Google, Chromium, Mozilla, WebKit, or your own configuration.
Objective-Clean (paid, didn't try it yet) - app raising build errors if predefined style rules are violated - possibly quite hard to use within the team, so I didn't try it out.
With very minimal setup, you can get Xcode to use our App to enforce
your rules. If you are ever caught violating one of your rules, Xcode
will throw a build error and take you right to the offending line.
In xcode, you can use this shortcut to Re-indent your source code
Go to file, which has indent issues, and follow this :
Cmd + A to select all source codes
Ctrl + I to re-indent
Hope this helps.
My personal fav PrettyC wantabe is uncrustify: http://uncrustify.sourceforge.net/. It's got a few billion options however so I also suggest you download UniversalIndentGUI_macx, (also on sourceforge) a GUI someone wrote to help set the options the way you like them.
You can then add this custom user script to uncrustify the selected text:
#! /bin/sh
#
# uncrustify!
echo -n "%%%{PBXSelection}%%%"
/usr/local/bin/uncrustify -q -c /usr/local/share/uncrustify/geo_uncrustify.cfg -l oc+ <&0
echo -n "%%%{PBXSelection}%%%"
You can use Command + A to select all content and next Ctrl + I to format the selected content.
I also feel xcode should have this function.
So I made an extension to do it: Swimat
Simple install by brew cask install swimat
You can give it a try, see https://github.com/Jintin/Swimat for more information.
Cmd A + Ctrl I
Or Cmd A And then Right Click. Goto Structure -> Re-Indent
Consider buying yourself a license for AppCode, an intelligent Objective-C IDE that helps iOS/OS X developers. AppCode is fully compatible with Xcode, but goes beyond Xcode in adding powerful features.
AppCode an Objective-C variant of the Intellij IDEA IDE from JetBrains. They are also authors of popular ReSharper extension to Visual Studio, which main purpose from here seems like a desperate attempt to bring a touch of IDEA experience to a Microsoft product.
AppCode is using its own code analyser which gives close-to-perfect refactoring and code navigation support. There is an ability to re-indent and completely reformat code also (although I still keep missing a couple of formatting settings in hard cases, but mostly it works well).
You might try the trial version, of course.
Swift - https://github.com/nicklockwood/SwiftFormat
It provides Xcode Extension as well as CLI option.
CTRL + i
that's it.
(no COMMAND + i)
You can also have a look at https://github.com/octo-online/Xcode-formatter which is a formatter based on Uncrustify and integrated into Xcode. Works like a charm.
You could try that XCode plugin https://github.com/benoitsan/BBUncrustifyPlugin-Xcode
Just clone github repository, open plugin project in XCode and run it. It will be installed automatically. Restart Xode before using formatter plugin.
Don't forget to install uncrustify util before. Homebrew, for exmaple
brew install uncrustify
P.S. You can turn on "after save formatting" feature at Edit > Format Code > BBUncrustifyPlugin Preferences > Format On Save
Hope this will be useful for u ;-)
I suggest using ClangFormat. In order to install, please follow these steps:
Install Alcatraz package manager for XCode
Supports Xcode 5+ & OS X 10.9+
After installation restart XCode.
Open XCode -> Window Menu -> Package Manager
Search (find) ClangFormat and install it. After installation again restart XCode.
Now at XCode menu you can use Edit -> Clang Format submenu for formatting.
You can choose different types of formatting. Also by enabling Format On Save you can gain auto-format capability.
If your Xcode version 3.x , you should use "User Script" With Uncrustify , here this a Example:
#!/bin/sh
echo -n "%%%{PBXSelection}%%%"
$YOURPATH_TO_UNCRUSTIFY/uncrustify -q -c $YOURPATH_TO_UNCRUSTIFY_CONFIG/CodeFormatConfig.cfg -l OC+
echo -n "%%%{PBXSelection}%%%"
add above to your Xcode "User Script".
if Xcode version 4.x , I think you should read this blog : Code Formatting in Xcode 4,
In this way , used the "Apple Services" , but it's not good enough , cause too slow experience, does anyone has the same thing ?
why apple drop "user script" .... xD
First, Examine XCode Preferences "Indentation" section. You can customize things quite a bit there...
For more fine grained control, refer to the XCode User Defaults document from apple. (May require a developer login to view). For example, I was able to disable the "indent on paste" by entering the following in terminal:
defaults write com.apple.XCODE PBXIndentOnPaste No
to read back your setting:
defaults read com.apple.XCODE PBXIndentOnPaste
This only works for languages with are not whitespace delineated, but my solution is to remove all whitespace except for spaces, then add a newline after characters that usually delineate EOL (e.g. replace ';' with ';\n') then do the ubiquitous ^+i solution.
I use Python.
Example code, just replace the filenames:
python -c "import re; open(outfile,'w').write(re.sub('[\t\n\r]','',open(infile).read()).replace(';',';\n').replace('{','{\n').replace('}','}\n'))"
It 's not perfect (Example: for loops), but I like it.
We can use Xcode Formatter which uses uncrustify to easily format your source code as your team exactly wants to be!.
Installation
The recommended way is to clone GitHub project or download it from https://github.com/octo-online/Xcode-formatter and add the CodeFormatter directory in your Xcode project to get :
Xcode shortcut-based code formatting: a shortcut to format modified sources in the current workspace
automatic code formatting: add a build phase to your project to format current sources when application builds
all sources formatting: format all your code with one command line
your formatting rules shared by project: edit and use a same configuration file with your project dev team
1) How to setup the code formatter for your project
Install uncrustify
The simplest way is to use brew:
$ brew install uncrustify
To install brew:
$ ruby –e “$(curl –fsSkl raw.github.com/mxcl/homebrew/go)”
Check that uncrustify is located in /usr/local/bin
$ which uncrustify
If your uncrustify version is lower than 0.60, you might have to install it manually since modern Objective-C syntax has been added recently.
Add CodeFormatter directory beside your .xcodeproj file
Check that your Xcode application is named "Xcode" (default name)
You can see this name in the Applications/ directory (or your custom Xcode installation directory). Be carefull if you have multiple instances of Xcode on your mac: ensure that project's one is actually named "Xcode"!
(Why this ? This name is used to find currently opened Xcode files. See CodeFormatter/Uncrustify_opened_Xcode_sources.workflow appleScript).
Install the automator service Uncrustify_opened_Xcode_sources.workflow
Copy this file to your ~/Library/Services/ folder (create this folder if needed).Be careful : by double-clicking the .workflow file, you will install it but the file will be removed! Be sure to leave a copy of it for other users.
How to format opened files when building the project
Add a build phase "run script" containing the following line:
sh CodeFormatter/scripts/formatOpendSources.sh
How to format files in command line
To format currently opened files, use formatOpenedSources.sh:
$sh CodeFormatter/scripts/formatOpendSources.sh
To format all files, use formatAllSources.sh:
$sh CodeFormatter/scripts/formatAllSources.sh PATH
PATH must be replaced by your sources path.
E:g; if project name is TestApp then the command will be
$sh CodeFormatter/scripts/formatAllSources.sh TestApp
it will look for all files in the project and will format all the files as configured in uncrustify_objective_c.cfg file.
How to change formatter’s rules
Edit CodeFormatter/uncrustify_objective_c.cfg open with TextEdit
Well I was searching for an easy way. And find out on medium.
First to copy the json text and validate it on jsonlint or something similar. Then to copy from jsonlint, already the json is formatted. And paste the code on Xcode with preserving the format, shortcut shift + option + command + v

set Vim as a basic C++ Editor [duplicate]

This question already has answers here:
Configuring Vim for C++
(3 answers)
Closed 9 years ago.
I want to set Vim to work with C++, I just want to perform these tasks:
write code (you don't say?)
check and highlight C++ syntaxis
autocompletion (if is possible)
compile, run, debugging and return to the editor
tree-view project files on the side
statusbar
I know that much of this tasks can be done with plugins, so I need your help to make a list of required plugins and how to set them up together.
why basic? well, I'm taking the programming course level 1 in my university, and we will make simple command-line programs, simple such a mathematical evaluations (functions, array even or odd numbers, draw triangles with asterisks and so.)
I don't think you need any plugins... the features you want are already there.
-write code (you don't say?)
this is a given
-check and highlight C++ syntax
:syntax enable
-autocompletion (if is possible)
in insert mode, try
ctrl-n
ctrl-p
-compile, run, debugging and return to the editor
vim is an editor, not a complier. You can, however, drop into a shell to run these commands or use :!commandname. Try one of the following
ctrl-z
g++ -o myprogram myprogram.cpp
fg
or
:!g++ -o myprogram myprogram.cpp
or just keep another terminal open.
-tree-view project files on the side
:!tree -C | less -R
-statusbar
already at the bottom. Try gvim for more toolbars et cetra.
Have fun!
BTW - this message was brought to you via vim and pentadactyl
Some plugins that might help you and I tried in the past when I was trying to get started with vim long ago:
IDE: http://www.vim.org/scripts/script.php?script_id=213
Tree view: http://www.vim.org/scripts/script.php?script_id=1658
Debugging: http://www.vim.org/scripts/script.php?script_id=3039
Completion: http://ctags.sourceforge.net/ and http://www.vim.org/scripts/script.php?script_id=1520
Statusbar: http://www.vim.org/scripts/script.php?script_id=3881 and its successor http://usevim.com/2013/01/23/vim-powerline/
You can search for further plugins at http://www.vim.org/scripts/index.php
That being said, I use vim just fine without any plugin for daily C++ development. It is also handy because I can use the same workflow when ssh'ing onto a server or someone else's machine without the consideration of major differences.
Also C++ syntax highlight works by default as such plugins for languages are usually included into the distributed vim, already.

how to install cc-mode-5.32.3? (hightling in C++ mode of emacs)

I am editting my C++ program on a unix cluster by using emacs. I wanna emacs to highlight key words in C++. After searching online, I decide to install cc-mode-5.3.3. But I stuck here:
follow the readme instruction at http://cc-mode.sourceforge.net/src/README
After byte compiling, I don't understand
Put the compiled files somewhere (X)Emacs will find them, i.e. in
some path that's in the load-path variable. You must make sure
they are found before any CC Mode files which are distributed with
(X)Emacs. A directory has higher precendence than all directories
after it in the load-path list.
GNU Emacs comes together with cc-mode installed by default, so you don't need to install it manually. To enable symbols hightlighting, you need to set variable global-font-lock-mode to true value, for example, by using M-x customize-variable global-font-lock-mode, switching it to t, and pressing Apply and Save.
P.S. Are you running Emacs in console, or in graphical mode? If in console, then you could be need to setup corresponding font-lock faces. Use the M-x customize-face command to set faces whose names are starting with font-lock-

Setting up vim as C++ IDE

I wish to setup vim as C++ IDE so I can do all work from it.
I'm using these plugins for vim:
Clang complete - accurate completion
nerdtree - browse files
snipmate - insert snippets
AutoComplPop - omni-completion
buffergator - buffer management
vim-powerline - nice statusbar
vundle - to manage plugins
But I lack things like Jump to definition and compiling multiple files in one executable, project view...
I'm using
nmap <F8> :w % <bar> :!g++ -W -Wall -Wextra -pedantic -std=c++11 % -o %:t:r<CR> <bar> :!./%:t:r<CR>
to compile current file, but it won't work if there are multiple file that create one executable.
I know I could just use eclipse, netbeans, code::blocks and such, but I really like vim... If such thing as vim ide isn't possible do I have to learn GNU build system or some other method?
Any advice is welcome.
You need to create a makefile which handles the build process.
Then from vim just run :make, it will run the build and pop all errors in quickfix window where you can navigate and jump to error locations.
First, to jump to definitions, you might try this:
http://www.santiagolizardo.com/article/vim-jump-to-classes-and-functions-defined-in-different-files/64003
I haven't tested it, so I can't tell you if it works.
Now, to build multiple file projects, it might be better for you to learn how to use makefiles and automake. These links might help you:
http://homepages.gac.edu/~mc38/2001J/documentation/g++.html
http://www.openismus.com/documents/linux/automake/automake
Good luck.
Edit: A similar question was answered on this link: https://stackoverflow.com/a/563992/1820837
"Jump to definition" is already there, it's <C-]> with the cursor on a keyword or :tag foo on the command line.
For these to work, you need a tags file generated by exuberant-ctags and to tell Vim where to find it. See :help tags and :help ctags.
Without a tags file, gd goes to the definition of the keyword under your cursor if it's in the same file. But it's not as generally useful as <C-]>.
For "Jump to definition" I can recommend the YouCompleteMe, plugin which is really easy to setup with vundle.
Otherwise there is also ctags, but I find it less useful.
To use vim as a IDE, I find this post useful.

Using Eclipse CDT from command line

I need to have some of my C++ classes, functions and namespaces renamed as a part of my build script, which is runned by my CI system.
Unfortunatly a simple sad/awk/gsar/... technique is not enough, and I need smart rename refactoring, that carefully analyses my code.
Actually I found out, that CDT C/C++ rename refactoring does, what I need. But it does it from Eclipse IDE. So I need to find a way to start it from command line, and to make it a part of my CI build script.
I know that Eclipse has eclipsec executable, that allowes running some Eclipse functions from command line (see e.g. here).
But I can't find any suitable documentation for functions, CDT exports to command line. The only thing, I found is the this. But it doesn't solve my problem.
So, I need help to run CDT rename refactoring from command line (or someway like that). If it is not possible, may be someone will advice another tool, that can do rename refactoring for C++ from command line ?
Pragmatic Approach
"I need to have renamed as a part of my build script"
This sounds a bit like a design problem. However, I remember having been guilty of the same sin once writing a C++ application on AIX/Win32: most notably, I wanted to be able to link 'conflicting' versions of shared objects. I solved it using a simple preprocessor hack like this:
# makefile
#if($(ALTERNATIVE))
CPPFLAGS+=-DLIBNAMESPACE=MYLIB_ALTERNATIVE
#else
CPPFLAGS+=-DLIBNAMESPACE=MYLIB
#endif
./obj64/%.o: %cpp
xlC++ $(CPPFLAGS) $^ -o %#
Sample source/header file:
namespace MYLIB
{
class LibService :
{
};
}
As you can see, this required only a single
find -iname '*.[hc]pp' -o -iname '*.[hc]' -print0 |
xargs -0 sed -i 's/OldNamespace/MYLIB/g'
Eclipse Automation
You could have a look at eclim, which does most, if not all, of what you describe, however it targets the vim editor.
What eclim boasts, is full eclipse intergration (completion, refactoring, usage search etc.) from an external program. I'm not fully up to speed with the backend of eclim, but I do know that it works with a eclimd server process that exposes the service interface used by the vim plugin.
I suspect you should be able to reuse the code from eclimd if not just use eclim for your purposes.
We are completing a command-line rename tool for C++, that uses compiler accurate parsing and name resolution, including handling of shadowed names. Contact me (see bio) for further details or if you might be interested in a beta.