Websocket Client for a mobile game in Godot. Creating a protocol to understand byte array being passed.

Currently I have to implement a Websocket client for a Godot mobile game.

What was really fun about it was deciding on the data transfer specifications. We want the data to be encoded and compressed on server side. We also want the client to decompress and decode the received data.

This sounds fairly simple but..there’s a small issue (it always is 😀 ).

The data is passed as a byte array (in Godot a PoolByteArray). To decompress it on the client side we need one piece of vital info: the size of the uncompressed original data.

So when the game received this compressed/encoded data, it scratches its head. It can’t do anything with it, it needs the size of the uncompressed data to decode it.

We can’t put this information in the original data sent from the server. That data is going to be already compressed – to decompress it we need the data inside the compressed data.
It’s like having the password for a .zip file inside the .zip file.

What we need to do is have the password outside the .zip file. In our case, we need the size of the uncompressed data outside of the compressed data, in an uncompressed format.

So if the size of the uncompressed size is 42.

Converted to string we get “42”. “4” converted to byte is 0x52. “2” converted to byte is 0x50. The byte array describing the size is thus: [0x52,0x50]. When the client gets this data, it will convert the byte array to a string representation first: “42”. Then it will try and parse it into an int, getting 42.

Where to put it? How to send it?

Here’s how I ended up doing this:

On server side I do the usual thing with the data.
1. Encode it with utf8.

2. Compress it.

So far so good. I end up with a byte array.
Now I need to attach to this byte array the information about the size of the uncompressed data.

I could just append it to the end. But how will the client know what is the compressed data and what is the information about the size of the uncompressed data? All it sees is a byte array, it doesn’t know where one ends and another begins.

One solution would be to decide on a “header” byte sub-array of fixed size. If the maximum size of the data is going to be 4096, I’ll need at least a header of 4 bytes in size (each byte will hold one number).

But what if the size is going to be smaller than 4096? Say 5. Then I’ll have to pad the remaining bytes with either “0” char or the nullbyte.
This presents 2 issues: one, it requires more code&work on the client side. Two – it wastes bandwith since all we need is just 1 byte of info (and we’ll send 3 extra “empty” bytes).

I chose another more elegant solution that also saved bandwith.

By convention, we’ll mark the end of compressed data with a nullbyte (0x00). After this nullbyte we put our uncompressed data size information in byte array [0x52,0x50]. Assuming the compressed data looks like: [0x01,0x05,0x99], by appending this nullbyte marker and the uncompressed size we’ll get:
[0x01,0x05,0x99,0x00,0x52,0x50]

The client will then start looking for a nullbyte from the end of the byte array (because nullbytes might be present in the compressed data itself). Once it finds than nullbyte, it will extract the sub array from the nullbyte location to the end of the byte array. In our case it sees 0x00 at index 3. It knows that from index 4 (inclusive) to the end of the array is the info about the uncompressed size.

Now the client has [0x52,0x50] byte array. Converted to string it gets “42”. Converted to int it gets 42. Now it can use this info to decompress the compressed data [0x01,0x05,0x99] (dummy example, not actual compressed data).

Of course, we perform all kinds of checks on the client side to avoid out of range errors and other data issues.

There might be smarter ways of passing along this information. But for my use case it works great!

Thank you for reading!

[EDIT] Some friends told me there might be better solutions for this issue. Mainly about prefixing the data, using htonl and possibly a header. I’ll keep you updated with how things ended up (I’m creating this backend server as a mock server so I can finish the client code. The actual backend server will be implemented by a backend developer).

How to learn Photoshop fast in 3 months!

Photoshop is arguably the best graphics editing software in the world. It has incredible capabilities and a fairly easy learning curve.

It’s quite easy to learn Photoshop. You need to follow a certain path though. You need to structure your learning. You need to pick your sources of knowledge.

Learn fast You must - Yoda | Meme Generator

Let me give you an example. Let’s say we have 2 people called Tom and Jerry. Both of them want to learn Photoshop.

Tom.

source

