A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Jump to

Quick reference

Showing posts with label text editor. Show all posts
Showing posts with label text editor. Show all posts

Whitespace woes

One very annoying aspect of software development in a team is whitespace. Many people use it differently. In a way it's unimportant, not least because it's literally invisible and so often overlooked. Yet it continues to cause problems which repeatedly waste time, and is especially distracting and troublesome for the many detail-oriented developers among us.

Clearly the only sane way to use whitespace in Perl is:

  • 4 character indent
  • only use spaces, never use tabs
  • never allow any trailing whitespace

One of the worst violations of these rules is an indent composed of mixed tabs and spaces. This is a list of reasons why that's very wrong:

  • When someone gets fed up and changes that whitespace to make it conform, it introduces noise into the code diff (they don't create a separate branch due to the overhead costs in a bureaucratic, audited environment).
  • Different text editors and web interfaces all display the indent differently, making the code hard to follow.

Terminal does not wrap properly in linux

Sometimes lines don't wrap correctly in a bash terminal in linux - long lines overlap and overwrite the beginning of the line instead of continuing onto the next line.

To fix it:
shopt -s checkwinsize

To check it:
shopt  | grep checkwinsize
You should see:
checkwinsize    on

If it still isn't working, try:
reset

(source)

Good enough software

There's so much software available these days, it's difficult to find which is the best without laboriously downloading, installing, configuring and testing, which I don't often have time for. Unfortunately a large proportion of software is simply not good enough, or its features are poorly described.

Here is some "good enough" software I've found for Windows:
  • To diff directories, e.g. sync music or photos: FreeFileSync 6.3
  • To diff the content of files, e.g. source code: WinMerge
  • Windows Explorer alternative: xplorer 2
  • To encode mp3s: LAME
  • To see where your disk space is being used: Treesize
  • To remove spyware: Spybot: Search & Destroy
  • Torrents: qBittorrent
  • N64 emulator: project64
  • Programmer's text editor: Notepad++
  • ebook management: Calibre
  • Manage iPhone music outside iTunes: Media Monkey
  • Graphics maniplation: GIMP
  • Rename files: Bulk Rename Utility
  • Macro recorder: Autohotkey
  • Media player: VLC, or MPC-HC (not tried)
  • Music player: Winamp
  • Documents and spreadsheets: Microsoft Office
    • (LibreOffice and OpenOffice are NOT good enough)

Emacs for a vi user

In the past I've exclusively used vi, but now I want to use Emacs as I've heard it has some useful modes, for example 'font-lock-keywords' mode which is one way to easily highlight certain keywords in a program's console output. I don't want to mess around compiling specialised text highlighting programs, and they're not in my standard repos. Emacs is much more likely to already be available wherever I need it.

Emacs commands:
  • To exit: C-x C-c
  • Turn on syntax highlighting: M-x font-lock-mode

Key:
C = Ctrl
M = Meta (Alt)

Thanks to the rest of the web

UPDATE: It turns out font-lock-keywords can easily be implemented in a 3 line bash script. Call it "highlight":

    # Usage: tail -f error.log | highlight "error"
    RED="$(tput setaf 1)"
    RESET="$(tput setaf 7)"
    sed "s/$1/$RED$1$RESET/"

But I would still like to see the Perl debugger integrated into Emacs

vim tabs and buffers basics


in vim type  ":grep -Ri search_string *"
...it executes... press enter to get back to vim
then type ":copen" to open a window with the search results in
and you can browse the matches really easily

:help grep

then if you press enter to open one of the files found,
to get back to your original file type :buffers or :ls

:tabe #[number against file] will open the original file in a new tab
:sp #[number against file] will open the original file in a new window

:buffer [number against original file] will open the original file again
and you could make the F keys load the buffers

I prefer tabs over buffers because they're more visible
in bash vim -p file1 file2 will open 2 files in two different tabs
gt and gT will cycle through the files (I have that mapped to alt+left and alt+right)
:tabe will open a file in a new tab


Thanks Phill

Sublime text editor tricks

Sublime is not a bad text editor for Linux:

Mount a remote directory:  sshfs username@hostname:/remote/path /local/path

Put a vertical line after 80 characters: Preferences > Settings - User > ... add an entry: "rulers": [80]

Change syntax highlighting colours: Preferences > Browse Packages > Color Scheme - Default > ... edit the Color Scheme file you are using.

{
"color_scheme": "Packages/Color Scheme - Default/All Hallow's Eve.tmTheme",
"font_size": 10,
    "rulers": [80],
    "auto_complete": false
}


Shortcuts:

  • Shift-F11 = Enter "concentration" mode AKA "distraction free" mode

Things lacking in Eclipse for Perl

Using EPIC
  • You can't fold code on 'if' blocks, or any arbitrary block (only on subs and perldocs).
  • Word wrap causes the line numbers to be wrong (a single wrapped line has more than one line number)
  • Syntax highlighting is not a perfect fit (perhaps this or these might help):
    • POD and heredoc are both marked as 'Comment2' and so can't be different colours
    • Even though there is a 'Markup' entry, it doesn't seem to be used for POD
    • The colour of dollar signs can't be changed (it's the same as the variable name in vim)
    • Neither variables nor special characters change colour within interpolated strings (as in vim)

