Commit df5d6b97 authored by Francisco Lopes's avatar Francisco Lopes
Browse files

Reorganize old URLs

parent 471824f9
+++
type = "post"
title = "better completion for c++"
description = "My endeavours in obtaining C++ code-completion in Vim"
date = "2015-01-29"
tags = ["cpp", "clang", "libclang", "completion", "intellisense", "vim", "ycm"]
+++
I have landed some improvements to Clang so that it can provide better code
completion for C++:
<a href="https://s3.amazonaws.com/f.cl.ly/items/1e2F0A123h331c1G0L0R/SadBart.gif">
![YouCompleteMe GIF](https://s3.amazonaws.com/f.cl.ly/items/2P0b0c3N2m2m2l2L273B/SadBart-Small.gif)
</a>
This comes in Clang 3.7 revision 227309. The specific area improved regards
parametric information that can be useful when inserting arguments.
This functionality can be easily tried in the command line using the
`c-index-test` tool that comes with Clang. For example, for the following code:
~~~ cpp
#include <iostream>
template <class T>
class SadBart {
public:
SadBart(T lesson) : lesson(lesson) {
}
template <class U>
void operator()(std::ostream &os, U width, U height) {
while (height --> 0) {
auto w = width;
while (w --> 0)
if (w > 0)
os << lesson << ' ';
else
os << lesson;
os << '\n';
}
}
private:
T lesson;
};
int main() {
SadBart<int>(42)(std::cout, 4, 2);
} ^ ^ ^ ^
~~~
these are the relevant results when running `c-index-test` using the four spots
highlighted in the source code:
c-index-test -code-completion-at=playground.cpp:27:18 playground.cpp
OverloadCandidate:{Text SadBart}{LeftParen (}{CurrentParameter int lesson}{RightParen )} (1)
OverloadCandidate:{Text SadBart}{LeftParen (}{CurrentParameter const SadBart<int> &}{RightParen )} (1))})}
c-index-test -code-completion-at=playground.cpp:27:22 playground.cpp
OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{CurrentParameter std::ostream &os}{Comma , }{Placeholder U width}{Comma , }{Placeholder U height}{RightParen )} (1)
c-index-test -code-completion-at=playground.cpp:27:32 playground.cpp
OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{Placeholder std::ostream &os}{Comma , }{CurrentParameter U width}{Comma , }{Placeholder U height}{RightParen )} (1)
c-index-test -code-completion-at=playground.cpp:27:35 playground.cpp
OverloadCandidate:{ResultType void}{Text operator()}{LeftParen (}{Placeholder std::ostream &os}{Comma , }{Placeholder int width}{Comma , }{CurrentParameter int height}{RightParen )} (1))}
A new `CXCursorKind` is provided in the libclang API,
`CXCursor_OverloadCandidate`, so that one can grab the results that refer
specifically to the overloads that apply for the current context.
For more details about the Vim plugin check
[my YouCompleteMe fork][oblitum-ycm].
<sub> For argument hints a little bit faster than official Clang take a look at
[this change][faster-candidates] I'm mantaining at
[a branch in my own fork][oblitum-clang]. You can use it if you care about some
milliseconds. </sub>
<sub> Knows someone that needs a programmer? Please [drop me a line][resume]!
</sub>
[oblitum-ycm]: https://github.com/oblitum/YouCompleteMe
[faster-candidates]: https://github.com/oblitum/clang/compare/faster-overload-candidates
[oblitum-clang]: https://github.com/oblitum/clang/tree/faster-overload-candidates
[resume]: http://www.oblita.com/resume/
../post/better-completion-for-cpp.mmark
\ No newline at end of file
+++
type = "post"
title = "my vim gems"
description = "A handful of VIM gems"
date = "2013-09-21"
tags = ["vim", "tips"]
+++
Here are some personal tips I've wrapped up:
__1.__ Use a plugin manager, it'll make your life much easier. I use
[VAM](https://github.com/MarcWeber/vim-addon-manager) which offers
good support for git and mercurial plugin repositories, but also
offers its own curated plugin list and installation from
self-contained directories.
__2.__ For the following tips, simplified clipboard usage is
required:
~~~ vim
set clipboard=unnamedplus " for simplified clipboard copy/paste
~~~
__3.__ Use [vim-shell](https://github.com/xolox/vim-shell) for
fullscreen GVIM:
~~~ vim
call vam#ActivateAddons(['github:xolox/vim-shell'])
~~~
__4.__ Put the following command on your `.vimrc` so that on
fullscreen you don't get weirdly colored borders in GVIM:
~~~ vim
" Fix borders of fullscreen GUI
if has('gui_gtk') && has('gui_running')
let s:border = synIDattr(synIDtrans(hlID('Normal')), 'bg', 'gui')
exe 'silent !echo ''style "vimfix" { bg[NORMAL] = "' . escape(s:border, '#') . '" }'''.
\' > ~/.gtkrc-2.0'
exe 'silent !echo ''widget "vim-main-window.*GtkForm" style "vimfix"'''.
\' >> ~/.gtkrc-2.0'
endif
~~~
As GVIM starts, that will generate a `~/.gtkrc-2.0` file that will
fix background color for GVIM GTK windows taking the current
background color of your colorscheme (so, set the colorscheme before
this code).
Example output:
~~~ vim
style "vimfix" { bg[NORMAL] = "#002b36" }
widget "vim-main-window.*GtkForm" style "vimfix"
~~~
If you use `.gtkrc-2.0` with other configurations beyond this, you
should adapt the script, this is the only use I have for `.gtkrc-2.0`.
__5.__ Export code with syntax highlighting to HTML. I've aways used
`:TOhtml` for that, but I've switched to the more powerful
[format.vim](http://sourceforge.net/projects/formatvim/). For
install, on my `.vimrc` I do (using VAM):
~~~ vim
call vam#ActivateAddons(['hg:https://bitbucket.org/ZyX_I/frawor'])
call vam#ActivateAddons(['hg:http://hg.code.sf.net/p/formatvim/code'])
~~~
It supports exporting not only to HTML, but also LaTeX and
other formats. I also add the following extra configuration for
exporting with the font I'm currently using:
~~~ vim
" format.vim Setup
let g:format_HTMLAdditionalCSS = '@import url(http://fonts.googleapis.com/css?family=Droid+Sans+Mono);' .
\' body { font-family: "Droid Sans Mono"; font-size:11pt; line-height: 120%; -webkit-font-smoothing: antialiased }'
~~~
__6.__ Create Gists from your code with [gist.vim](https://github.com/mattn/gist-vim):
~~~ vim
call vam#ActivateAddons(['github:mattn/gist-vim']))
~~~
__7.__ With the help of format.vim and gist.vim, you can use the
[bl.ocks.org](http://bl.ocks.org) web site to host code snippets using
your colorscheme. To do that, add the following command (`Blocks`) to
your `.vimrc`:
~~~ vim
" Gist it to bl.ocks.org
command! -range=% Blocks
\ <line1>,<line2>Format format | f index.html | exe 'Gist -a' | bd! |
\ let @+ = 'http://bl.ocks.org/anonymous/raw/' . matchstr(@+, 'https://gist.github.com/\zs\w\+\ze') . '/' |
\ redraw | echomsg 'Done: ' . @+ | setlocal nomodified
~~~
This will create an anonymous gist (`Gist -a`) from your current
selection (or if there's no selection, use all the buffer) exported to
HTML, and then use bl.ocks.org as the viewer of that HTML, after the
command finishes, the temporary buffer with HTML output is destroyed
and you get the bl.ocks.org url of your code snippet (on your clipboard)
using your exact colorscheme.
For example,
- generated with selection (`:'<,'>Blocks`):
[6672885](http://bl.ocks.org/anonymous/raw/9389654/)
- generated from buffer (`:Blocks`):
[6672894](http://bl.ocks.org/anonymous/raw/9389579/)
__8.__ Make the QuickFix window take all the lower section of the
screen when there're multiple windows open, so that it stops showing
up only bellow a particular window:
~~~ vim
" QuickFix Window
au FileType qf wincmd J " Open QuickFix horizontally
~~~
__9.__ Paste block selection without overwriting contents:
~~~ vim
function! FancyPaste(reg)
let paste = split(getreg(a:reg), '\n')
let spaces = repeat(' ', virtcol('.')-1)
call map(paste, 'spaces . v:val')
call append(line('.'), paste)
endfunction
" Paste block while inserting new lines to hold it
nnoremap <Leader>p :call FancyPaste('"')<CR>
nnoremap <Leader>P :call FancyPaste('+')<CR>
~~~
The previous creates two mappings, `<Leader>p` and `<Leader>P`, that
will paste text indenting it according to the position of the pasting
location, the first map is for yanked text in VIM, the second is for
text from other applications in clipboard.
__10.__ Edit the contents of special buffers:
~~~ vim
" Edit command output in a buffer
command! -nargs=+ BufOut redir => bufout | silent <args> | redir END | new | call append(0, split(bufout, '\n'))
" :Me[ssages] as shorthand for `:BufOut :messages' (the dominant use case of :BufOut)
command! -nargs=0 Messages :redir => bufout | silent :messages | redir END | new | call append(0, split(bufout, '\n'))
~~~
The first command (`BufOut`) is for getting output of a general
special buffer passed as argument into a new buffer. The second
(`Messages`) is a shortcut for getting output from the `messages`
buffer, the one with error logs, etc.
---
For reference, this is my [.vimrc](https://gist.github.com/oblitum/5565974).
../post/my-vim-gems.mmark
\ No newline at end of file
+++
type = "post"
title = "on value semantics"
description = "A trivial comparison of yeppp! against compilers"
date = "2014-02-16"
tags = ["cpp", "cpp1y", "modern cpp", "boost", "range"]
+++
2013 Keynote: Optimizing the Emergent Structures of C++ <sub> -- Chandler Carruth</sub>
<div class="video-container">
<iframe src="//www.youtube.com/embed/eR34r7HOU14?start=2565" frameborder="0"> </iframe>
</div>
42:45:
> You don't need output parameters, we have value semantics in C++ [...].
> Anytime you see someone arguing that "nonono I'm not going to return by value
> because copy would cost too much", someone working on an optimizer says
> they're wrong. All right? I have never yet seen a piece of code where that
> argument was correct. [...] People don't realize how important value semantics
> are to the optimizer because it completely clarifies the aliasing scenarios.
~~~ python
import re
for i in range(1000000):
re.split(' +', 'a b c')
~~~
The previous python code is twice as fast than the following c++ code (which
uses libc++'s regex implementation):
~~~ cpp
#include <regex>
#include <vector>
#include <string>
using namespace std;
vector<string> split(const string &s, const regex &r) {
return {
sregex_token_iterator(begin(s), end(s), r, -1),
sregex_token_iterator()
};
}
int main() {
const regex r(" +");
for(int i = 0; i < 1000000; ++i)
split("a b c", r);
return 0;
}
~~~
It's easy to spot the performance problem here, the c++ version allocates
strings to fill a vector which itself is allocated/destroyed in each iteration
of the loop, while the python version should just be doing the right thing:
building string slices over the single original string.
The trivial _naive_ way to solve the issue with the c++ code is using parameters
by reference for output:
~~~ cpp
#include <regex>
#include <vector>
#include <string>
using namespace std;
void split(const string &s, const regex &r, vector<string> &v) {
auto rit = cregex_token_iterator(s.data(), s.data() + s.length(), r, -1);
auto rend = cregex_token_iterator();
v.clear();
while(rit != rend) {
v.push_back(*rit);
++rit;
}
}
int main() {
const regex r(" +");
vector<string> v;
for(int i = 0; i < 1000000; ++i)
split("a b c", r, v);
return 0;
}
~~~
This avoids all the abusive string allocations/destructions, the vector grows
its memory just once. Still, we could have string slices over the original
string instead of allocating memory for the token substrings and there's now
this awkward interface, it's not as natural as the python version of `split`
which uses a return value as output.
How do we solve this?
Here's a sample solution that's built upon three key components, a `string_view`
implementation, ranges and an iterator adaptor:
~~~ cpp
#include <string>
#include <string_view>
#include <boost/regex.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/iterator/transform_iterator.hpp>
using namespace std;
using namespace std::experimental;
using namespace boost;
string_view stringfier(const cregex_token_iterator::value_type &match) {
return {match.first, static_cast<size_t>(match.length())};
}
using string_view_iterator =
transform_iterator<decltype(&stringfier), cregex_token_iterator>;
iterator_range<string_view_iterator> split(string_view s, const regex &r) {
return {
string_view_iterator(
cregex_token_iterator(s.begin(), s.end(), r, -1),
stringfier
),
string_view_iterator()
};
}
int main() {
const regex r(" +");
for (int i = 0; i < 1000000; ++i) {
split("a b c", r);
}
}
~~~
A `transform_iterator` is an adaptation of another base iterator which changes
of behavior only when being dereferenced. When dereferenced, what is obtained is
the result of a call to a given function over the original dereferentiation. Its
use here is to adapt a `cregex_token_iterator` to get `string_view`s at
dereferentiation, instead of match objects or full-fledged strings.
With our special `string_view_iterator` operating through the `stringfier`
function we can use it to initialize an `iterator_range` which builds a range
over a pair of iterators. We end up with a range of `string_view`s which are
lazy matches, since the matches will actually happen only when iterating over
the range. This version is much faster (even if we filled a `vector` using the
returning range) and doesn't lose for the output parameter version in
performance.
In context to Chandler's talk, this solution shouldn't make a difference in
helping the optimizer clarify the aliasing scenarios, but it obtains perfomance
on par or better than output through parameter by reference.
The final result is faster than python as expected. I'm not sure I can call this
_value semantics_ because it's all references over the place, the original
inefficient solution returning a vector of strings seems more into the _semantic
of values_.
Notice also that Boost.Regex is currently twice as fast as libc++ regex
implementation.
More information in the following references, particularly the `std::split`
proposal which is similar to the solution presented here.
## References
- [c++11 regex slower than python](http://stackoverflow.com/q/14205096)
- [value semantics vs output params with large data structures](http://stackoverflow.com/q/21669155)
- [`string_view`: a non-owning reference to a string, revision 7](http://isocpp.org/files/papers/N3921.html)
- [`std::split()`: An algorithm for splitting strings](http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3593.html)
- [Marshall Clow's `string_view` implemetation for libc++](https://github.com/mclow/string_view)
../post/on-value-semantics.mmark
\ No newline at end of file
+++
type = "post"
title = "the m$ redemption"
description = "Rumblings while drunk"
date = "2014-04-05"
tags = ["microsoft", "foss"]
+++
Under Satya Nadella, microsoft looks like taking a new breath, they have made
Windows for mobile free-of-charge, really a small step since, well, few people
care about Windows mobile. Both OS X and Linux are free-of-charge, let's not
even talk about free-of-speech. But, hey, they have
[open sourced .net](https://roslyn.codeplex.com/) implementation... that's a
big step. I really don't know under which terms it's open now, since we're
talking about M$, one should take care. Anyway, it looks like an improvement.
So, under this new vision, what M$ shoud do next?
- Currently, their free-of-charge IDE Version, Visual Studio Express, is
limited by usage of plugins. IMO, this is really a VERY dumb model, creativity
comes from the community. At last, it's very willing to come from it, but
anyway, M$ prefers to make IDE plugins available only to paid customers of
Visual Studio, which is sad since FOSS plugin initiatives can only honestly
help paid onwers. This model is only "smart" in the sense of using express
editions to lure users so they aftwards become addicts to buy a paid version.
This must be fixed, express editions should allow plugins.
- Kernel development in Windows is WEIRD. Right now it means you must have
a paid version of Visual Studio to have the environment for developing drivers.
Not only that, since now drivers must be signed to be used, a kernel developer
must seek how to buy a certificate to sign its binaries, so anyone can load
them. This comes through a third party signing authority service, which you
must pay for. Can this be more unfriendly?... Please solve this.
- Stop trying to bury OpenGL please, stop giving dubious excuses for not
supporting WebGL. DirectX may be well adopted, but now, it seems like it'll
never reach the status of OpenGL across desktop, mobile and consoles. As of
now, it seems at last WebGL is being accepted in IE11, anyway... throughout
the years I've heard OpenGL support would be dropped in Vista, not adopted
in browsers, etc. OpenGL can't be buried now, since you're not the single
player anymore, so, embrace it.
- Stop with the license "small letters", where it's uncovered that, in the end,
you're always seeking to take advantage over others, see [this recent instance
for example](http://haacked.com/archive/2013/06/24/platform-limitations-harm-net.aspx/).
I won't come back to Windows any time soon, since it doesn't provides multiple
desktops, a worth command line, nor a worth package manager, anyway, as I have
used Windows before, and may still use it some time, having those things figured
out would be helpful.
Feel free to add more redemptions points in comments!
../post/the-m-redemption.mmark
\ No newline at end of file
+++
type = "post"
title = "why I use linux"
description = "My ramblings on why I choose Linux"
date = "2013-09-25"
tags = ["linux"]
+++
## Reason 1: Philosophy
I simply got tired of seeing microsoft throwing disposable technology
to just remove support, deprecate or whatever afterwards. Release
"free" stuff and then, you know what happens...
Time for quoting some early microsoft employ,
[one of the original heads of Direct X division](http://www.shacknews.com/article/46338/alex-st-john-interview),
let's look at the roots of this:
>This is all great stuff, you have a perfect plan. Developers who are
>reasonable should all support it, but what do you do if none of this
>works.
>
>What do you mean?
>
>What if in spite of your best efforts, your best arguments, you best
>relationships, you can't get them to support them. How do you force
>the industry to support Microsoft anyway?
>
>Force them? Well, I don't know.
>
>Come back when you have a plan that answers that question.
>
>---
>
>That perplexed me for a long time. I'm thinking, "What the hell does
>he mean, force them? I can't hold a gun to their head, so how do I
>put all these companies in a position where, regardless of what they
>see is in their best interest, they have to adopt your technology?"
>
>That experience had a major impact on my thinking.
>
>I realized that a major part of my job was to figure out how to use
>technology control to create economic force, or leverage, such that
>money and business flowed in Microsoft's direction, and people had to
>go [to them]. That, ultimately, is when I became a "Microsoft guy,"
>when I got that concept.
Well, I'm more aligned with GNU than that. I'm also tired of
learning how microsoft likes to play the good guy to screw everything up later.
I think now they're trying [to play](http://haacked.com/archive/2013/06/24/platform-limitations-harm-net.aspx)
the good guy in the open source space... such a joke!
I'm happy to see a come back of the OpenGL, in the past I felt sad
seeing graphics on Windows evolving purposely not supporting OpenGL
and the alternative for the rest of the world stall. Those days are
now gone. The world has changed. Mobile graphics matter. I'm just
trilled with the SteamOS announcement by Valve, it may shake things up
in the gaming space, I already play some games through Steam, but
availability still doesn't compare. And last, but not least, OpenGL is
active again.
Talking about announcements, I've also pledged for the Ubuntu Edge.
Even if it doesn't catch, Canonical proposal of convergence is more
coherent, [contrary to microsoft tentatives till now](http://motls.blogspot.com.br/2013/09/windows-8-lack-of-progress-and-end-of.html).
## Reason 2: Sincerely Friendly
I started computing on Windows, and spent most of my programming
career working on it, even developed drivers, and by now, almost
abandoned it.
In the meantime I used linux distributions in rare occasions, because
of job related stuff and to my surprise, started finding stuff I
missed on Windows, or which I even had no idea existed, like multiple
workspaces.
I then bought a macbook pro and initially found it quite nice, it got
a decent shell, contrary to Windows which has its _very_ limited
command prompt, or the much late powershell, which is quite a weird
creature in the shell world. I found OS X touchpad gestures awesome,
and it also had multiple workspaces, which I find so useful.
Anyway, I started to miss the friendly environment I was looking as a
developer. Much late to the game, homebrew started a great job on
packing tools for easy build and deploy (I never liked MacPorts). As
time passed by, I got convinced that nor OS X, nor Windows, were first
class citizens as development platforms for what I was interested,
which is to play with and use a lot of programming languages and open
technologies. You know, I'm writing this post using VIM, Jekyll, Git,
Linux, Ruby, Github... I'm in the right place for this kind of stuff.
Because of its completely non-*nix inheritance, Windows aways gets
late on support by interesting open source initiatives and projects.
Its culture runs around distribution of tools through binary blobs,
instead of sources. I can't fix them myself if needed.
I view the way Windows is, as a two-way barrier in itself, which may
initially provide technology lock-in, but that in the long-term can
promote its own irrelevance.
I turned my macbook pro into a tuxbook pro:
<a href="http://cweiske.de/tagebuch/tuxbook.htm">![tuxbook](http://cweiske.de/tagebuch/images/tuxbook/tuxbook-1.jpg)</a>
How do I compare it to OS X on usability?
1. Better font rendering, out-of-the-box (on a macbook pro 13"):
### Font on Ubuntu Raring Ringtail
<a href="http://i.imgur.com/W4jrWV7.png">![Font on Ubuntu Raring Ringtail](http://i.imgur.com/W4jrWV7.png)</a>
### Font on OS X Mountain Lion
<a href="http://i.imgur.com/6LPxdXd.png">![Font on OS X Mountain Lion](http://i.imgur.com/6LPxdXd.png)</a>
### Font on Windows 8
<a href="http://i.imgur.com/aSvp7oY.png">![Font on Windows 8](http://i.imgur.com/aSvp7oY.png)</a>
I really dunno how to get OS X to display like Ubuntu, I tried to
tweak its font rendering...
2. Better workspace management. I got a 3x4 wrap-around workspace
grid.
<a href="http://i.imgur.com/77TGwVN.png">![Workspace Grid](http://i.imgur.com/77TGwVN.png)</a>
Very customizable, with VIM-like keybinds for workspace
switching and also, with touchpad gesture bindings. I find this
much better than OS X Mission Control.
I must note that, at this age, Windows still doesn't offer native
multiple workspace functionality. All alternatives for multiple
desktops I've tried, were broken someway or another simply because
Windows has no proper native support for this.
3. I didn't expect to be able to customize touchpad gestures like
this, and that it would work. Switching to Linux I just expected
to get used to scrooling through scrollbars, and just use the
keyboard to control windows and workspaces. Not just that, I have
2-finger drag for vertical and horizontal scrooling, 4-finger drag
for workspace switching, both horizontal and vertical, and