Tom starts looking at random tutorials. Whatever fancies his interest, he watches. Since he’s a beginner, he doesn’t completely understand what’s going on. But he tries as best as possible to imitate what he sees. He’s eager to learn fast but gets disappointed on advanced tutorials.

After 3 months Tom is frustrated. He knows some techniques, true. But he doesn’t know how to do new tasks.

source

Jerry.

source

Jerry on the other hand uses a more structured approach. He starts by watching a short introductory tutorial from Skillshare or Udemy. He knows that short articles and videos don’t have the best structure and completeness.

After that first course the starts experimenting on his own, for couple of days. Afterwards he picks up a more advanced course. There he learns the 80% most used features of Photoshop. He experiments some more.

Finally he ends up watching specialized courses, when he needs to.

After 3 months Jerry is confident in his abilities. He knows the basics very well. He continuously builds upon his solid foundation of Photoshop knowledge.

source

What does it mean?

The moral is simple. Make a game plan. Start with the basics. Practice. Then learn the medium stuff (used 80% of the time). Practice some more. Finally, watch specialized tutorials when needed.

In 3 months you can be a capable Photoshop user. All new knowledge will have a solid foundation to grow. You’ll be confident and happy while using Photoshop.

This is the “true” fast way of learning Photoshop.

Avoid temptation.

The desire to learn “fast” it’s common. How many “learn in 24 hours SUBJECT” books exist?

You have to be smart about it. Jumping into an advanced tut without understanding the basics – not good. It’s a recipe for frustration and limited learning.

And it’s not even that hard to learn the basics. Photoshop may seem daunting at first. But once you understand the concepts it’s fairly simple. It’s just pixel manipulation and some common tools. After you understand that, you can improvise on your own.

How long it took YOU to learn Photoshop?

In 6 weeks I learned the basics and advanced Photoshop features with Deke Mclelland’s “Photoshop one on one” course. Another 2 weeks I solidified the existing knowledge. 4 more weeks I used to follow various specialized tutorials (photo manipulations mainly). Total: 3 months.

I went from 0% to 80% in 3 months. Over the following years I’ve kept improving my skills, of course. But those 3 months were the most important step I took. I did this full time. Part time would’ve taken 6 months, maybe 9.

Without that structured approach I wouldn’t have a solid grasp on Photoshop.

Do I need to become a Photoshop “ninja”?

Ninja, Războinic, Japonia, Asasin, Sabie, Masca, Umbră

It’s important to ask yourself this question. How do you intend to use Photoshop during your life/career? Is it something you’ll be using heavily? Or you’ll be using it sparsely, here and there for a quick edit?

If you need it sparsely, you probably won’t need to get really good at Photoshop. Just following tuts will probably suffice.

If you need it heavily then you WANT the structured approach. Without it you’ll waste time.

Do I need to follow your plan exactly?

No, you don’t. That plan worked for me but it might not work for you. Make your own plan. But make sure of 2 things:

  1. Start by understanding the basics really well.
  2. Follow a structured approach.
  3. Aim to learn 20% of features used 80% of the time.
  4. Use quality and structured tutorials, not articles. Articles are good for specialized knowledge, not so good for complete training.

How hard is it to learn Photoshop well?

Laptop, Femeie, Educaţie, Studiu, Tineri, Calculator

95% of the time it’s very easy. It’s just new knowledge. Photoshop is well thought in terms of usability and features. With a good instructor you’ll have no problems learning Photoshop with ease. The rest of 5% will be harder. Usually it will consist of arcane features. Or concepts that are hard for you personally.

All in all it’s quite a fun experience. I remember the joy of learning during those 6 weeks. Every day was fun and adventurous. I was feeling really good about going this structured and solid way.

I also remember the bad times. The first time I opened Photoshop I closed it after 30 seconds, haha. It just seemed so alien and complex.

Just after I’ve made a serious commitment to learn Photoshop, I ended up enjoying the process. And learning with ease.

What courses do you recommend for learning Photoshop?

BASICS.

