Search This Blog

Showing posts with label sublime. Show all posts
Showing posts with label sublime. Show all posts

Saturday, March 29, 2014

How to create a sequence of replace commands to change your file

Use existing plugin: RegReplace

We could write a custom plugin using the Sublime API or try to use a plugin that promises to offer this functionality already: https://github.com/facelessuser/RegReplace

Demonstration

We have a following structured but not consistently formatted data that we would like to adjust so it is easier toread and work with.



To reformat the text we can use the above plugin and define a series of regex that match and modify text.
  • Installed RegReplace plugin.
  • Create a reg_replace.sublime-settings in your Sublime2\Data\Packages\User\ directory and define the regex commands we want to use.
{
    "replacements": {
        // add teh .<digit> when is missing
        "ig_order_add_dot_digit": {
            "find": "([0-9][0-9]) at",
            "replace": "\\1.0 at"
//            "greedy": true,
//            "case": false
        },
        "ig_order_add_dot_digit2": {
            "find": "([0-9][0-9]) *- ",
            "replace": "\\1.0 - ",
            "greedy": true
        },
        "ig_order_fix_spaces": {
            "find": "/(201[0-9]) *",
            "replace": "/\\1 "
        },
        "ig_order_fix_spaces2": {
            "find": "-   -    -  ",
            "replace": "-    -    -     "
        },
        "ig_order_change_android_str": {
            "find": "AndroidApp",
            "replace": "AndrAp"
        },
        "ig_order_remove_str": {
            "find": "/s ",
            "replace": " ",
            "greedy": true
        },
        "ig_order_fix_header": {
            "find": "(Date) *(Time) *(Activity) *(Market) *(Period) *(Channel) *(Currency) *(Size) *(Level) *(Stop) *(Type) *(Limit) *(Result)",
            "replace": "Date        Time    Activity Market                                               Period              Channel Cur Size Level  Stop Type Limit Result",
            "greedy": true
        },



        "ig_transactions_fix_header": {
            "find": "(Type) *(Date) *(Ref) *(Market) *(Period) *(Opening) *(Ccy) *(Size) *(Closing) *(P/L)",
            "replace": "Type    Date        Ref         Market                                                  Period            Opening Ccy Size    Closing P/L",
            "greedy": true
        },
       "ig_transactions_add_dot_digit": {
            "find": "([0-9][0-9]) +£",
            "replace": "\\1.0 £"
        },
        "ig_transactions_add_dot_digit2": {
            "find": "(£ +.*\\..* +)([0-9]+) +",
            "replace": "\\1\\2.0 "
        },
        "ig_transactions_fix_plus_minus_sign": {
            "find": "([0-9]+\\.[0-9]+ +[0-9]+\\.[0-9]+ +)([0-9]+\\.[0-9]+)",
            "replace": "\\1 \\2"
        }

    }
}
  • Define the final  regex command to run and associate a a keyboard short in Default (Windows).sublime-keymap file
