Friday, January 27, 2012

Sunday, January 22, 2012

The Rap on Vim's Registers

My first attempt at two things. Firstly, this is my first infographic (and yes, I know, it violates quite a few of the so-called rules. Meh. It's my first! Woo hoo!) Secondly, this is the first time I've tried to explain Vim's World of Registers, and... it's complicated.

Update: I added some clarity behind the unnamed register and how the numbered registers are populated/shuffled.

Update: I fixed a typo with the <c-r>0 in the Grief Counseling section and changed the recommended solution to the Deleting problem to use a visual selection.



Thursday, January 19, 2012

One Key To Toggle Them All

...whether to paste or to nopaste, that is the quintain
Real estate in the Vim Keymap World is a bit sparse. Vim steals for itself nearly every sane key combination, leaving the paltry <leader> basement space for us lowly users to occupy. Vim does leave most of the Function Keys alone, though, making them a popular squatters choice in ~/.virmc . But there’s only twelve of them (on non superhero keyboards) so you don’t want to go wasting them either. The Vim docs (:help 'pastetoggle) suggest mapping <F10> to enable paste mode and <F11> to disable it. Meh. That’s TWO WHOLE F keys for one logical operation (and its inversion - its… toggle). Surely we can do better…
Paste Toggle on a Single Key
paste_toggle.vim
" Paste Toggle
" Barry Arthur, Jan 2012

" show paste toggle in insert mode
set showmode

" toggle (invert) the current paste state and show new state
function! PasteToggle()
  set invpaste
  set paste?
endfunction

" map for normal mode
nnoremap <F11> :call PasteToggle()<CR>

" map for visual mode
vnoremap <F11> :<c-u>call PasteToggle()<CR>gv

" insert mode handled by pastetoggle option
set pastetoggle=<f11>

Now we have paste toggle on a single key, working from most places you’d want it. Copy that code and put it in ~/.vim/plugin/paste_toggle.vim on linux and mac. On windows, copy it to $HOME/vimfiles/plugin/paste_toggle.vim. Make that path if you don’t already have it. Restart your vim and test your shiny new <F11> key in normal, visual and insert modes.Of course, you can make it any key you want instead of <F11>. Joy.

Thanks to osse for catching a silly bug on the vnoremap - forgetting to put <c-u> at the start of the map will cause the function to be called for each line currently selected - definitely not the behaviour we want here.

Tuesday, January 17, 2012

Conical Gradients in Inkscape

Let's Draw a Colour Wheel in Inkscape

Inkscape doesn't yet (circa Jan 2012) support conical gradients, but it is getting some sexy love in this area, hopefully soon. Until then, this article shows one way to do it. Look here for an alternative.

Recipe

1. Create a circle and unset its colour.


Click the big question mark ( ? ) to unset the selected object's colour:



2. Duplicate the circle with ctrl-d (Edit | Duplicate), move it aside and using the Circle tool (F5), modify its arc to be (360 / 255) 1.4117 degrees. The arc End textbox will show 1.4112 but it holds the higher precision number internally, I believe.



3. Move the rotation point of the circle to the top left hand corner.  Use the select and transform tool (F1) and click the arc twice (not double-click) to enable rotation mode. Drag the cross at the centre of the arc to the top left hand corner.




4. Open the Clones dialog (Edit | Clone | Create Tiled Clones...)



Symmetry Tab:

5. Choose P1: simple translation and set the  Rows, columns to 1, 255



Shift Tab:

6. Check the per column Exclude tile box.




Scale Tab: No scale

Rotation Tab:

7. Set the per column rotation to 1.4117 degrees. It will show you that it's only 1.4 degrees, but it uses more precision behind the scenes, apparently.



Blur & Opacity Tab: No Blur or fade.

Color Tab:

8. Set the per column Hue percentage to (100 / 255) 0.4 %.  (Percent seems to be a weird unit for this setting.) The formula of
100 / 255 is percentage-points / hue-points.


9. Click the coloured rectangle beside the Initial color label and set H, S, L, A to 0, 255, 128, 255.



Trace Tab: No Trace.

10. Click the Create button and you should see:



Notice the spiral artefacts around the edges and particularly along the vertical line between dark blue and purple. We will group and blur these cloned circle segments (arcs) to remove that distortion.

If you forgot to set the rotation point in step 3, you will instead see:



Use ctrl-z to undo and go back and do step 3.

11. Using the select and rotation tool (F1), draw a box around the whole colour-wheel to select all of the clones. Use ctrl-g to group them.

12. Using the blur setting on the Fill and Stroke dialog (ctrl-shift-f), set the blur to 2.



Which results in:



If you're happy with that then you can stop here, but if you would like a crisp edge to your colour wheel instead of the fuzz the blur created then we need to clip it with the black circle.

13. Select the black circle and make sure it is the top-most object on the layer by pressing the Home key (Object | Raise to top).

14. With the black circle still selected, shift+click the grouped colour wheel and open the Align and Distribute dialog (with ctrl+shift+a or Object | Align and Distribute) and click the Center on vertical axis button and then the Center on horizontal axis button.

 
 
Once the two are aligned, you can just see the blurred colours beneath the black circle:



15. Clip the colour wheel with the black circle by choosing Object | Clip | set.

Done! And your colour wheel should look like this:


Not too shabby. Enjoy. :-)

You've Got This Big Z In Your Code


Nasty

We've all seen it at one time or another. A big, nasty, hairy, cranky looking THING in our nice, clean, precious text file. How the hell did that get there?! More importantly... How do I get rid of it?

Diagnosis

This condition can present itself in several ways, like the unprintable character code in angle brackets:

 F<83>k me

...an intimidatingly visible character from another land:

 好天

...or just fancy versions of good old regular ASCII characters:

 I’m sick of ‘smart’ quotes


Complications


Navigating through your whole file looking for and exterminating these little warts by hand would be tedious and we're Vimmers after all, so we should be thinking in sharper tools, like... a whole buffer substitution. Great. Now we have a new problem... How do I type one of those eyesores into the substitute command...? We'll use a little dash of Register Pasting magic.

Caveat

This could be an encoding problem, so make sure   :set enc? fenc?   return sane values before you go stripping out or replacing these crusty critters.

Cure

Let's take the smart quotes example and clean them up to be ordinary, normal, sane, plain quotes. We'll tackle that smart single quote case from above.

  1. Navigate on over to one of the offending ’ characters.
  2. Press xu
  3. Type :%s/<c-r>"/'/g
  4. Repeat for all of the other smarts in the file.
Hopefully when you next break out in an embarrassing rash of wicked wigglies, frightful foreigns or undecorous unprintables you will now be able to get righteous on their bad selves.

Monday, January 16, 2012

What Are Your Options?

Gnnnh! Gack! *curse* *pound-fist* *cry-like-a-baby*

You know the frustration. You know there's an option in Vim for what you're trying to do... You're sure of it. You've used it before! You've seen people talk about it on #vim. You've bored your wife over dinner with it. You just can't remember it now. It had a funny name. It wasn't quite what you'd call it. What was it again?!  Bah!

What do you do now?

You could log on to #vim and ask there, and that's fine - hundreds do.  You could try to google it, but then you've just failed. Most times, trying to find Vim options in google yields more noise than signal.  You could paw through the vim docs yourself, though you've probably already tried that and failed with all of the names you would have called the option. Are they all your options? Are you doomed to a humiliatingly simple response on #vim that, once seen you say, "Bah!  That's it! Gnnnh!"? No. You have other options. In fact, you have :options .

The Options Browser

An almost criminally unknown fact about Vim is that it has this awesome Options Browser built right in to display and modify all of your Vim settings. Jump into vim and type :options to start playing with it. Read all about how to use it in :help :options.

Demonstration

A Vimmer asked on the channel today: How do I blah blah c++ blah label blah blah indent? And I thought, :options! Well, actually, I thought :help 'cino, but then I thought of this cool article to explain the learning moment. Here's how you can find an answer to that sort of question all by yourself:

  1. Open the Options Browser with :options
  2. Search for indent with /indent
  3. Press <enter> to go to that section of the Options Browser
  4. You could just scroll down through the options at this point - at least we're in the right ball-park now... OR Seeing we're interested in C stuff, search for C with /\<c\>

And look! Three C options glaring at us, inviting us to press <enter> on their descriptions to learn more about them. And, indeed, in this case, it's the cinoptions that we're after.

How's that? No more crying over lost options. :-)

Bairui's School of Vim-fu

Wanna skill up in something?

How do you do it? What's your strategy? Do you have one?

One approach I'd like to put more thought into is Project Based Learning. I'll talk more about this in a later article. Here, I want to talk about Deliberate Practice.

You have probably already heard a lot about Deliberate Practice.

If not, just quickly: Deliberate Practice is the process of setting aside some time on a regular basis for the express purpose of challenging yourself at a level slightly above your current abilities in order to improve your skills in that area.

Stay Thy Sword!

I can picture your face now. It's an image of fading hope and growing disappointment. You thought this might be it! The silver bullet of learning and thinking. The answer to all your grokking needs. Well, maybe I can still be of some service...

Bairui's School of Vim-fu

Here is the method I used to go from a Vim dweeb to a power Vimmer in just a few months. The secret lies in an accidental application of Deliberate Practice. It turns out, years later, when I read about this Deliberate Practice stuff... that's what I was doing and I didn't know it! And you know what... it wasn't boring at all. It was fun!

Here's how I did it, addressing each of the requirements for Deliberate Practice:

  1. Mentally demanding, requiring concentration - I do this in the early hours of the morning, before the house pixies are awake.
  2. Challenging tasks - I find these challenges on the freenode IRC channel, #vim. I scroll back through the logs looking for an interesting, non-trival problem that I think is at the edge of my skills. If it's too easy, I skip it - other Vimmers need to grow too. If it looks too hard, I skip it, or write the gist down in a future challenges list.
  3. CANI - Constant and Never-ending Improvement - I put in regular time behind the keyboard every day to sharpen my Vim skills.  Can I keep it up for another decade...? I hope so! :-)
  4. Regular practice - I do it every morning with my first cups of coffee. On holidays... even longer.
  5. Feedback - you need to know if you're still on the path. Personally, I think this is essential and #vim again has the goods. There are people there who actually know what they're doing, and I compare my answer to theirs when I'm done. If I'm confused over a point, I can always ask on the channel to get clarification. It's a freaking Vim Open University!
  6. Have goals - honestly... I didn't, apart from the general desire to improve my Vim-fu. This is an area I could still work on. There are many facets to Vim and now that I think about it, the whole syntax highlighting thing still gives me the willies. If I were a goal-setting man, creating my own colorscheme would have to be on the list.
  7. In-practice self-observation and reflection - always. I'll write a map or macro or some VimL code and look at it and think, yuck!  Sometimes I can refactor it; sometimes I delete it and start again.
  8. After practice reflection when doing Real World stuff - Initially I wasn't conscious of this. Sometimes I would catch myself at a bad habit or not having learned from a recent DP session. In those situations I would, time permitting, undo my poorly implemented solution and redo it again the new way. I try to be more conscious of this these days. I think this is something that naturally grows when you start to pay attention to it.