For learning Photoshop basics/medium I’d recommend the one I used, “Photoshop One on One” by Deke McLelland. It was a complete beast of a course, starting with the basics and continuing well into the advanced. Deke was a great teacher too. The version I used though was for Photoshop CS6 (or 5?).

I haven’t watched the updated versions (so I don’t guarantee anything), but I guess they’ll also be good. Who knows, maybe even better than the originals.

Here are the links for Photoshop one on one (the 2021 version):

Fundamentals, Advanced, Mastery.

You can also learn Photoshop basics following these courses on Udemy. I haven’t tried them but lots of people seem to like them.

ADVANCED/SPECIALIZED

For specialized and advanced knowledge, check out my courses. I’ve written quite a few of them. I’ve made them easily accessible even to beginners. So you could jump directly into them. But like I said, it depends on what your goals and current skills are.

  • Do you already know the basics? Cool, then check them out.
  • You don’t know the basics AND you don’t care about learning Photoshop completely? Cool, check them out.
  • You don’t know the basics AND you want to learn Photoshop really well? Start with a basics course. Afterwards check them out.

(they are paid courses mostly. But I also have a very good completely free course.)

Here are some things you will create while following my advanced but easy to follow photoshop courses:

You can also check out my YouTube channel. It has a continuous stream of Photoshop quick tips & techniques.

The cat in the tree.

The weirdest thing happened to me today.

I was at the end of a biking session through the outskirts of the village where I’m residing. Near the end of the circuit I spotted a rosehip bush.

I’m a big fan of rosehip fruits (I think?). They are tasty and have lots of vitamin C. Thing is – they are usually tough and hard to ingest. When it’s cold outside and then hot again they “thaw” and become softer.

So I’m particularly on the lookout for soft rosehip fruits.

This particular bush was known to me and I thought – let’s stop and see if the fruits are soft.

I dismounted my bike and proceeded to inspect the fruits. True enough – they were soft – and BIG. Tasty! Trouble was, I didn’t have any bag of sorts to pick some up.

While thinking that next time I have to bring a bag I saw a orange patch of fur in the tree just next to the bush. WTF?

At first I thought it was a dead cat. Someone found it funny to put this dead cat in the tree. The height was about 2 meters, the tree was rather fluffy and with small branches.

As I rounded the tree to see what the hell was this I saw the “dead” cat slightly moving. Damn.

I looked closely and the cat was actually alive, just stuck in this weird contorted position in the bushy tree. It was possible for it to come down but I guess some kind of freeze occurred in its feline brain.

It did look scared and it meowed sadly. I petted it tentatively to accommodate her and not have her scared for the next operation. I picked her up with some difficulty (bushy tree and thorns nearby) and put her down. She bolted towards the village instantly.

The weird thing was the following: I was listening to Fast and Slow thinking ebook. I just finished listening to a part about the invisible gorilla experiment (if your attention is focused on something you might miss weird/strange things).

More than that – stopping by that rosehip tree was a rather random decision. I inclined toward not stopping but barely convinced myself to stop.

Thirdly – the cat was orange on an brown-orange tree. Very hard to spot if you weren’t looking. Not making any sounds either (until I looked at it and talked to it).

If I somehow missed seeing it and continued on my journey the cat would still be there. If someone would tell me later that there was a cat in that tree I would’ve found it impossible. I didn’t see it so it didn’t exist.

It was like some hidden power made be decide to stop and look for rosehip fruits and look up by chance. (it’s not a very favored fruit in my country and I doubt many people would be interested in that particular location). Of course, it’s also pure chance but when weird stuff happens to you, you tend to attribute it to some “deus ex machina”.

The reason I mentioned it is that it was a weird and notable experience. Like the universe decide it to show me the practical side of the “invisible gorilla” immediately after I’ve learned about it.

That’s one interpretation of course. Another is that the importance and meaning of events is not intrinsic. That is – they have no absolute truth value to them. They are what we interpret them to be.

The world is thus not the world, just our interpretation of it. Choose to interpret it differently (through experience, chance or learning) and the world changes (from our perspective).

Food for philosophical munching! 🙂

