Read a code can be a pain, especially if you wrote it years ago or if someone else have to read it later. Fortunately, you are using Sublime Text !
So I recently learned to add space to my code; add some empty lines to separate blocks of related content and, more recently, between brackets.
Here is the solution to automatically add space between yourĀ brackets in Sublime text 2 or 3.

<?php

echo('Bonjour monde !');

?>

become

<?php

echo ( 'Bonjour monde !' );

?>

Here is how to tell to Sublime text to do that automatically

Open the user key binding file (Preferences -> Key Bindings – User) and copy this code :

// Auto-pair brackets
	{ "keys": ["("], "command": "insert_snippet", "args": {"contents": " ( $0 )"}, "context":
		[
			{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
			{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
			{ "key": "following_text", "operator": "regex_contains", "operand": "^(?:\t| |\\)|]|;|\\}|$)", "match_all": true },
			{ "key": "selector", "operator": "equal", "operand": "source.php" }
		]
	},
	{ "keys": ["("], "command": "insert_snippet", "args": {"contents": " ( ${0:$SELECTION} )"}, "context":
		[
			{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
			{ "key": "selection_empty", "operator": "equal", "operand": false, "match_all": true },
			{ "key": "selector", "operator": "equal", "operand": "source.php" }
		]
	},
	{ "keys": ["backspace"], "command": "run_macro_file", "args": {"file": "res://Packages/Default/Delete Left Right.sublime-macro"}, "context":
		[
			{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
			{ "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
			{ "key": "preceding_text", "operator": "regex_contains", "operand": "\\( $", "match_all": true },
			{ "key": "following_text", "operator": "regex_contains", "operand": "^ \\)", "match_all": true },
			{ "key": "selector", "operator": "equal", "operand": "source.php" }
		]
	}

Explanation

The interesting part is :

"contents": " ( $0 )"

This is the result you want : [a space], the bracket, “$0” is where your cursor will be, then, the closing bracket.

Then, on line 10, you have to do the same for the case when your type a bracket to enroll your current selection :

"contents": " ( ${0:$SELECTION} )"

After that, on line 16, we manage the suppression of the open-bracket, to remove the close-one.

You can do the same for all type of brackets : square “[” and curvy “{“.

Enjoy.

Links : Sublime Text


React to this article!

Did I miss something? I'd really liked to know your though about this.
If you like this article, please šŸ“£ share-it!

You can also follow me on my blog, on Medium, and reach me via Twitter and LinkedIn

One thought on “Sublime Text : Add space to your code

Leave a Reply