There. That's the secret to my Continual Vimprovement. I hope it works for you too...

What?! It's still not fun enough?! Hard to please...

Ok... so, I might have a lower threshold for fun than you guys... So, can we make this funnier?

Can You Spare Twenty, Sir?

Gladwell (building on Ericsson) postulates 10,000 hours need to be spent on a craft before mastering it. This relates pretty well with the hours required of a Journeyman. These hours need to be put in over an extended period (they say ten years) for it to return the promised dividends (and Ericsson advises no more than four hours per day of Deliberate (arduous) Practice to avoid burnout.) Of course, you can't sit on the sofa for ten thousand hours and claim to be a zen master; the quality of those hours are far more important than the actual quantity. My Taekwondo instructor's way of saying this was: "practice doesn't make perfect; perfect practice makes perfect."

It happens a lot that when someone in #vim says: "I've been using Vim for twenty years!", they've really been using for nineteen years the same Vim they learned in the first year. This was certainly (and sadly) true of myself; I most certainly didn't spend the vast majority of my twenty (plus!) years with Vim "properly learning" it. It wasn't until around 2010 that I decided to really learn Vim. And it didn't take long, using the techniques above, to get adequately competent at Vim. A few months, really. LearnVim was a happy product of that journey.

Adequately competent? Yes. How good a vimmer do you need to be? My opinion: Good enough to not suck, for whatever value of 'suck' is appropriate to your circumstances. If you don't really need mastery, then you need a lot less hours. How many? Between twenty to fifty hours seems to be the accepted answer. :-o , I know, right?. Twenty to Fifty hours?! That's not so bad... At twenty minutes per day, that's 2 to 5 months. And I believe that with the right approach, twenty minutes of Deliberate Practice per day for two to five months will greatly enhance your Vim skills; or get you to adequate competency if you're just starting out. Would 40 minutes per day reduce your goal time to 4 to 6 weeks? Quite possibly. "Would 80 minutes per day make me a Vimmer after just two weeks?!" I think there's a point where actual number of days count as much as actual number of minutes, but let me know if you prove me wrong.