On a side note it also dawned to me how much my thought patterns influence my mental and physical state. If my thoughts say “you’re depressed, you’re in a shitty situation, the future is bleak” then I’m going to act accordingly.

I tried inserting (consciously and with some power) some positive thoughts (“you’re happy, everything is great, the future is awesome”) and I’ve noted a spike in the mental well-being.

That’s obvious in theory but not often experienced in practice. To know about the fire it’s not to feel the fire. (Lord of Light by Zelazny has a beautiful thought provoking section on this topic, about words and their meaning).

I think I’m going to consciously inject positive thoughts, to form some sort of habit and reflex AND to create some positive mental inertia. I’ve tried this before (CBT stuff) but now I feel I understand and believe in it more.

Convenient Utilities Linux. Show broken links, users file count&size, big file list, etc

You know what annoys me sometimes? That I can’t see quickly a list of existing users on linux. Don’t get me wrong. I love me a bit of finger gymnastics and awk every once in a while. But to have to type all those chars EVERY time…that’s annoying.

cat /etc/passwd | awk -F: '{print $1}'
cut -d: -f1 /etc/passwd

Each one of the lines above will do the trick. It’s not much typing but why not a more convenient command?

That’s why I started writing a list of convenient linux utilities. For the convenience lovers.

Some of the utilities are rather simple in execution but convenient to use. Other are a bit more complex – filenames with spaces, I’m looking at you! From now on I swear, NEVER I’ll put spaces in my filenames again. 😛

In principle one could even use one liners AND deal with filenames that have spaces. BUT there’s a small nasty side effect – if there are no results for find (or the command that sends output to xargs) the command executed by xargs will usually show help output. Couldn’t figure out how to skip it in the one liner easily. In a script it’s doable.

Oh, and some scripts are a bit slow. That’s a side effect of calling xargs -n1 mycommand with thousands of input lines. Sometimes it can’t be helped if you desire certain results.

For example to show the biggest files fast you use find with -printf option. But It displays the size in bytes, not human readable. Right now I used this implementation. Parsing the left side raw bytes into human readable output it’s on the to do list.

On the other hand using du -h and xargs will display nicely formatted size – at the expense of speed.

Right now there’s just 7 utilities but I’ll keep adding to the list. I’m already using them on a daily basis – and not just because I wrote them.

Here’s what they do:

showbf

  • show big files. First 10 by default, current user, current dir.
  • Use it with different user, different dir.
  • Works well with files that have spaces or other “funky” chars.

showus

  • Show a user disk usage and file count in a dir. Calculates by adding file sizes owned by user.

showbl

  • show broken links. Use custom dir or custom user.

showg

  • Show groups, every group on one line.
  • It’s a simple one liner (in the script) but quite convenient to use in this form.

showp

  • Show paths added to $PATH, each on one line

showu

  • Show users, each on a separate line.

wtw

  • What’s the word? A simple one liner (in script) to show possible words for regex.

Get them while they’re hot HERE (github)

BIG list of text processing recipes on linux. Featuring vim, tr, cat, tac, sort, shuf, seq, pr, paste, fmt, cut, nl, split, csplit, sed, awk, grep.

Here’s some more cool text processing techniques that I wrote. It starts with a simple regex tutorial. Then it continues to explain a wide variety of general text processing tools and their purprose. Finally I’ve added all the previous guides (from grep, sed, awk, vim) into one place.

Enjoy and let me know what you think! 🙂

I recommend the following books if you want to learn more about text processing:

Definitive Guide to sed – by Daniel Goldman


Sed & Awk – Dale Dougherty & Arnold Robbins


Effective awk programming – by Arnold Robbins

Quick grep reference and tutorial.

Here’s a short but quite comprehensive grep reference and tutorial.

Snippet:

Search for match (the string ‘hello’) in file (called generically ‘file’). Display every line that matches pattern (in this case every line containing ‘hello’)
grep hello file

Search for match in file and use quotes on the pattern. Not required unless you have special chars that are expanded by the shell. (in this case not required)
grep ‘hello’ file

