A CEO, a Browser and Civil Equality

This post is late. Not much late, but it is.

Today Brendan Eich stepped down as Mozilla CEO. Brendan Eich, for those who don’t know who he is one of the fathers of JavaScript and was Mozilla CTO for a long time. Also, he contributed to the “PROP-8″, a constitutional amendment to band same-sex marriage.

Now I don’t live in California or even in the USA, but I can understand why this can outrage some people.

And I’ll say some things that may make the same people outrage at me, so let me put this right here: I’m in favor of same-sex marriage only because it has absolutely nothing to do with a religious ceremony and everything to do with civil rights and how the law sees “couples”.

(And before some idiot comes commenting some stupid bullshit like “so are you in favor of a man marrying a tree?” I’d say “yes, if the tree is capable of signing the damn document, which it can, you stupid moron.”)

But back to topic: After Eich was appointed CEO, a huge discussion about someone against civil liberties going to lead the company that talks a lot about “freedom” and “open to all”. I can understand that.

The reaction from his appointment was so huge that Mozilla co-founder Mitchell Baker posted about separating personal opinions and company opinions, which Eich himself addressed too, without saying he was sorry about funding the PROP-8 legislation.

And, to be honest, I get that: I bet my company board of directors are all in favor of a right-wing government, while I’m a pro-left-center government. My personal opinion do not reflect my working posture (and yes, I reckon both are not in the same level, but still…)

There is a huge discussion at Ars Technica when OkCupid warned Firefox users and I must say they raised very valid points (which is what made me write this blog post).

Some points were way over the head, like claiming PROP8 was against their very human rights, like it would burn them in sticks for staying with their same-sex partners. Again, this is a civil right — a right that should be recognized by the government — but Eich voted against it. Eich wouldn’t personally go to those people houses and slap bibles to their faces till they fall in love with someone else (of the opposite sex, that is). And Eich has been way less loud than, say, Orson Scott Card, someone that makes me regret even reading his books.

On the other hand, this kind of religious bullshit should stop and people should be free to be recognized as a couple with whatever person they love. Even as a straight guy I can see that those kind of people would not stop once they ban same-sex marriage: they would ban people using long beards because it’s a sign of another religion (which is completely bullshit) then ban computer games because someone else told them “it is evil work” (which is utterly bullshit).

In the end, as always, people said that you should boycott Firefox. And that’s where my moral compass got all confused.

You see, there are some companies around here that sponsor TV shows that I absolutely despise, which I believe does nothing good; I hate with all my strengths companies that market themselves as a product to “real fanatics for soccer/football” when you see those same fanatics hitting people with metal bars only because they root for the other team[1] and, because of this, I refuse to buy any of their products. So, if I’m against someone that tries to take civil freedom from other people, how could I still use their browser?

Is not that Eich would even dictate the behaviour of Firefox, for any chance. Some of the comments mention that Obama (again, not my president, but a president of a country, nonetheless) also was against same-sex marriage but, mid mandate, was in favor of it. You can claim whatever political maneuver you want, but as a president of a democratic republic, Obama is force to go with whatever the people of his country want. As per Eich post, I’d expect that he too would not enforce his personal views over Mozilla and Firefox.

Still the problem persist: How could I still use something that would give money to someone to sponsor things I believe are the opposite I want to see in the world?

But Eich stepped down, so now I’m not in a moral conflict between a browser by a company with a CEO that doesn’t believe in equal rights and a browser by a company that is effectively trying to block the free internet for everyone.

[1] Seriously, if you work for a marketing company that does this kind of bullshit and don’t know what the fuck a “fanatic” is and how hitting someone with a metal bar IS fanatiscism, go put a bullet on your head. Seriously.

Posted in Uncategorized | Tagged , , , | Leave a comment

Apple, Let’s Talk About “Explicit” and “Implicit”

Dear Apple,

I’m one of the guys who goes around saying “Apple API is one of the easiest GUI APIs I ever used”. Even when people complain about Objective-C, I point that since everything is a canvas, you can extended every component in any imaginable way.

I also get why Table Views go under the Navigation Bar, Tool Bar and Status Bar: To give the user the impression that the application stretches over all the screen instead of a small space in the middle.

But there is one thing I learnt with Python: Explicit is better than Implicit.

When you automatically add the default padding to an element dragged in the storyboard, I can see the padding in the Size inspector; when I set a relationship between two elements, I can see the constraint in the same Size inspector.

But when I drag a Table View to my View Controller and it automagically gets a padding to go under the navigation bar and there is nowhere to see this, then we have a problem.