Vim features


  • Auto-complete (for Perl files): start typing, then press Ctrl-Shift-P

Vim navigation

1. Vim Line Navigation
Following are the four navigation that can be done line by line.
  • k – navigate upwards
  • j – navigate downwards
  • l – navigate right side
  • h – navigate left side
By using the repeat factor in VIM we can do this operation for N times. For example, when you want to
go down by 10 lines, then type “10j”.

Within a line if you want to navigate to different position, you have 4 other options.
  • 0 – go to the starting of the current line.
  • ^ – go to the first non blank character of the line.
  • $ – go to the end of the current line.
  • g_ – go to the last non blank character of the line.

2. Vim Screen Navigation

Following are the three navigation which can be done in relation to text shown in the screen.
  • H – Go to the first line of current screen.
  • M – Go to the middle line of current screen.
  • L – Go to the last line of current screen.
  • ctrl+f – Jump forward one full screen.
  • ctrl+b – Jump backwards one full screen
  • ctrl+d – Jump forward (down) a half screen
  • ctrl+u – Jump back (up) one half screen

3. Vim Special Navigation

You may want to do some special navigation inside a file, which are:
  • N% – Go to the Nth percentage line of the file.
  • NG – Go to the Nth line of the file.
  • G – Go to the end of the file.
  • `” – Go to the position where you were in NORMAL MODE while last closing the file.
  • `^ – Go to the position where you were in INSERT MODE while last closing the file.
  • gg – Go to the beginning of the file.

4. Vim Word Navigation

You may want to do several navigation in relation to the words, such as:
  • e – go to the end of the current word.
  • E – go to the end of the current WORD.
  • b – go to the previous (before) word.
  • B – go to the previous (before) WORD.
  • w – go to the next word.
  • W – go to the next WORD.

5. Vim Paragraph Navigation

  • { – Go to the beginning of the current paragraph. By pressing { again and again move to the previous paragraph beginnings.
  • } – Go to the end of the current paragraph. By pressing } again and again move to the next paragraph end, and again.

6. Vim Search Navigation

  • /i – Search for a pattern which will you take you to the next occurrence of it.
  • ?i – Search for a pattern which will you take you to the previous occurrence of it.
  • * - Go to the next occurrence of the current word under the cursor.
  • # - Go to the previous occurrence of the current word under the cursor.

7. Vim Code Navigation

% – Go to the matching braces, or parenthesis inside code.

8. Vim Navigation from Command Line

Vim +N filename: Go to the Nth line of the file after opening it.
vim +10 /etc/passwd

An easy way to browse the file system is the command:
:Sex
Really!

Perl sub name in vi status line

" Thanks Ovid!
" http://blogs.perl.org/users/ovid/2011/01/show-perl-subname-in-vim-statusline.html


:set laststatus=2


if ! exists("g:did_perl_statusline")
    setlocal statusline+=%(\ %{StatusLineIndexLine()}%)
    setlocal statusline+=%=
    setlocal statusline+=%f\ 
    setlocal statusline+=%P
    let g:did_perl_statusline = 1
endif


if has( 'perl' )
perl << EOP
    use strict;
    sub current_sub {

        my $curwin = $main::curwin;
        my $curbuf = $main::curbuf;


        my @document = map { $curbuf->Get($_) } 0 .. $curbuf->Count;
        my ( $line_number, $column  ) = $curwin->Cursor;


        my $sub_name;
        # for modules, display the current sub name
        for my $i ( reverse ( 1 .. $line_number  -1 ) ) {
            my $line = $document[$i];
            if ( $line =~ /^\s*sub\s+(\w+)\b/ ) {
                $sub_name = $1;
                last;
            }
        }
        # for templates, display the current block starting line
        if (not $sub_name) {
            for my $i ( reverse ( 1 .. $line_number  -1 ) ) {
                my $line = $document[$i];
                # if ($input_state eq 'next_disc_at_station') {
                if ( $line =~ /^}/ ) {
                    # we're below a block
                    last;
                }
                elsif ( $line =~ /^(\S.+{)\s*$/ ) {
                    $sub_name = $1;
                    $sub_name =~ s/'/''/g; #' # escape single quotes for vim function
                    last;
                }
            }
        }
        # TODO:
        # * Reset sub name if we're out of the sub (check for closing bracket: })
        # * Search upwards vertically in the same column for nested blocks
        $sub_name ||= '..';
        VIM::DoCommand "let subName='$line_number: $sub_name'";
    }