Search for a match in multiple files
grep hello file1 file2

Search for match in all files in current dir (will show a warning if dirs are present too)
grep hello *

Search for a match in all files in curent dir. Don’t show errors if dirs are present. (grep treats dirs just as ordinary files and tries to “read” them). ‘-s’ is for silent. Will also skip errors regarding nonexistent files.
grep -s hello *

Search for a match in all files than end with ‘.py’
grep hello *.py

simple-awk. A practical and simple awk guide.

I wrote a simple but practical guide to awk. There are some surprisingly powerful and mind blowing techniques towards the end.

Here’s a snippet from the end of the guide (the beginning starts much simpler):

#!/usr/bin/awk -f

# Declare custom func outside
function throw_ring(who){
	if (who=="gollum"){
		return 0
	}
	else if (who=="frodo"){
		return 1
	}
}

# On all records matching /ring/
/ring/{
# Find gollum or frodo
if (match($0,"gollum")){
	was_thrown=throw_ring("gollum")
	#use ternary if/else. If was_thrown is true (or bigger than 0) return "THROWN". Else return "NOT THROWN"
	print "the  ring throw status is ", was_thrown?"THROWN":"NOT THROWN"
}

if (match($0,"frodo")){
	was_thrown=throw_ring("frodo")
	print "the  ring throw status is ", was_thrown?"THROWN":"NOT THROWN"
}

}

This is a rather lange script but simple when you break it into pieces.

Start by declaring a custom “throw_ring” function.

on records that match /ring/ exec the following operations:

check if that record (which contains /ring/) contains “gollum”. If yes get “thrown_status” value.

Use the ternary operator to return either “THROWN” or “NOT_THROWN”.

Do the same for “frodo”

The output will look like: the ring throw status is THROWN

This one is also one of my favourites – inverse of a regex match.

#!/usr/bin/awk -f
{
	reg="[Bb]ilbo"
	if (match($0,reg)){
		bef=substr($0,1,RSTART-1)
		aft=substr($0,RSTART+RLENGTH)
		pat=substr($0,RSTART,RLENGTH)
		print bef,"|",pat,"|",aft
	}
	else print $0
}

We start by checking for a match. If a match exists commands inside if will run (since it will return a value greater than 0).

‘bef’ is the substring before the match. We cut it from position beginning (string indexing starts at 1) up to the start of the match (to RSTART).

‘aft’ is the substring after the match. We cut it from the end of the match up to the end. Note how we use “RSTART+RLENGTH” to calculate the first char AFTER the end of the match. This it’s a bit confusing with indexing starting from 1. If you’re used to 0 indexing you would want to add a 1 (“RSTART+RLENGTH+1”) but it’s not needed here because indexing starts at 1.

Note the comments starting with #

Check out the rest of this cool awk guide here.

6 bad worries and the needed attitude toward them.

This is an excerpt from “Think and Grow Rich” by Napoleon Hill. It summarizes an attitude I think it’s very healthy (towards common worries).

The six basic fears become
translated into a state of worry, through indecision.

Relieve
yourself, forever of the fear of death, by reaching a decision to
accept death as an inescapable event.

Whip the fear of poverty
by reaching a decision to get along with whatever wealth you
can accumulate WITHOUT WORRY.

Put your foot upon the
neck of the fear of criticism by reaching a decision NOT TO
WORRY about what other people think, do, or say.

Eliminate
the fear of old age by reaching a decision to accept it, not as
handicap, but as a great blessing which carries with it
wisdom, self-control, and understanding not known to youth.

Acquit yourself of the fear of ill health by the decision to
forget symptoms.

Master the fear of loss of love by reaching a
decision to get along without love, if that is necessary.

Kill the habit of worry, in all its forms, by reaching a
general, blanket decision that nothing which life has to offer
is worth the price of worry.

I think so highly of this advice that I’ve put it over my desktop wallpaper. I will follow this advice and attitude as best as I can, for I have the intuition it is the right one.

The reason I’m sharing this is because you might draw some inspiration from it. If you can read Napoleon’s book – do it. Great, great stuff.