[
{ 
    {
        "keys": ["alt+ctrl+t"],
        "command": "reg_replace",
        "args": {"replacements": [
                                    // orders
                                    "ig_order_add_dot_digit",
                                    "ig_order_add_dot_digit2",
                                    "ig_order_fix_spaces",
                                    "ig_order_fix_spaces2",
                                    "ig_order_change_android_str",
                                    "ig_order_remove_str",
                                    "ig_order_fix_header",

                                    // transactions
                                    "ig_transactions_fix_header",
                                    "ig_transactions_add_dot_digit",
                                    "ig_transactions_add_dot_digit2",
                                    "ig_transactions_fix_plus_minus_sign"


                                ],  "find_only": true}
    }
]
  • When you activate the regex chain command it will first show what part of the file are going to be changed
  • Accept the "yes" option at the bottom and reformat the file

How to write a plugin for Sublime editor

Below is a list of links for Sublime API and Sublime commands if you want to write a custom plugins.

Sublime API

https://www.sublimetext.com/docs/api-reference
https://www.sublimetext.com/docs/2/api_reference.html

Commands

http://sublimetext.info/docs/en/core/commands.html
http://www.sublimetext.com/docs/commands

Debug best practices

Once you follow the steps below everything you do in the editor will be logged on the console.
  • Open Sublime console: Ctrl+~
  • Enable verbose and debug within the editor
sublime.log_commands(True)
sublime.log_input(True)
  • Example commands to try on the console 
view.run_command("goto_line", {"line": 7})
view.window().run_command("show_minimap", {"key": True})



Thursday, October 3, 2013

Beautiful code formatter for JavaScript in Sublime

I needed recently to work with some JavaScript code to understand how bookmarklets work in Google Chrome. Unfortunately the js code was often not well formatted and difficult to read.

Problem

How to automatically reformat JavaScript code so it looks beautiful and is easy to read.

Solution

I recommend this online site if you don't need to have this functionality in your editor of choice: http://jsbeautifier.org/. To enable beautiful code formatting in Sublime you can:
Testing

To test that the node.js and the necessary plugin is installed correctly you can run the node virtual machine and try to import the module:
 
$ node
> require("js-beautify")
{ [Function]
  js: [Function: js_beautify],
  css: [Function: css_beautify],
  html: [Function],
  js_beautify: [Function: js_beautify],
  css_beautify: [Function: css_beautify],
  html_beautify: [Function] }
>

To test that the plugin is installed successfully in in sublime you can:
  • check sublime tree directory
  •  
     ... Sublime2\Data\Packages\CodeFormatter\
     
To trigger the formatting:
  • Menu tools -> Command Palette (Cmd+Shift+P or Ctrl+Shift+P) and type `Format`.
  • The default keyboard shortcat is  ["ctrl+alt+f"] or 
  • If you want to run the command from the console
  •  
     view.run_command("code_formatter")
     
References

https://sublime.wbond.net/packages/CodeFormatter
http://nodejs.org/
https://npmjs.org/package/js-beautify
http://jsbeautifier.org/

For further info about node.js and the JavaScript virtual machine functionality

http://www.nodebeginner.org/#hello-world
http://stackoverflow.com/questions/2353818/how-do-i-get-started-with-node-js

Tuesday, October 1, 2013

Sublime macro error

Macros are a very power full tools when working with text editors. If you repeatedly typing the same commands/characters to edit your text you can always try to capture them and save as a macro.

Problem

A macro that tries to capture the ALT+F3 keyboard shortcat to highly all the word occurrence in text (more about this here) doesn't work and is erroring out on the console with this message.
 
Unknown macro command find_all_under

Troubleshooting

You can reproduce this by trying these steps:
  • Create a new file with this content.
  •  
    Line : aaa
    comment1
    comment2
    comment3
    
    Line : bbb
    comment4
    comment5
    

  • Select menu tools -> record macro in sublime.
  • Highlight the ":" char and press ALT-F3 to mark two lines.
  • Stop macro and save it.
The file should look similar to this one:
 
[
 {
  "args":
  {
   "by": "characters",
   "extend": true,
   "forward": true
  },
  "command": "move"
 },
 {
  "args": null,
  "command": "find_all_under"
 }
]

When you try to execute this macro it doesn't work and you can see the error message in the console window.

Analysis and solution

The command find_all_under is documented and works fine. You can always try to run it manually from the console yourself.
 
view.window().run_command("find_all_under")

To create the automatic solution and let the editor to do the work for me I decided to write a Plugin using Sublime Python API. The code works perfectly fine and can be found on my github account: https://github.com/rtomaszewski/sublime under the file device_list.py. All what you need to do is to install this plugin and execute it manually or use a keyboard shortcat to trigger it.

Workaround example:
 
view.run_command("device_list")

References

Sublime Python API
http://www.sublimetext.com/docs/2/api_reference.html
http://docs.sublimetext.info/en/latest/reference/plugins.html

Commands
http://docs.sublimetext.info/en/latest/reference/commands.html
http://www.sublimetext.com/docs/commands
http://docs.sublimetext.info/en/latest/extensibility/commands.html

Debugging
http://www.sublimetext.com/forum/viewtopic.php?f=6&t=10106
http://sublimetext.userecho.com/topic/114638-ctrlshiftt-does-not-work/
http://www.sublimetext.com/forum/viewtopic.php?f=6&t=4961

Tuesday, July 9, 2013

Migration from Sublime 2 to Sublime 3

With the advent of the version 3 of my favourite sublime editor I decided to give it a try and see what need to be change to migrate all my settings from the sublime2 to sublime3. Below is a list of changes I did.
At first glance it was easy to copy the basic settings. There are some compatibility issues with the modules although.
References
  1. http://www.sublimetext.com/blog/articles/sublime-text-3-beta

Tuesday, June 11, 2013

Sublime keyboard shortcat list

This is work in progress...
  • Below is a list of most common keyboard shortcats I use in Sublime (this is a work in progress post)
Ctrl-Shift-Space - select whole string in brackets
Ctrl-B - show/hide results panel
Ctrl-D - highlight a word
Alt-F3 - multi selection for all highlighted words
F4 - (in the search results Ctrl+Shift+F) opens a file and takes you to highlighted line
Ctrl-F2 - marks a point in a line and create a point for multi selection if needed
Alt-F2 - edit all the marked lines at once (create a multi selection from all the marks above)
Alt-F2, Ctrl-F2 - removes all the marks in the file
Ctrl+Alt+Enter - In the Find/Replace window at the bottom it 'Replace All' matches
More keyboard shortcats https://gist.github.com/eteanga/1736542

Sublime has a built in console terminal with ctrl+` . When type sublime.log_commands(True) there you enable verbose logging. When enabled you are going to see all commands that Sublime is executes as you use it. Just remember to turn logging off when you’re done :)

More function to play with can be found here: http://www.sublimetext.com/docs/2/api_reference.html

Sunday, June 2, 2013

Sublime multi-selection keyboard shortcats

We have discussed the benefit of Sublime editor in our previous posts. In this one we will show how to use efficiently the multi selection feature.

Keyboard shortcat for random multi selection

With Ctrl + D you can create multiple selections when editing text. But when combining it with Ctrl + K you can skip some matches.

Example:
Copy the following text into your editor:

`Example text. This is an example text. Text has only one line`

Test 1:
Ctrl-F to find all `text` string.
Press Ctrl+D twice times.
Escape to get back to editor from the search dialogue.

You created a three word multi selection. You can edit word in 3 different places at once.

Test 2:

Ctrl-F to find all `text` string.
Press Ctrl+D once. It creates 2 word multi-selection.
Press Ctrl+K once. It ignores the last selected work. It gets back to single word selection.
Press Ctrl+D second time. It creates 2 word multi-selection.
Escape to get back to editor from the search dialogue.

You created a 2 word multi selection. You can edit the 2 words simultaneously. We skipped the word in the middle.

Of course you can always use ctrl+u to return to a previous selection :).

Sublime Cheat sheet 

A short summary (more can be found here and on internet)

Ctrl + D    repeat multi-­select word
Ctrl + K    skip multi-­select word

Monday, April 8, 2013

How to show Build Results panel in Sublime editor

If you like using Sublime editor when coding in Python you love the shortcut ctrl+b. It executes the python interpreter with your script as parameter and prints any stdout or error messages in a new Result panel at the bottom of the window. With a Esc you can instruct the editor to hide this new panel.

Unfortunately there isn't a default shortcut to bring the Result Panel back.

Problem

How to create a shortcut to open Tools -> Build Results -> Show Build Results.

From menu open Preferences -> Bindings -> User and copy this similar config there.
 
{ "keys": ["alt+b"], "command": "show_panel", "args": {"panel": "output.exec"} }

Now with every time you press alt+b the result panel will appear again with the previous output.

References
  1. http://stackoverflow.com/questions/10674030/in-sublime-text-2-reopen-build-output

Saturday, March 30, 2013

How to run Sublime editor on remote cloud Linux server

Sublime is a graphical text editor that uses GTK libraries on Linux. If you would like to run it from your remote cloud servers session please follow the instruction below.
  1. Install the Sublime locally on your cloud server 
  2. Check what libraries you may be missing 

  3. The listing below shows that any libraries are missing.

     root@server:~/Sublime Text 2# ldd ./sublime_text
            linux-vdso.so.1 =>  (0x00007fff7d1ff000)
            libgobject-2.0.so.0 => /usr/lib/x86_64-linux-gnu/libgobject-2.0.so.0 (0x00007f85d64d9000)
            librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f85d62d1000)
            libglib-2.0.so.0 => /lib/x86_64-linux-gnu/libglib-2.0.so.0 (0x00007f85d5fda000)
            libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f85d5dbd000)
            libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f85d5bb9000)
            libutil.so.1 => /lib/x86_64-linux-gnu/libutil.so.1 (0x00007f85d59b5000)
            libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6 (0x00007f85d567d000)
            libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f85d5376000)
            libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f85d50f1000)
            libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f85d4edb000)
            libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f85d4b3c000)
            libgthread-2.0.so.0 => /usr/lib/x86_64-linux-gnu/libgthread-2.0.so.0 (0x00007f85d4936000)
            libffi.so.6 => /usr/lib/x86_64-linux-gnu/libffi.so.6 (0x00007f85d472e000)
            libpcre.so.3 => /lib/x86_64-linux-gnu/libpcre.so.3 (0x00007f85d44f2000)
            /lib64/ld-linux-x86-64.so.2 (0x00007f85d6731000)
            libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1 (0x00007f85d42d5000)
            libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6 (0x00007f85d40d2000)
            libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6 (0x00007f85d3ecb000)
    

  4. Try to execute it and it should complain about some libraries now that are loaded dynamically after start.  
  5.  
    root@server:~/Sublime Text 2# ./sublime_text
    Unable to load libgdk-x11-2.0.so
    Unable to load gdk_cairo_create from libgdk-x11-2.0.so
    Unable to load gdk_cursor_new_for_display from libgdk-x11-2.0.so
    Unable to load gdk_cursor_unref from libgdk-x11-2.0.so
    Unable to load gdk_error_trap_pop from libgdk-x11-2.0.so
    Unable to load gdk_error_trap_push from libgdk-x11-2.0.so
    ...
    Unable to load gtk_window_unfullscreen from libgtk-x11-2.0.so
    Unable to load pango_font_description_free from libpango-1.0.so
    Unable to load pango_font_description_new from libpango-1.0.so
    Unable to load pango_font_description_set_family from libpango-1.0.so
    Unable to load pango_font_description_set_size from libpango-1.0.so
    Unable to load pango_cairo_show_layout from libpangocairo-1.0.so
    Unable to load pango_cairo_update_layout from libpangocairo-1.0.so
    Unable to load all required GTK functions
    Unable to init px
    

  6. Let's find the missing library file and install the necessary package   
  7.  
    root@server:~/Sublime Text 2# aptitude install apt-file
    root@server:~/Sublime Text 2# apt-file update
    root@server:~/Sublime Text 2# apt-file search libgdk-x11-2.0.so
    ia32-libs: /usr/lib32/libgdk-x11-2.0.so
    ia32-libs: /usr/lib32/libgdk-x11-2.0.so.0
    ia32-libs: /usr/lib32/libgdk-x11-2.0.so.0.2400.6
    libgtk2.0-0: /usr/lib/x86_64-linux-gnu/libgdk-x11-2.0.so.0
    libgtk2.0-0: /usr/lib/x86_64-linux-gnu/libgdk-x11-2.0.so.0.2400.6
    libgtk2.0-0-dbg: /usr/lib/debug/usr/lib/x86_64-linux-gnu/libgdk-x11-2.0.so.0.2400.6
    libgtk2.0-dev: /usr/lib/x86_64-linux-gnu/libgdk-x11-2.0.so
    lsb-build-desktop3: /usr/lib/lsb3/libgdk-x11-2.0.so
    
    root@server:~/Sublime Text 2# aptitude install libgtk2.0-0
    
    root@server:~/Sublime Text 2# ./sublime_text
    (sublime_text:14069): Gtk-WARNING **: cannot open display:
    

  8. We need to enable X11 forwarding and set up a X11 server where the application output can be displayed

  9. If you connecting from Linux you need to use the -X option for ssh client.
    If you using Windows putty program you need to enable the X11 forwarding at Connection-SSH-X11-"Enable X11 forwarding". For the "X display location" option use the localhost:0.0

  10. Open new ssh session to the cloud server and test

  11. If client and server are configured properly you should be able to see DISPLAY variable being set
     
    root@urado2:~# set | grep DIS
    DISPLAY=localhost:10.0
    
    root@urado2:~# cat /etc/ssh/sshd_config | grep X11
    X11Forwarding yes
    X11DisplayOffset 10
    

  12. Test if we can start out sublime editor or if we get any new errors
  13.  
    root@urado2:~/Sublime Text 2# ./sublime_text
    (sublime_text:16851): Gtk-WARNING **: cannot open display: localhost:10.0
    

    To fix this we need to have an X11 windows server running on our local machine  If you are using Windows you can install for example Xming X Server for Windows

  14. Final test after the Xming server is up and running

  15. After lunch you should be able now to see the screen of your editor that was lunch on Linux cloud. 
    As this is a remote session there maybe some issues with lag and latency what will influence responsiveness and delays when editing.

Wednesday, March 27, 2013

Custom 3 pane layout in Sublime

I work with many files and often I need to copy and paste various lines when editing them. What help me a lot was a nice 3 pane layout where I could move files around. One way to create it is to use the Origami plugin that you can install in Sublime. But to make it simpler I decided to create a keyborad shortcut/menu entry for this.

The layout looks like this:


This is the config you need to put:
  • create a config file Main.sublime-menu in your sublime2\Data\Packages\User directory
  • copy the config into the file
[{
    "id": "view",
    "children": [{
        "id": "layout",
        "children": [{
             "command": "set_layout",
             "caption" : "Custom: 3 Pane",
             "mnemonic": "C", 
             "args": {
        "cells": [[0, 0, 1, 1], [0, 1, 2, 2], [1, 0, 2, 1]],
     "rows": [0.0, 0.5, 1.0], 
     "cols": [0.0, 0.5, 1.0]
   }
  }]
 }]
}]
  • Before you save the file open console (view->show console) and see if the file is parsed and loaded properly
# on the console
found 11 files for base name Main.sublime-menu
  • If you need now to divide your screen you need to select View->Layout->Custom:3 Pane from menu
  • You can create a custom keyboard shortcut as well. To replace the original [alt+ctrl+3] open the Preferences -> Bindings -> User and copy this similar config there. 
  • {
        "keys": ["alt+shift+3"],
        "command": "set_layout",
        "args": 
        {
            "cells": [[0, 0, 1, 1], [0, 1, 2, 2], [1, 0, 2, 1]],
            "rows": [0.0, 0.5, 1.0], 
            "cols": [0.0, 0.5, 1.0]
        }
    }
    
References
  1. http://www.macdrifter.com/2012/07/sublime-text-working-with-multiple-panes.html
  2. http://stackoverflow.com/questions/13149800/custom-layouts-sublime-text-2
  3. http://stackoverflow.com/questions/10674030/in-sublime-text-2-reopen-build-output

Tuesday, March 26, 2013

Installation of Sublime Text editor on Ubuntu 12.10

Update 1:
added how to update alternatives in debian/ubuntu

An absolutely brilliant  installation manual how to install Sublime on Ubuntu:
How to install Sublime Text 2 on Ubuntu

If you want now type 'editor' in bash and start sublime as your default editor you have to update the alternative system that Debian introduces.
 
 update-alternatives --install /usr/bin/editor editor /opt/Sublime\ Text\ 2/sublime_text 55
 update-alternatives --display editor



Saturday, March 2, 2013

Text developer editor with Python API

I often need to work between Linux and Windows systems. Under every OS I have my favorite tools I like that help me to get the job done. But there has always been one tool that I wasn't very happy with: a good text editor.

Problem

What is a good cross platform editor with development features that is written and integrated with Python.

Analisis and discussion 

When I code I always like to know the editor so I can quickly and comfortably navigate in a single or multiple files at the same time. I've found recently one that I tend to use more: Sublime. The other one I was using for a long while was Notepad++ but it was only limited to Windows.

Why Sublime works for me:
My simple config

You can view and change all global settings under Menu - Preferences - Settings - Default but a better way is to create a local customized user preferences file.

To modify user settings open the following file under Menu - Preferences - Settings - User and copy or modify these options:
 
"fade_fold_buttons"        : false,
"highlight_line"           : true,
"auto_complete_size_limit" : 44194304,
"tree_animation_enabled"   : true,

My packages

Below are some of my packages I'm using

How to highlight a whole line in Sublime like in Notepad++ 

In notepad++ when editing your can enable whole like to be highlighted (here are some example screenshots). To achieve the same effect in Sublime you need to enable the highlight_line: true.

References and documentation

http://www.sublimetext.com/2
http://docs.sublimetext.info/en/latest/index.html