Currently, I would spend at least twenty minutes every day (as often as I can) in and around various aspects of Vim (outside of any actual coding work I need to do) of pure Deliberate Practice time. I still follow the School Of Vim-Fu as outlined above, hacking together little solutions for interesting puzzles on #vim.

And puzzle is the right word for it, too. I've recently come to consider Vim to be my Suduko. I borrow this notion from Chuck Moore who says the same is true for him of his beloved forth.

Suspecting that I know my audience, I'd wager that a good number of us spend at least 20 minutes a day playing games. Imagine our geniusness if we were to invest that in learning instead?! Even if you are acceptably good at Vim right now, I bet you could afford to spend twenty minutes per day pushing yourself in any number of areas where your vim-fu is currently weak. Just because you don't want to be a master is no excuse for coasting the OK Plateau.

I know, though, right? Learning is boring. It's hard. Nobody has done all the heavy lifting for us, as game designers do.

Game Face

So... let's change it up. What if learning Vim were more like playing a game? What if we had a place where we could meet and compare shiny new creations (like maps, functions, macros, colorschemes, entire plugins, whatever) every day. The system required you to generate something every day. You earned participation points for this. Then we could have daily challenges too. Everyone could participate in the challenge and submit their solutions. Each solution is automatically checked to verify correctness, but also gets peer reviewed by several random 'players' (vimmers) on more of an aesthetic evaluation - is it a pleasant solution or does it make your cat howl? Vimmers are rewarded for doing these reviews. Earn enough points and you climb in rank - giving you access to more power in the system, including being responsible for providing a Daily Challenge pack (challenge + tests).  Did you see that? That's the heavy lifting missing from traditional self-paced learning - provided for us by our team of elite Vim masters - a rank you can strive for by showing us your goods.