When a UITableView is the first subview of the main view, it magically gets a padding; this is shown nowhere.

When a UITableView is the first subview of the main view, it magically gets a padding; this is shown nowhere (except in the storyboard, which makes you think you suddenly got a table header).

The same view as before, but the UITableView is not the first subview anymore; the padding disappears.

The same view as before, but the UITableView is not the first subview anymore; the padding disappears.

Things shouldn’t be like this. Sure, there is some obscure documentation saying “Hey, if your Table View is the first subview of a view, it will magically get a padding on the top”, but that is a total bullshit. What if I, somehow, want to keep some logical order that requires an element just below the navigation bar but my table view should still get the padding? What if I need a bigger padding, then?

This thing should never be magical. It should be a flag, a value, even a freaking constraint, but not a damn magical positional setting which is not obvious at first glance.

Seriously Apple, this is the kind of bullshit that ruins our relationship…

Posted in Uncategorized | Tagged , , , , , | Leave a comment

My Take on Banished

There are several games that take you on the role of some immortal mayor/governor/president/emperor in the quest to create the greatest city ever (Civilization, SimCity and Anno being the greater exponents of this line). Even iOS games like Townsmen put you in that role.

In all those games, you have to focus on resources: You need to “capture” that iron mine in order to build iron weapons; you need workers to get the iron from the mine and bring it to your town to build said weapons; you need some farm to keep your workers alive so they can mine your iron and so on.

But none of those really focus on workers. Workers are nothing more than some easy-to-get resource, in which you usually build a house and wait till workers popup. And they keep going till someone kills them.

That’s not what Banished do. Banished focus solely in the workers and their lifetimes.


The interface is as spartan as you could get — pretty much what your new followers have now. On easy, you fortunately start with a barn to store goods, a stockpile of goods and houses for all your families; on medium, no houses and just a cart with food. And I still didn’t had the guts to try it on hard.

In this situation, you need to start providing some facilities for your people: Houses if you’re on hard, then some food generating facility, then some route of clothing or tools creation, then some roads to connect all those, then maybe some trading facility…

So far, it looks pretty much like any other town-creation game, right?

Well, here’s the twist: Building more houses does not mean more workers. When you put a house, you actually create a place for a family: a man and a woman (and hey, that’s the game saying what’s a family, not me — although I’ve seen families with just a man and his son). And, after a while, a family will have a child.


Children are little resource suckers that take food and produce absolutely nothing. But you need them ’cause, at some point, the mother and the father will get too old and just die.


And that’s the cycle you have to manage: Create houses, manage families, wait till they have kids, wait till the kids are old enough to work, wait till they create new families, wait till the old people die, try to move young adults to do the jobs of the dead…

Oh, not only that, but when you create some resource-creation facility, it just don’t simply sparkle to life and start producing resources: You need to allocate your adults to produce said resources.


“Laborer” is pretty much a person that doesn’t have a job, so they keep moving around, transferring resources from barns and stockpiles to houses (yes, houses have their little stockpile of food and wood and clothing, so people don’t need to keep walking back and forth — unless they are at work and feel hungry, in which they will do all the way from work to their houses to get fed), transferring resources from resource-creation facilities to barns and stockpiles and so on. Once a specialized worked dies (either of old age, crushed by a rock, mauled by a warthog, giving birth or some natural disaster) a laborer will take their place.

So there is this constant “I need more children so later I’ll have more workers, but I need workers now to keep the children fed and train them and OH GOD, WHY DON’T YOU GROW FASTER, YOU LITTLE RESOURCE-SUCKING-FUCKERS?!?” and “Gawd dammit, another worked died”. The balance between keeping laborers for when someone dies, trying to keep your workers alive, fed and warm, so they can produce resources to make more workers is very very very thin and keeps the constant “Ok, just a few more minutes so I get enough workers for this and then I’m going to bed” that goes for hours and hours.

Although the game sucks you into it — in a good way — there are some things that really aren’t helpful.

For example: Remember when I said that you have to wait for families to have children, wait till children grow up and then wait till they create their own families? Well, that’s the first problem: The constant waiting makes the game feel so sloooow it becomes kinda boring if you play in normal speed. I am, on easy, playing constantly at 10x the normal speed (fortunately, the game have a speed control). This is partly what sucks you in, and partly what will annoy the fuck of you (but, then again, if they removed the cycle, the whole game would lose its appeal).

