28
VIM FOR DEVELOPERS © Professor Leon King, Jan 13, 2021

Vim For Developers - Humber College

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Vim For Developers - Humber College

VIM FOR DEVELOPERS

© Professor Leon King, Jan 13, 2021

Page 2: Vim For Developers - Humber College

PUTTY TIPS

Choose a different font size & style

Port 22 means putty uses ssh. Leave this alone

Choose “System Colors”For black text, white background.

Turn off that annoying bell

Specify your login id & system

Define the settings you want, give it a name and Save for later

Select “Use Unicode line drawing code points so you can put emojis in your code

Download & install putty from: https://www.chiark.greenend.org.uk/~sgtatham/putty/

Page 3: Vim For Developers - Humber College

To access my predefined macros

ln -s ~king/.vimrc ~/.vimrc

• One time only on apollo or munro

• Or: scp [email protected]:/home/staff/king/.vimrc ~

Page 4: Vim For Developers - Humber College

Predefined Text Macros (Feature 1: Code Generation)

• HC => Humber College

• IBM => International Business Machines

• PROG => generates main for C

• PR => generates fprintf(stdout,”Hello World\n”);

• fori => generates a for loop

• SW => generates a switch statement

• HTML => generates outline for basic web page (caution needed)

• WEBR =>generates 4 columns in an HTML table

• psvm => outline of a class definition – same as in NetBeans

• FHEAD => Commented C heading listing student & course info

• BHEAD => Commented bash shell heading listing student & course info

Page 5: Vim For Developers - Humber College

Predefined function keys (F2:Compile & Run in vim)

• F1 - reserved for :help

• F2 - Save (:w)

• F3 - gcc -g3 –std=gnu99 –wformat % -o %:r (compile file)

• F4 - run the current compiled file

• F5 - javac % (compile current java file)

• F6 - java %:r (run current compiled java file :r removes the ext)

• F7 - :!bash (open a bash subshell)

Page 6: Vim For Developers - Humber College

Useful settings in ~king/.vimrc

• set encoding-utf8 (new! interpret Unicode characters)

• set mouse=a (enable mouse to change cursor, resize windows)