Obviously, in my limited way, I am trying to describe a Gamified Vim learning environment. We can add badges and leaderboards but we'd better have something real to keep our Vimmers attracted and engaged too. What? I dunno. Suggestions?

I would so love someone to build this. I'd even be interested in lending a hand. Come... let's play.

Sunday, January 15, 2012

Duplicate Inkscape Layer Across Multiple SVGs

Note: I use Vim for this tutorial. Possibly, your editor or your favourite scripting language could serve as a suitable alternative.

The goal of this tutorial is to show one way of inserting a new layer into many SVG files. The SVG with the layer we want to copy is called the source layer in this tutorial. The term target layer is used here to identify the layer in the destination SVGs under which we want to paste the source layer.

Here is my source SVG containing the source layer, called "red star":

 

Here are two destination SVGs:



In this workflow, we've added a layer with a new object to one of several similar designs. Rather than duplicate that effort across all three SVG files, it would be better to duplicate the layer instead.  Let's do that.

Open the SVG with your source layer in Vim and search for "red star"

  /red star

Save the whole <g ...> tag in register a:

  "ayat

Edit your first target SVG:

  :e vi.svg

Find the target layer. In my files, that's the layer called text:

  /label.*text

Move to the beginning of the <g ...> tag:

  vato<esc>