EOP


function! StatusLineIndexLine()
  perl current_sub()
  return subName
endfunction
endif

navigation in vim

vi keybindings

Summary:
  • h - move left
  • l - move right
  • j - move down
  • k - move up
  • g, then j or k - move only one screen line (for long lines)
  • w - go forward one word
  • e - go to end of word
  • b - go to beginning of word
  • { - jump up to next blank line
  • } - jump down to next blank line
  • m? - set mark ? (where ? is a lowercase letter a-z)
  • '? - jump to mark ? (where ? is a-z) NOTE: This is a single quote mark followed by a lowercase letter

    Insert non-printable characters in vi

    • Ctrl-V, then Ctrl-[X]
    Where [X] is A-F

    Perl tools

    Perl Needs Better Tools

    IDEs

    • Padre is free, supposedly it knows more about Perl internals than other IDEs.
      • Syntax highlighting: View|Style|Evening
      • Current line highlight colour: Tools|Preferences|Appearance|Editor Current Line Background Colour
    • Eclipse is free but, seems very heavyweight. Extensible with plugins (Version control, etc. See EPIC for Perl)
    • Komodo is paid, but is explicitly designed for Perl. It has a remote debugging feature, which works! You have to install a script on the remote server, and have access to the remote fileystem to display the source code.
    • NetBeans is free
    • IntelliJ IDEA is paid, and has no Perl plugin
    Text editors
    • vim - I use this a lot. It has keyword lookup (if you can configure it), a powerful but difficult-to-use scripting language, and tabs, but no debugging support. Lots of scripts/add-ons available.
    • Emacs - some of my colleagues use it, can be very powerful with add-ons/perl modules
    • UltraEdit
    • Textpad - Windows only. Nice to use, has plugins
    • Sublime - A nice text editor
    Further reading

    • Why should I use an IDE?
    • TODO: [an article on coding horror or somewhere "what would a good IDE look like?"] where is it?

    Eclipse notes

    • File associations are under Preferences | General | Editors | File Associations
    • Background colour is under: Preferences | General | Editors | Text editors 
      • and Preferences | oXygen | Editor
    • Syntax highlighting is under: Preferences | XML | XML Files | Editor | Syntax Coloring
      • and Preferences | oXygen | Editor | Syntax highlighting
    • Eclipse plugins site: http://eclipse-plugins.info/eclipse/
    • How to import/export syntax highlighting colours
    • No word wrap!

      Text file endings

      Mac OS: \r
      Unix: \n
      Windows: \r\n

      Roll an 'if' statement into a single line in vim

      Ctrl-V
      s/\n\t\+/ /g

      or

      type JJJ

      Record and playback macros in vi

      qN - start recording, where N is a-z
      @N - play back your recording, where N is a-z
      @@ play back the same recording again

      vim features

      7.0.237 has highlighting of the text for which you're searching.

      Edit text files on remote linux servers

      UNTESTED:

      > I've never managed to figure out how to rig up editors to edit
      > files on remote servers.

      On the server, put this in smb.conf

      [homes]
      comment = Home Directories
      hide dot files = yes
      read only = No
      browseable = yes


      Then in the finder/windows explorer connect to 'smb://hostname/' . Then make an alias to it on your desktop.

      Alternatively, TextWrangler on the Mac has an ftp/sftp browser.

      http://www.barebones.com/products/TextWrangler/

      Code folding in vi

      All you ever wanted to know about code folding in vim, including keys: http://www.linux.com/archive/articles/114138

      Config settings for code folding: http://smartic.us/2009/04/06/code-folding-in-vim/

      Vim documentation for folding: http://www.vim.org/htmldoc/fold.html
      There are six methods to select folds:

      manual manually define folds
      indent more indent means a higher fold level
      expr specify an expression to define folds
      syntax folds defined by syntax highlighting
      diff folds for unchanged text
      marker folds defined by markers in the text

      Key concepts:
      • To use the indent method you need to set the :tabstop correctly
      • Syntax method requires the correct syntax files to be present
      Commands:
      • zc -> close fold
      • zo -> open fold