• set number (show line #s)

• set autowriteall (save file when changing buffers)

• set backup (Create a backup file)

• set backupext .bak

• set syntax on (syntax hiliting based on file type)

• set undofile (new! Persistent undo between edit sessions

save file is: .filename.un~)

Page 7: Vim For Developers - Humber College

F3: Syntax hiliting

vim detects the file type from the extension. There are dozens syntax coloring rule files that come with vim.

Useful to distinguish variables from keywords, identifying what’s commented out and detecting where a string begins and ends

Page 8: Vim For Developers - Humber College

F4: TODO Markups

The following keywords will show hilited in yellow when displayed within a comment. This is a common feature of development IDEs which is used to hilite tasks, achievements and problems

// TODO DONE XXX BUG HACK FIXME Note Feature

This is set up with vim’s syntax keyword command in .vimrc

Page 9: Vim For Developers - Humber College

F5: Bracket Balancing

The % command jumps between matching parentheses making it easier to check and confirm balance. Incredibly useful as a missing bracket is a major headache. Both opening and closing bracket will be hilited.

It covers the following: ( < [ { } ] > )

The % operator ignores matching characters in “ but not in ‘

% also works with /* comments */and C macro definitions #if, #ifdef, #ifndef, #elif #else and #endif:

Page 10: Vim For Developers - Humber College

F6: Help within vim

• Type capital K over any C/C++ function name or a keyword topic such as TCP or systemd to display the man page. If the topic appears in multiple man pages, type in the section #, ie: 5K

• (1) Unix commands• (2) C System calls• (3) C Library calls (not requiring system privileges)• (4) Devices and special files (ie: man null; man 4 tty; man random);• (5) File formats (ie: man passwd, man proc, man elf)• (6) Games (unfortunately many organizations do not install these)• (7) Miscellaneous (man ascii; man 7 time, man 7 signal; man Unicode)• (8) System administration tools (requires adm privilege to use)• (9) Kernel developer functions (requires root privilege to use)

Manual topic sections can be found under the directory /usr/share/man

Page 11: Vim For Developers - Humber College

F7: Multiple Buffers

One can open up multiple files at the same time and switch between them

vim file1.c file2.c file3.c ….

Commands:

:ls (shows open buffers. %a is the active buffer, # - prev buffer used ):bn (switch to buffer #n, :b# is the prev buffer)

:b partialMath (supply part of an open file name. tab thru list if more than 1)

:n file(s) (add new files):n (go to next file in the list)

:prev (go to previous file in the list)

:find filePattern (find a file contained in vim’s path variable. tab thru list if more than 1)

Page 12: Vim For Developers - Humber College

F8: Split windows or Multiple Tabs

vim -o file1.c file2.c ….. (display files in n panes split horizontally)vim -O file1.c file2.c …. (display files in n panes split vertically)vim -p file1.c file2.c … (display files with tabs. Maximum 10) :split (current file displayed again in new pane):vsplit (current file displayed again in new pane):split fileA.html (horiz split current pane and add another file):vsplit fileB.py (vertical split of current pane and add a file):tab ball (Convert all buffers into tabs)

If the same file is open in 2 (or more) buffers an edit in 1 causes all to change as they are really the same buffer. Useful to refer to one part of a file while working on another or to cut and paste within the same file!

Page 13: Vim For Developers - Humber College

F9: Autocompletion

Start typing any variable name or function and press <ctrl>p or <ctrl>n

If there is only 1 option vim will fill it in. If there are several it will list them in a scrolling popup window where you can select the item. The names come from the current file or included files.

<ctrl>x<ctrl>n will limit the search to items in the current file.<ctrl>x<ctrl>k will search any installed dictionaries to complete the word<ctrl>x<ctrl>f will search file for file names the current or specified dir

To find out more: :help ins-complete

Page 14: Vim For Developers - Humber College

F10: Jump to definition

Type gD over variable or function names and the cursor jumps to global declaration but only in the same file.

Type gd and the cursor jumps to a local definition inside a function.

Typing gF over the name of a file opens the file in the same bufferType <ctrl>WgF opens it in a new window

Page 15: Vim For Developers - Humber College

F11:grep search with jump list

:lgrep pattern % filelist…:lopen

Searches multiple files and presents of lines where the pattern can be found. My .vimrc sets up egrep as the default search engine. Reissuing :lgrepreplaces the searched items with a new list.

:lclose (closes the search list lookup window)

Page 16: Vim For Developers - Humber College

F12: QuickFix – Integration of Error Messages

When compiling redirect the error output to a file followed by :fopen file

gcc -g3 –std=gnu99 –wformat % -o %:r 2>errors.dat:cfile errors.dat

A jump list will appear in a separate window. Use it to make as many corrections as feasible and repeat. Subsequent uses of :cfile do not need to mention the file. (This saves an incredibly significant amount of time.)

The following commands work, but may be unnecessary with a mouse::ncn[ext] (jump n error messages ahead. Default is 1):ncp[rev] (jump n error messages back)

:cclose (close the quickfix window

Page 17: Vim For Developers - Humber College

F13: Auto Indenting and Formating

:set cindent auto indentation for C programs. Defined in .vimrc

gg=G global reformat of entire buffernot recommended as it distorts comments

V=select text with mouse= range reformatting of selected code

n== reformat the next n lines=i{ reformats the current code block and sub blocks=2i{ reformat the current block & the surrounding block

n>> indent the next n lines 1 shiftwidth leftn<< indent the next n lines 1 shiftwidth right

Page 18: Vim For Developers - Humber College

F14: Opening terminal panes inside vim

:term [command] (horizontal split)

:vert term [command] (vertical split)

Without a command opens up a bash shell With a command the command runs in the new pane

:term gdb:vert term top

:term %:r (run the current compiled file):vert ls

Page 19: Vim For Developers - Humber College

F15: Examining binary data in files

On occasion a developer will need to examine the hex value of unprintable characters. A classic case is detecting NULL values, MAGIC values at the start of files or MD-DOS carriage returns.

To examine an individual character use the command ga over the suspected item. The decimal and hex values will appear in the status line. However I’ve modified the status line in .vimrc to do the same

If you need to look at several characters through the file, the od (octal dump) utility on the command line should preferred over vim which only gives you a window of one character at a time.

Page 20: Vim For Developers - Humber College

F16: Supporting Unicode

Vim is normally an ascii editor. Displaying Unicode is a matter of using the correct settings and what your version of the operating system supports.

In putty settings: Translation | Use Unicode line drawing code points

The following setting is enabled in ~/.vimrc: set encoding=utf-8

//JavaScript example

const monkeys= " 🐒🙈🙉🙊 "; //monkeys.length is 8const checkmark= " check: \u{2714} “;alert(monkeys+checkmark);

//C example int main(int argc, char * argv[],char * envp[])

{ setlocale(LC_ALL,"en_CA.UTF8");fwprintf(stdout,L"Hello🌎\n");return 0;

}

Page 21: Vim For Developers - Humber College

F17: Showing vim version information

While not strictly a programmers tool, this does allow you to review installed (and not installed) features of vim.

:version

Page 22: Vim For Developers - Humber College

F18: Show current modifications to a file

:changesng, moves n changes backwards through the changes listng; moves n changes forwards

:jumps n<ctrl>o moves back n older jumps (only the last 100 are saved)n<ctrl>I moves n items forward in the jump list

My .vimrc is set up with the option persistant so that a record of changes is maintained across separate edits however there is no connection to undo. This may be of help in diagnosing changes that lead to errors.

Page 23: Vim For Developers - Humber College

F19: Code FoldsA code fold hides large segments of code along natural lines while leaving the 1st line displayed as a hint with a ‘+’ symbol at the start indicating a fold. Folds allow one to ignore code that you are not currently working on.

Issue the command :set foldmethod=syntax The other five methods are: manual (default), indent (use w python), expr, marker, diff. Only syntax is covered here

zc close/create a fold

zC recursively close all nested folds

<space> or zo open current fold

zO recursively open all nested folds

Folds can be created over { } and also /* comments */For HTML code a fold only applies to a single tag expressed over multiple linesTo work with embedded css or javascript one has to change the filetype: set ft=c(I’m looking for an workaround using the marker fold method)

Page 24: Vim For Developers - Humber College

F20:Automatically continuing comments

This is programming language sensitive.

// in C, Java, C++/* subsequent lines will contain a *

“ This is the comment symbol in vim resource files

Currently / and -- is not supported in SQL files and ; is not supported in assembler though keyword hiliting is.

Page 25: Vim For Developers - Humber College

F21: Saving the current vim state

:mksession sessionFileName (with no filename listed, session.vim is created)

This generates a script file that can recreate your settings

:source sessionFileName (restores previous cursor and window states)

Page 26: Vim For Developers - Humber College

F22: Running bash commands on file text

!!date cmd line args (runs a command and inserts output into file)!!who

:1,10!tac runs a command and applies it to a range oflines – replacing them

:n,m!html tag enclose a range of lines in an html tag(source code html.c available on request)

Page 27: Vim For Developers - Humber College

F23: vim comes with netrw: a file tree browser

:vsplit dir:split file.zip (or .ar, .jar, .gz - any archive format file

type o over a file name and it opens in a new horizonal windowtype v and it appears in a new vertical windowdouble click and it appears in the last window opened (?)

Page 28: Vim For Developers - Humber College

NEXT PROPOSED TALK: GDB AS A TEACHING IDE

When: TBA