Paste the star:

  "aP

Save:

  :w

And repeat for all destination SVGs.

Of course, you could open many files at once with:

  :args *.svg

and then:

  :wn

To save and move to the next file.

Seeing the Results

Open the files again in Inkscape (or use File | Revert if they were already open in a session) and you should see your source layer dutifully copied to each of the destination files.



This is a kludge. It is. Hand editing XML files is always a kludge.  This could be better done with a script, possibly an Inkscape plugin.  I might even write it. About time I revisited that corner of the world again. I'll let you know if I do. Until then... hack away on those XML files by hand. :-/

Saturday, January 14, 2012

Gardening in #Vim

I spent most of the day today weeding out silly factoids from Vimgor, the infobot in #vim. I removed about 80 broken entries and cleaned up several factoids along the way. There is still a bit of redundancy and a few broken entries that can't be removed due to the way the forget command is implemented. See the current list of factoids.

The Things Vimgor Knows

(as at January 14, 2012)

:*; :-*; :filetype; :help; :helptags; :kill_kittens; :noh;
:nohl; :open; :unsure:

about; admin; admins; align; anyone; ask him!; ask;
autocomplpop

Bear!; Blockwise visual; backspace; beginning; bgrep;
biscuit; bof; bots; bs; bufexplorer; buffers; but;
butterfly; bw

CSExact; Cowsgo; caps lock; capslock; card back; caret; cat;
cheat sheet; cheatsheet; chip; clipboard; cockie; color;
color-check; colorchart; colors; colorscheme; colorschemes;
colour; colourschemes; command-t; compatible; conque;
cookie; copy; cream; csapprox; ctab

debug; deleting buffers; delimitMate; didn't work; doesn't
work; drchip; duck; dvorak; dvsm

easter egg; easter eggs; easter; emacs; enc; enter;
everything; evil away; evim; example vimrc

FuzzyFinder; facts; ff; fileformat; flying; fuckthecloud;

fugitive; fun; tabs

ggVG; gnome; gnome-terminal; godlygeek; good night!;
goodnight; google; gundo; gvim; gvimgor

hates away updates; he's back!; hello; help!; help2; hi!;
hi; hidden; hjkl; html and php; html with php

idea; imho; indent; indent-guides; infobot; insert mode;
installer; intro; irc; is useless; iterm2

jamessan

Kill!; kittens; knock, knock

LearnVim; LustyExplorer; latest; latex; latex-suite;
latexsuite; leaders; learn vim; learning curve; lettuce;
libtermkey; life; lisp; logs; lol; long lines

MetaCosm; macros; macvim; mail lists; map esc; map;
mapleader; mapping; mixed-filetypes; modeline; monastery;
movement; mru; mswin; mswin.vim

NERD; NERD_Commenter; NERD_Tree; n; nails; nancy; netlib;
neverland; nlnul; noh; nohl; nohls; none; noremap; nr

off-topic; omnicomplete-ruby; ops; owner

paste; pastebin; pathogen; pcre; perl; php with html; pick;
programming fonts; python-indent

quickfix

rails; rails.vim; redir; regex; regexp; reghelp;
relativenumber; rename.vim; reply; respond; restart-vim; rnu

Shelley; s/null; say yes; screencasts; scripting;
scriptnames; scroll; scrooloose; sex; shell;
shell-integration; shibboleth; shut up!; shut up; slimv;
smartindent; snipmate; space.vim; sparkup; speeddating.vim;
statusline; stupid bot; sudo; sudoedit; supertab; surround;
surround.vim; syntastic; syntax

t_Co; tab; tabs; tabular; talk; term-issues; terminal;
terminalkeys; text-objects; thank you; thanks anyway;
thanks; thx; tim-tiny; tips; tutorial; tutorials

ubuntu; ugt; usehelp; user commands; usr_41

vba2zip; vi; vidir; vim; vim's learning curve; vim-bindings;
vim-latex; vim-minimal; vim-mode; vim-tiny; vim.org;
vimball; vimdoc; vimhelp; viml; vimlatex; vimpire; vimrc;
vimscript; vimtabs; vimtiny; vimtutor; vis.vim; vsearch;
vundle