Some people say that the chapters on the infinite intelligence and ether vibrations are bullshit. I disagree.

We don’t know everything. Not by far. Some form of universal infinite energy influenced by thought and desire doesn’t seem so far fetched to me.

We know that by observing a certain thing we influence the properties of that thing (from quantum theory).

Another thing that stuck to my mind was the senses analogy. Imagine if you lacked the visual sense. All your life you would not be aware of vision as an aspect of the world – even if it existed.

Since we are a rather mundane biological entity it follows we don’t posses a myriad of senses. AKA – we’re not some super being capable of experiencing the world in a vast way.

A human is to such an ideal being as an ant is to a human. An ant experiences the world through an array of senses much limited when compared to ours.
We too are limited in our sensory experience when compared to this fantastic superior being.

An ant that hears Bach will miss it’s meaning – probably interpret it just as some random wacky sounds.

(Speaking of ants hearing Bach a beautiful SF book is “A roadside picnic”. After an event known as the Visitation there’s a an area full of wonderful and dangerous alien tech/energies. People who visit it risk horrible deaths or awesome rewards if they get they’re hands on something valuable.
The name of the book comes from the following theory: this visitation event might be similar to a roadside picnic made by humans. We might leave behind things such as plastic wrappers, bottles, cigarette buts, a lighter, a fire, etc. An ant visiting the leftovers of this picnic will have the same experience as the people visiting a Visitation Zone).

Who’s to say which divine sensory experience bypasses us completely because we’re unable to experience it? Who knows all the secrets an component parts of universe and life?

Basically we know jacksh*t even with all the scientific progress of our time (if you’ll excuse my french).

Anyway, I diverted heavily from the original subject!

No matter. Following the advice from above I am not worried about what other people think, do or say. Or at least I am trying.

(On a side note fear of criticism has its roots in our social conditioning. It’s part of our genes. It has to do with group acceptance which meant survival in the stone age and before.
A certain compromise must be reached between “I don’t give a f*ck and I walk naked in the streets painted blue and screaming Evrika” and “I base all my life decisions on how they make me appear to others.” Preferably geared towards the former. :D)

Wizardly Tips Vim (full version on Github)

As promised here are the much wanted Vim tips. This is just a SNIPPET.

Full tutorial freely available on github (which will be updated regularly, this post not so much)

Wizardly Tips Vim

A fast way to benefit from vim’s power. Ideally you should read a good book and the :h section. But if you’re in a hurry this should serve you well.
This is a list of somewhat unknown but highly useful Vim tips and tricks. I try and keeep the list succint by not showing well known or less useful commands.

HOW TO READ SHORTCUTS:

<Esc> – Escape. Usually you should press the key, not type it. When you see ii<Esc> you type ii and then Escape, not ‘ii` literally.

<C-g> – means Ctrl+G

g<C-g> – means press g then press Ctrl+g

<S-g> – means press SHift+g

<C-Z> – means Ctrl+Shift+Z (Shift is not shown but implied since we have an uppercase Z)

<zZ> – z followed by Shift+Z

<C-m><CR> – type Ctrl+M followed by Enter. <CR> is Carriage Return (another word for Enter key)

Find files and send them to vim.

find ~ -size +10M | vim -
  • find files and open the results in vim. While in vim you can press gf to open a file (from the results provided by find) in vim.
  • HINT: if your file has spaces vim will complain that the file is not in the path. This happens because it truncates the file when a space appears, thus trying to reach the file at an erroneous path. So instead use <S-v> to select the hole line and then press gf
  • HINT2 – you can use any other command that outputs to stdout and send it to vim.
  • HINT3 – you can open the file under cursor in a new window with <C-w>

Encrypt

  • You decide to write your secret journal using vim. Trouble is – anyone can read your unencrypted text files. Or can they? By using vim -x mysecretfile.txt you use encryption on file. You’ll be asked for a key (password) to encrypt/decrypt your file. Warning – if you forget your key bye bye file.
  • HINT – you can also encrypt a file after you open it by typing :X

  • I’m still amazed by how many vim users totally ignore the power of register playback. That is – you record your actions into a register and play those actions back. It’s a bit weird to wrap your head around it but once you do – you’ll be amazed.
    Here’s how it works
  • press qa to start recording your actions into register a
  • Perform some actions that you want repeated. Here’s a very useful example for coders – custom line by line editing. Let’s say that you need to go line by line, search for the word “foo” and place it in tags () and place those tags again on the same line at the end of the line.
  • This is a pretty complex scenario. Doing it by hand for thousands of lines it’s PITA (Pain In The A*s). What can you do? Write an awk script? A Python script? NOOOOO. You use vim register playback.
  • So you start your action by implementing a movement that will go to the next line or the next pattern. This is very important because it will make the playback “smart”, as it will go on the next line or pattern and do the work.
  • In your case you would start by typing /foo and pressing <CR> (Enter). This takes care of always finding the next pattern and working on it.
  • No do your desired operations. i<<Esc>ea> which will insert the bracket, then to normal mode, go te end of the word, append the closing bracket.
  • next you copy the whole bracketed foo by pressing ya> (yank all in between brackets) followed by $p (go to end of the line and paste)
  • Your work is done. You press q to stop recording.
  • time for PAYBACK …ah, I meant PLAYBACK.
  • you press @a to playback the contents of register a (into which you recorded your actions). You watch amazed how vim repeats “smartly” the operations you just performed previously.
  • Now you can press @@ to repeat the previous playback as many times as you want. Or you could press 10@@ to repeat the playback for 10 times. Or if you want this applied to your whole file type :% norm @a – which means – apply the macro to all lines.

Open files in own tab/win

  • Your girlfriend’s father comes to visit you. You want to impress him by opening a bunch of text files, each in it’s own window in vim (and show him that you’re very smart and tech savvy)
  • You write vim -o f1 f2 f3 f4 to open the specified files with windows split horizontally. use vim -O f1 f2 f3 to split them vertically. If you have lots of files and you dont want a hundred narrow windows use vim -o5 *.txt to open a max of 5 windows (horizontally stacked).
  • You could instead open them in tabs by using the same syntax vim -p f1 f2 or vim -p5 *.txt

Info

  • The <C-g> magic – it displays file name and position. g<C-g> will display number of words, num of lines and other useful stats.

Enter special chars

  • Enter digraphs (speciar chars). Use <C-k> in Insert mode and type the digraph code. For example you can enter the pound sign using ‘Pd’ (£). Type :h digraph-table for more info. To just view the codes type :dig

Quickly write buffer to disk

  • ZZ – write the buffer to disk if modified and exit. I bet you didn’t knew that – but if you did BRAVO, you know how to quit Vim!

Sort

  • :%!sort -u – sort all lines and remove duplicates. % refers to the range and it means all the lines. You could use 1,5 for example and it would only sort lines 1 to 5. The ! in this context means – execute an external shell command (in our case sort) with the range as stdin, when you’re done put back in place the stdout from that command.

Paste register

  • While in insert mode press <C-r> followed by a registry, such as a or b or @ or : or +. eg: <C-r>a. This will insert the contents of the registry at cursor.

Insert mode navig

  • While in insert mode press <C-h> to backspace a char, <C-w> to delete a word backwards, <C-u> to delete until the beginning of the line (all without leaving Insert mode)

Autocomplete

  • Did you knew you also have autocomplete by default? While in insert mode press <C-n> or <C-p> to cycle through possible autocompletions.

How to quit Vim

  • There are lots of famous memes about people not knowing how to quit Vim. Here’s a little secret – you can quit the current buffer(if you opened just a single file) without writting to disk by pressing ZQ.

Repeat Insert

  • Everyone knows that you can insert a character repeatedly using a command such as 20i-<Esc> – which will insert 20 ‘-‘. Or you could do something like 10aHello World Of Vim.<Esc>. This will do 10 appends of the phrase ‘Hello World Of Vim’

THIS IS JUST A SNIPPET. Full Tutorial on github, freely available and regularly updated.