The other problem is the spartanness of the interface. Sure it allows seeing a lot around so you know where would be a good place to build a farm or an orchard or were simply send your laborers to collect stone, but it makes harder to see how many resources you already have, for that quick “Damn, my firewood resources is slowly going down, maybe I need more woodcutters”, if you have too many laborers and can move them to more specialized work and even when people die, which mean you’ll have, maybe, to move some specialized worker back to laboring, in case someone else dies. That’s why most of the screenshots here have those 3 windows open all the time: without them, it’s pretty hard to keep track of all of this. Sure, you have the option to open those windows, but the fact that you have to open them irks me a bit.

On the other hand, you can’t call the game ugly (maybe not “pretty”, but seriously not ugly).


With all that, do I recommend Banished? If you like games about building stuff that give a different focus than other games and keep you on the edge of your chair (well, at least, till everything runs smoothly, you have a shitload of food, a shitload of tools, a shitload of warm clothes and a shitload of laborers), it certainly it is a good game.

Posted in Uncategorized | Tagged , , , , , | Comments Off

Auto-virtualenv, now with more magic

Following yesterday’s post about Auto-virtualenv trick, today I managed to fix the issue of “auto-virtualenv loses the virtualenv if you go into a subdirectory of the directory with the .venv“.

The only change is the _venv_cd function. All the other alias still remain the same.