wallpaper; weird error; what's up; whichwrap; why hjkl;
win32-patched; window; windows; works for me; worthless

xptemplate screencasts; xptemplate

you

zencoding

Thursday, January 12, 2012

Nancy Can Dance

#vim's Wolly loves Nancy. It's always Nancy this and Nancy that. Nancy can sing! Nancy can dance... but Wolly, Nancy can't use vim. :-p


Concentric Circles

How I tamed the Tiled Clones tool in Inkscape

The goal of this tutorial is to show you how to create a set of concentric circles with uniform line width using the Create Tiled Clones tool in Inkscape.

First, create your original object in Inkscape. In this tutorial, I'm using a plain circle.


Make sure your object is selected and open the Create Tiled Clones dialog window (Edit | Clone | Create Tiled Clones...)


For this tutorial, I am creating 9 concentric circles. We don't want any of the preset clone styles, so just choose P1: simple translation from the dropdown. Set your rows,columns to be 1,9. Make sure the Use saved size and position of the tile checkbox is off (unchecked). The settings on the Symmetry tab should look something like this:


On the Shift tab, make sure all Shift X and Shift Y offsets are zeroed. Keep the Exponents at 1, and check the per column Exclude tile checkbox:


I wanted neat, even, concentric circles, so I set my per column Scale X and Scale Y values to 100% each. Again use an Exponent of 1:


Leave everything zeroed on the Rotation, Blur & opacity, Color and Trace tabs. Or not, if you want to mess with those settings. But in this tutorial, we'll leave them zeroed.

Click the Create button and you should get concentric clones:


Notice how the successive circles at this stage are evenly spaced apart (good), but have increasing line widths (bad). I haven't found a way to tell Inkscape not to do this for me, even when I try to turn off the Scale Stroke Widths Proportionately affect. :-/ If you know how to do this, I'd love to learn.

So, the rest of this tutorial will focus on making all stroke widths equal.

Select all of the circles:


Unlink them (Edit | Clone | Unlink Clone) or Alt+Shift+D:


Group them (Object | Group) or Ctrl+G:


Open the Fill and Stroke dialog (Object | Fill and Stroke...) or Ctrl+Shift+F:


Set whatever Stroke Style you want. I'm using a plain solid line with width 1px here:


And the final result:


There are many more weird and wonderful things you can do with the clone tool, and I'm only starting to fathom its depths. Until this morning, this tool scared me because nearly every time I tried to use it I would end up with many copies of something I didn't want. Finally with some experimentation this morning, I have tamed the beast! Well... found out where he lives and what he likes to drink, at least. If I have made a flub, omitted something crucial or just plain messed up, let me know.

Saturday, January 7, 2012

Wanna Learn Vim?

There are many tutorials and guides and books and other resources for learning Vim, both available online and in paper form for us dinosaurs who like the feel of turning physical pages and the satisfaction of knowing our indulgences are dwindling natural resources as is the wont of our generation. Rock.

So, why does the world need another Vim learning resource? I guess it doesn't. But LearnVim is here to stay anyway. So there.

Intended as an eventual guide from beginner through to advanced topics, it is written more as a collection of good resources, habits and tips to get the newcomer up and running in Vim as quickly and effectively as possible.

The post-beginner sections are still in draft form, so if you're looking for something a bit meatier, this is not the guide for you... yet.

A big part of learning Vim is mastering the regular expressions within Vim. LearnVim does not attempt to cover regular expressions. Instead, I offer you VimRegexTutor for that journey.

As always with these sort of projects, constructive feedback most certainly welcome.

Friday, January 6, 2012

Vim is More Fun


I woke up one morning thinking how much more fun Vim was than a poke in the eye with a blunt stick. At least, that's how some people view the venerable editor. So... the Vim is More Fun series of Vim and Vigor cartoons was born. I will stop at these three for now:

Vim & Vigor 5: Vim is More Fun 1 
Vim & Vigor 6: Vim is More Fun 2 
Vim & Vigor 7: Vim is More Fun 3 

 Is Vim. Is Fun.