function _upwards_search {

    while [[ `pwd` != '/' ]]; do
        if [ -f ./.venv ]; then
            venv=`cat ./.venv`
        cd ..

    cd $curdir
    echo $venv;

function _venv_cd { 
    if [ ! -f $PWD/$1 -a "$VIRTUAL_ENV." != "."  ]; then 
    \cd $1
    if [ -n "$venv" ]; then 
        venv $venv 
alias cd=_venv_cd

Next step: remove all this stuff from my .bashrc, move to a single file which can be easily sourced inside your on .bashrc and drop it in a repository somewhere.

NOTE: Apparently, there is something wrong with the test for empty venv. Hold down your horses for a sec.

NOTE 2: Ok, problem solved. Also, the repository is now live at https://bitbucket.org/juliobiason/auto-virtualenv.

Posted in Uncategorized | Tagged , , , | Comments Off

My magical auto-virtualenv trick (without VirtualenvWrapper)

One thing that pissed me off a few days ago was working in a Python project with some modules and switching between virtualenvs every time[1]. So I quickly hacked a solution.

But before going further, let me say that the solution is highly based on VirtualenvWrapper — to the point that I’m using the same environment variables. I just didn’t want to install a whole package for a simple feature.

And, without further ado…

The whole thing started with two alias added in my .bashrc, one to create a virtualenv and another to “active” the virtualenv. Today, they look like this:

function venv { source $WORKON_HOME/$1/bin/activate; }
function mkenv { virtualenv $WORKON_HOME/$1; venv $1; echo "$1" > ./.venv; }

Nothing fancy here: I’m using WORKON_HOME exactly as it is used with VirtualenvWrapper, to point the directory where all virtualenvs sit. Then, to avoid going full path to activate them, I can simply use venv <virtualenv-name> to activate any virtualenv and, finally, to create virtualenvs in the right directory, I have mkenv <virtualenv-name>. Simple as that.

One thing you may notice is that I’m saving the virtualenv name in a hidden file inside the current directory, called .venv. This is what makes the magic happen.

Then, I have this script + alias:

function _venv_cd { 
if [ ! -f $PWD/$1 -a "$VIRTUAL_ENV." != "."  ]; then 
\cd $1; 
if [ -f ./.venv ]; then 
    venv `cat ./.venv`; 
fi }
alias cd=_venv_cd

This basically replaces cd with my function, which checks if the target directory have a .venv and, if it does, activate the virtualenv (so I don’t need to use venv anymore in normal situations); if there is no .venv but a virtualenv is active, deactivate it.

The only problema I still have is that going up inside the project/module won’t check if there is a .venv in any of the parent directories and, thus, would disable the virtualenv.

[1] It was just a matter of “keeping each with their own”. The whole project goes around creating modules for a web framework and each module must be capable of working standalone, without the others.

Posted in Uncategorized | Tagged , , , , | Comments Off

My Take on Grim Dawn

Before the end of the (previous) year, Crate Entertainment decided to give early access to all backers of Grim Dawn. Well, it just happened that I was a backer — although not an “early access backer” — on their Kickstarter, so I had the chance to play it.

Just beware that everything I say here is based on their alpha, which have access only to the first Act and not the whole game. So I bunch of things couldn’t be accessed yet[1] and some things may change till the final release.

What’s Grim Dawn, anyway?

Grim Dawn is yet another ARPG, much like Diablo and Path of the Exile. The engine is a full 3D engine, which allows you to rotate the screen in any angle — although keeping the classic isometric view.

The story is somewhat intriguing, although not at all too different from other ARPGs: A race called “Aetherials” enters “our” realm and start turning humans into zombies, which puts the human race in the brink of extinction (I just read the Wikipedia page and it seems that the extinction was not brought by the Aetherials alone, but actually from a fight of the Aetherials and the Chthonians, the first trying to turn humans into an army and the later trying to kill all humans before that but I don’t remember reading anything about Chthonians in the whole first act, although I skipped most of the reading till the very end.)

Your character was saved in the last minute from a hanging due being possessed by one Aetherials. The whole story seems that it will float around the fact that you are now “infected” with aetherial material, which grants you some special abilities — opening rifts, for example, which can be related to “town portals” in other games, except require no special skill or item, require no mana and, be used as many times as you want and allow you to pick any other portal around (so not just to town, but to any other point you already know).

The whole environment is quite interesting too: instead of going full fantasy, Grim Dawn seems to be centered in a not distant past, as you can use fire weapons — pistols, rifles and shotguns — along weapons you’d find in any other ARPG — crossbows, swords, daggers, clubs, maces — not to mention the gear, with some heavy armor floating around leather jackets and such.

Getting your feet wet

When you start Grim Dawn, you’ll see your last played character, an option to jump to the next one or, if you have none, you’ll get straight to the character creation screen, which is as spartan as it can get.


It was my first surprise: No class/profession selection? No customization at all? Just “name” and “male or female” options?

Actually, yes, that’s it. It seems Crate took everything that was not really necessary for an ARPG and went down to the very bare bones of an ARPG. It’s so down to the bones that there are only three attributes to use: Physique, for health and armor usage; Cunning for attack speed; and Spirit, for your mana bar and mana regen.


Speaking of mana regen, some time after attacking or being attacked, you’ll receive a fast health regen. I’m kinda divided about it: First, it gives you some chance to recover health without resorting to massive health potion chugging — although the potion itself have a cooldown and, fortunately, gives health at once instead of simply giving you “regeneration” — or some other gimmick like health orbs dropping from time to time, but, at the same time, the simple fact that you can simply start running around your enemy, without giving it the chance of attack you and without attacking, will give you a massive regeneration feels so… gimmicky.

Becoming one

Even if you start with a clean slate, at level 2 you can pick a class, which will dictate your skills and abilities. There are 4 classes you can take then, which can be easily related to the “usual” ARPG classes:

The Soldier is, basically, the classic warrior:


The Demolitionist, although with a name like that, is basically the ranger/archer stereotype, without the pet and with a preference for fire weapons:


Occultists take the position the mage stereotype position in classic ARPGS:


And, finally, the Nightblade takes the assassin/rogue place:


I just need to stop here and point that there is nothing telling or even stopping you from using weird class/weapon combinations: You want to make a pistol solder? No problem, the game will not stop you from doing it so. The only barrier is that some skills — which I’ll show next — will require some specific weapons (for example, the soldier have a skill that requires a shield, the nightblade have skills that require dual wielding melee weapons and so on).

Going up

Once you pick your class, you’re presented your skill tree. And seriously, Grim Dawn rivals Path of the Exile in the “this will require some thinking” tree.


You have actually two intertwined trees: The basic one, at the bottom, indicates your class proficiency — the higher, the more skills are available to you, increasing your basic stats at the same time[2]. At every level, you gain only 3 points, which you must allocate in those two trees — which is the part that makes it something you may need to think ahead: You can make a very meek character with very strong skills or an incredible build character with weak skills.


Balancing the trees is, obviously, the way to go, but how do you balance it is the part you’ll have to look for a while before just clicking away.

Oh, and if you think that’s easy enough, at level 10 you get the chance of getting a secondary profession:


And the second tree is not at all tied to the first class: Adding points to the second tree will earn as many attributes as the early levels — so you’re gaining attributes for a level 2 character instead of a level 10 character, but you need to put those points to open skills!

Going above the baseline

There are upgrades, like any other ARPG. The difference here is that there are no slots in any piece of gear: Everything has the ability to carry an upgrade beyond those in the gear itself.


Once an item receives an upgrade, it can only be upgraded with the same piece — you can’t mix two different upgrading elements in the same piece of gear. On the other hand, “upgrading” an upgrade component will complete its set, which can grant better results — pretty much what would happen if you complete a set of gear in other ARPGs, but with upgrades.

Gear sets are also available, although in my play time I only found two pieces of one set.


Going around

As I mentioned before, because you have been infected by the aetherials, you can summon personal rifts at any time, although only one rift can be open at the same time. Beside those, you can also find stable rifts all around, filling the “waypoint”… erm… “stereotype”?


And, as I said, one you open a personal rift, you can go anywhere:


Oh, and, in case you didn’t notice, the world is massive. I’d say that one map (from waypoint to waypoint) is actually larger than Path of the Exile maps.

The final tidbits

Obviously, there are other things in Grim Dawn that every ARPG have. Weapon swaps, health and mana potions and Vendors, for example:


In the case of the vendors, you’ll notice that items can have 3 different colors: Yellow means it’s a magical item (there are three other “quality” colors: red for set items, blue for named items and green for magical with better stats); Red means you don’t have the necessary attributes to wield that item; and Gray points that you don’t have enough money to buy the item.

The idea is good, but sometimes it falls to its knees: If you don’t have the coin and the attributes to buy something, the colors mix in and you can’t say if you can’t buy it simply because you need a few more attribute points or you need attribute points and coin. Yes yes, in the end, it means that you can’t use the damn thing, but it still annoys me, somehow.

Grim Dawm have a full economy with “iron coins” being used on sell and purchase, which I personally think it’s uninspired when compared to the barter system in Path of the Exile. On the other hand, it makes things easier, I guess. Also, as a side note, the whole time I played the game, the vendors never had something better than what I already had. Either that or I’m really bad at stats.

There are also factions, although I didn’t notice any difference in game play with it.


There are also destructible objects, which can contain loot:


One of the downsides I found is that the minimap encompasses the whole visible zone, without any visible zoom indicator, which completely removes the “fog of unknownness”. The only way to see where you still have to explore is through the full map.


And finally, when you’re low on health, the whole screen will get darker and the borders will point out that you’re in a really bad shape.



At this point you’re probably asking yourself “So what?”. And I admit, there are very few interesting things in this piece of my opinion besides the skill tree. That’s because the most interesting thing in the game can’t be shown by images alone.

It’s its atmosphere.

Seriously, the visuals are darker with an amazing track which in very few times reminded me of the old Diablo games[3] which will keep you on tense the whole time: My right thumb is hurting by putting too much pressure on my mouse.

And the environment is really dark sometimes, which will reduce your vision to barely anything and will force you to navigate using only the minimap. And the maps are smartly designed to have some wet spots which will break your concentration by changing the noises and visuals.

And, to be honest, the story picks up really fast, to the point that after a while I decided to finally stop and read what was going on ’cause things were doing turns all the time.

Although I sunk more than 10 hours in the first act alone (8 with a single character, which was the only one I could finish the first act), I still think there are some points the game could improve:

First, voice acting. I admit that maybe this is asking too much, but I didn’t feel too interested the whole thing because there were too many walls of text. The story picks up and you start reading, but maybe I’d feel more into the story if I had someone to hear.

Second, the mini maps really needs some zoom and the “fog of unknown” zone needs to be smaller. If I need to explore around, I’d at least like to know if I’m not running around in circles.

Third, the maps could use some random generationness. I mean, 4 different characters and the maps were all the same. That makes me wonder if there is any replayability once you complete the whole campaign (well, besides multiplayer, that is).

All those are minor, in my opinion. The game is interesting enough, the skill tree is enough to keep (or, at least, to keep me) playing for a long time just to level up and open all those skills, the story seems incredible well written, even if you may skip most of it due the lack of voice.

At this point, with the latest build (released on the last day of 2013, nonetheless) I’m really not regretting backing Crate on this endevour, even if the final release seems to be a bit late — but honestly, with the quality shown so far, I guess no backer can be pissed if they still want to do some clean ups.

[1] Fun fact: After you complete the first act, the NPC which will probably grant you access to the second act zone only says something around the lines of “This is the end of the alpha version. In the future, you’ll be able to access the whole game”, which your character replies with “I can’t wait!”

[2] I didn’t notice any change in the attribute gain by class (like one could expect that the soldier would gain more physique per level than an occultist), but I could be wrong here.

[3] Compared to, say, Torchlight 1 and 2, which are pretty much the same musical tone, but that’s because Diablo 1 and 2 and both Torchlight games had the same composer.

Posted in Uncategorized | Tagged , , | Comments Off

Uma Lição de VIM #16: Conclusão

(Essa é a parte em que nos despedimos.)

Pessoalmente, a palavra que eu usaria para descrever o VIM é extensível. Não apenas pela quantidade de plugins criados e aperfeiçoados nestes 20 anos de editor (na verdade, 22 se você considerar a primeira versão disponibilizada em 1991 ou 25 se você considerar quando Bram Moolenaar fez a versão 1.0 para o Amiga), mas pela forma como os comandos foram projetados: Você sabe que uma movimentação do cursor com um número da frente “pula” outras ocorrências, então qualquer comando que você descobre como movimentação repete esse comportamento; Você sabe que comandos que requerem movimentação aceitam qualquer comando de movimentação (incluindo a quantidade, discutido antes); e assim por diante. Claro que isto permite várias formas diferentes de fazer a mesma coisa, mas isto também garante que você vai achar uma forma que se encaixe com o seu workflow de desenvolvimento.

E não que, como eu falei lá no começo, VIM seja o editor perfeito para todas as condições: Existem coisas novas surgindo a todo momento (por exemplo, a idéia de múltiplos cursores só foi popularizado quando o TextMate foi lançado no OS X) e que o editor base não consegue fazer — mas como o editor é extensível em várias formas, alguém já fez um plugin para repetir o comportamento no editor. Existem arquivos de sintaxe que são terríveis, e mesmo assim fazem parte do pacote original — e existem formas de atualizar por versões melhores. Existem plugins que baseiam-se unicamente no tipo de arquivo inteiro e não no bloco — mas não há nada que não garanta que, no futuro, alguém consiga fazer um plugin que troque automaticamente de modo baseado no contexto atual.

Na contrapartida, existem certas coisas que o VIM consegue fazer que outros editores não fazem: Pular para o ponto onde o texto foi inserido da última vez é o que sempre me faz voltar a usar o VIM e que eu sinto uma tremenda falta nos outros editores — que, diga-se de passagem, é fácil do editor controlar pela existência dos modos.

E, como dicas de despedida: Quando alguém comentar sobre uma feature em outro editor, lembre-se de procurar por “vim {feature}” na internet; muito provavelmente a feature já existe em alguma forma para o VIM ou já tem alguém tentando escrever um plugin para fazer a mesma coisa. E lembre-se sempre que :wq só funciona no VIM, não nos demais editores ou no seu emulador de terminal[1].

[1] Você pode perguntar para qualquer usuário de longa data quantas vezes eles tentaram fechar o terminal ou mesmo um editor de textos como Word ou LibreOffice com :wq e a resposta provavelmente vai ser “mais vezes que eu posso lembrar”.

Posted in Uncategorized | Tagged , , | Comments Off

Uma Lição de VIM #15.10: Plugins – Vim-Multiple-Cursors

(Essa é a parte em que você pode repetir várias coisas, visualmente.)

O último plugin da lista de plugins é o Vim-Multiple-Cursors.

Já que sempre falamos em usar Vundle…

Bundle ‘terryma/vim-multiple-cursors’

Assim como outros plugins já comentados, Vim-Multiple-Cursors não tem nenhuma apresentação inicial. O que este plugin faz é permitir que você tenha várias cursores no texto ao mesmo tempo, aplicando a mesma transformação em todos os lugares.

A forma mais simples de usar Vim-Multiple-Cursors é ir até a palavra que você quer alterar e pressionar [Ctrl]n. Você vai notar que o VIM irá mostrar como se você tivesse entrado em modo visual e selecionado apenas aquela palavra, o que não é nada impressionante. No entanto, se você pressionar [Ctrl]n de novo, você verá que o cursor irá para a próxima ocorrência da palavra. Na verdade, o que você tem agora são dois cursores e tudo que você fizer em um será repetido no outro. Por exemplo, se você fizer ce sobre a palavra, você verá as duas palavras mudando ao mesmo tempo.

De certa forma, o que você está fazendo é um “search and replace” só que está vendo exatamente o que vai ser alterado.

Teoricamente, você poderia fazer I"[Esc]ea" para adicionar aspas ao redor da palavra, mas há um pequeno inconveniente: [Esc], que você precisa usar para retornar para o modo normal depois de entrar em modo de inserção com I irá também terminar o modo de múltiplos cursores.

A segunda forma de usar Vim-Multiple-Cursors é fazer uma seleção visual e usar [Ctrl]n. Para cada linha da seleção, será adicionado um novo cursor. E, novamente, o que você fizer em um deles será repetido em todos.

Simples assim.

A única coisa que eu posso deixar de aviso é que, por algum motivo, utilizando uma seleção visual de várias linhas ([Shift]v), entrando em modo de múltiplos cursores ([Ctrl]n) e usando aspas (com o Auto-Pairs), meu undo acabou sendo perdido (u removia o texto inteiro, não a alteração feita com Vim-Multiple-Cursors).

Posted in Uncategorized | Tagged , , , | Comments Off

Uma Lição de VIM #15.9: Plugins – CtrlP e CtrlPFunky

(Essa é a parte em que você vai ter a impressão de estar programando em Perl, porque qualquer caractere é válido.)

O nono e penúltimo plugin (na verdade os nonos e penúltimos plugins) discutido é o CtrlP e seu plugin (sim, um plugin do plugin[1]) CtrlPFunky.

Para instalar os dois, com Vundle:

Bundle ‘kien/ctrlp.vim’
Bundle ‘tacahiroy/ctrlp-funky’ 

CtrlP é um plugin que facilita encontrar e abrir arquivos, com procura fuzzy. E, por procura fuzzy eu quero dizer que ele encontra qualquer arquivo que tenha as letras digitadas na ordem que você digitou.


Para acionar o CtrlP, você deve digitar, logicamente, [Ctrl]p. Ao fazer isso, uma janela parecida com a Quickfix irá aparecer, mostrando alguns arquivos e um prompt para que você digite o que quer encontrar. No exemplo acima, como que digitei “vim”, ele encontrou todos os arquivos a partir do diretório atual que começavam com “v”, tinham um “i” no meio e terminavam com “m” (seria basicamente o mesmo que pegar a lista de arquivos a partir do diretório atual e seus sub-diretórios e procurar pela regex “v.*i.*m”.)

Uma vez que você encontre o arquivo desejado na lista (ela não tem rolagem, então se você ainda não estiver vendo o arquivo, continue adicionando caracteres para que o arquivo desejado apareça na lista — uma vez lá, você pode selecioná-lo com as setas), você pode:

  • Pressionar [Enter] para abrir o arquivo na janela atual.
  • Pressionar [Ctrl]t para abrir o arquivo em outra aba.
  • Pressionar [Ctrl]s para fazer um split horizontal e abrir o arquivo no novo split.
  • Pressionar [Ctrl]v para fazer um split vertical e abrir o arquivo no novo split.

Um problema que você talvez encontre é que o CtrlP costuma listar tudo que se encaixar na expressão utilizada, inclusive arquivos binário, objetos intermediários, etc. Para remover estes arquivos da listagem, você pode usar :set wildignore, que também afeta a lista de arquivos que o VIM mostra quando você estiver usando os comandos normais de abertura de arquivo (:e, :tabe, etc).

Como a configuração do wildignore é uma lista, você pode adicionar ou remover usando += e -=. Por exemplo, para ignorar os arquivos de objetos compilados do Python e o diretório que o setup.py constuma usar para construir o pacote de distribuição do módulo, você teria:

set wildignore+=*.pyc
set wildignore+=*/build/*

ou ainda, para economizar uma linha:

set wildignore+=*.pyc,*/build/*

CtrlP tem um plugin, chamado CtrlPFunky. O que ele faz é basicamente o mesmo que o CtrlP, mas procurando funções, não arquivos.

Para ativar o CtrlPFunky, você precisa primeiro adicionar o mesmo como uma extensão do CtrlP (e, só pra avisar, isso é específico do CtrlP, não algo que funciona com todo e qualquer plugin):

let g:ctrlp_extensions = ['funky'

Uma vez instalado, você pode usar :CtrlPFunky para mostrar a lista de funções no fonte (e a procura continua igual). O problema com CtrlPFunky é que, assim como todas as demais coisas que vínhamos vendo, ele se basea no tipo de arquivo atual (:set ft) e para arquivos em que o conteúdo e uma mistura de várias linguagens (p.ex., arquivo template com a linguagem de template, HTML, CSS e JavaScript), a listagem de funções pode não ser o que você está esperando (ou sequer vai funcionar).

Para facilitar a sua vida, você pode fazer um mapeamento do comando para um atalho de teclado. Por exemplo, eu coloquei [Ctrl]o para chamar o CtrlPFunky com

nnoremap <C-O> :CtrlPFunky<CR>

[1] “Plugin-ception” har har har[2].

[2] Eu não consigo entender porque as pessoas utilizando tanto o “ception” quando encontram um meta desta jeito. Um “inception” é a inserção de uma idéia de forma que a pessoa pense que a idéia é dela, não uma “Matrioska“.

Posted in Uncategorized | Tagged , , , , , , | Comments Off

Uma Lição de VIM #15.8: Plugins – SnipMate

(Essa é a parte que automatizamos a digitação de coisas repetidas.))

Para o oitavo plugin, iremos falar sobre SnipMate.

Como de costume, instalando pelo Vundle:

Bundle ‘msanders/snipmate.vim’

SnipMate adiciona a funcionalidade de snippets dentro do VIM. Para quem não sabe, snippets são trechos de código que são adicionados automaticamente (ou com a ação de alguma combinação de teclas) a partir de uma simples palavra.

Por exemplo, um dos snippets que já estão inclusos no pacote do SnipMate, você pode, num arquivo JavaScript, simplesmente digitar:


… e, ao pressionar [Tab], o SnipMate irá adicionar, automaticamente

function function_name (argument) {
  // body…

… posicionando o cursor diretamente sobre function_name para que você coloque o nome da função; pressionando [Tab] irá posicionar o cursor sobre argument e pressionando [Tab] de novo, o cursor ficará sobre // body... (depois disso, [Tab] irá funcionar como tabulação, como normalmente é).

Para criar seus próprios snippets, você tem duas opções e ambas devem ficar no diretório $HOME/.vim/snippets:

A primeira forma é através de um único arquivo, com o nome do tipo de arquivo em que os snippets serão válidos (que você pode ver usando :set ft) com a extensão snippets (por exemplo, para snippets para arquivos Python, você teria um arquivo $HOME/.vim/snippets/python.snippets). Neste arquivo você deve iniciar os snippets com a palavra snippet, seguida da palavra que será utilizada para identificar o snippet, seguido pelo snippet em si, com uma tabulação na frente (quando não houver tabulação, SnipMate considera que o snippet terminou). Os pontos onde você quer que o cursor pare devem ser identificados por ${{número}:{texto}} e, se ficou confuso, é porque eu estou usando “coisas que você substituir” com {} e o próprio SnipMate usa {} para blocos, mas deve ficar mais claro com este exemplo:

snippet for
    {% for ${1:record} in ${2:list} %}
    {% endfor %}

Este snippet, para Django e Jinja, faz um loop “for”. Ao digitar “for” e pressionar [Tab], o conteúdo será adicionado, o cursor será posicionando onde ${1:record} está permitindo a alteração do mesmo, pressionando [Tab] de novo irá posicionar em ${2:list} e assim por diante.

E, caso você esteja se perguntando “E o que acontece se eu colocar o mesmo número em dois lugares diferentes?”, a resposta é: lugares com o mesmo número são alterados ao mesmo tempo. Por exemplo, o snippet:

snippet block
    {% block ${1:blockname} %}
        ${2:{% content %}}
    {% endblock $1 %}

… tem o número “1″ duas vezes (uma depois de “block” e outra depois de “endblock”). Quando você colocar o nome do bloco no primeiro (do lado de “block”), o outro (depois de “endblock”) será preenchido automaticamente.

A segunda forma de adicionar snippets é através de arquivos individuais. Ao invés de ter um arquivo com o tipo de arquivo com todos os snippets dentro, você irá criar um diretório com o tipo de arquivo e cada arquivo dentro deste diretório deve ser {palavra}.snippet. Assim, como no exemplo anterior tínhamos um arquivo $HOME/.vim/snippets/htmldjango.snippets, poderíamos ter, na verdade, um diretório $HOME/.vim/snippets/htmldjango/ e, dentro deste diretório, um arquivo chamando block.snippet com o conteúdo do snippet, sem as tabulações (já que agora o SnipMate sabe exatamente onde termina o snippet: no final do arquivo).

E quando usar um ou outro? Você deve usar arquivos individuais se o SnipMate já tiver um arquivo de snippets para o tipo de arquivo especificado. Assim, se você quiser adicionar novos snippets para Python, que já tem uma série de snippets prontos incluídos no pacote do próprio SnipMate, você deve usar a segunda forma. Caso contrário, fica por preferência pessoal.

E, para concluir: Ao escrever este post, descobri que existe um fork da versão apresentada aqui. A versão do “msanders” não é atualizada a 4 anos — mas funciona perfeitamente e tenho usado sem problemas a bastante tempo. Se você quiser algo mais recente (por algum motivo), o fork está em github.com/garbas/vim-snipmate (e requer mais dependências que a versão original).

Posted in Uncategorized | Tagged , , , , | Comments Off