From 1752754dd3d9dca22c225630144c1ea3ca7c07ed Mon Sep 17 00:00:00 2001 From: marcin Date: Sat, 1 Jan 2011 11:29:19 +0100 Subject: initial commit, english version is still in progress --- JL_vim.tex | 711 +++++++++++++++++++++++++++++++++++++++++++++++++ Use Vim Like A Pro.tex | 668 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1379 insertions(+) create mode 100644 JL_vim.tex create mode 100644 Use Vim Like A Pro.tex diff --git a/JL_vim.tex b/JL_vim.tex new file mode 100644 index 0000000..403a0c9 --- /dev/null +++ b/JL_vim.tex @@ -0,0 +1,711 @@ +\documentclass[a4paper,12pt]{article} + +\usepackage{amsfonts} +\usepackage{amssymb} +\usepackage[polish]{babel} +\usepackage[T1]{polski} +\usepackage{polski} +\usepackage[utf8]{inputenc} +\selectlanguage{polish} +\usepackage{times} +\usepackage{graphicx} +\usepackage{eso-pic} +\usepackage{hyperref} + +\hypersetup{ + colorlinks=true, + linkcolor=black, + pdfauthor={Marcin Karpezo}, + pdftitle={Use Vim Like A Pro}, + urlcolor=blue +} +\title{Używaj VIM-a jak profesjonalista} +\author{Tim Ottinger} +\date{15 grudnia 2010} +\newcommand{\linia}{\rule{\linewidth}{0.4mm}} +\begin{document} +\pagestyle{empty} +\noindent +\linia \\ \\ +{\Huge Używaj VIM-a jak profesjonalista}\\ +\linia +\begin{flushright} +Tim Ottinger +\end{flushright} +\newpage +\noindent +Tytuł oryginału: \href{http://tottinge.blogsome.com/use-vim-like-a-pro}{Use Vim Like A Pro}\\ +Tłumaczenie: Michał Bielawski \\ +Korekta/skład: Adrian Bogdanowicz, Katarzyna Świderska, Marcin Karpezo\\ +\href{http://jakilinux.org}{JakiLinux}\\ \\ +Wersja: 1.0\newpage +\pagestyle{plain} +\setcounter{page}{3} +\tableofcontents \newpage +\section{Wstęp} + +Jest wiele edytorów tekstu. Niektóre z nich są bez wątpienia świetne i nic nie stoi na przeszkodzie, żebyś ich używał. Jednakże są pewne powody, dla których warto używać właśnie VIM-a. Nawet pomimo tego, że powody te nie są unikalnymi cechami tegoż edytora. +\begin{itemize} + \item Dzięki wzrostowi zainteresowania platformami Uniksowymi (głównie Linux i Mac OS X), VIM jest powszechnie używanym edytorem + \item VIM potrzebuje niewielkich ilości pamięci RAM i mocy procesora. Nawet średniej klasy komputer jest w stanie udźwignąć wiele instancji edytora jednocześnie + \item VIM ma wiele “supermocy”, które sprawiają, że edycja plików przebiega dużo sprawniej + \item VIM wytwarza wokół siebie aurę “geekowatości” + \item VIM ma bardzo aktywną społeczność użytkowników i deweloperów. Zawsze ją miał. +\end{itemize} + +\subsection{Po co w ogóle pisać ten poradnik? (czyli podejście)} + +Są inne bardzo dobre tutoriale i Google na pewno pomoże Ci w znalezieniu ich. Zapewne kolejny tutorial do VIM-a nie jest artykułem pierwszej potrzeby, ale ten jest wyjątkowy – bo mój.\\ +Przyjąłem nieco odmienne podejście niż inni autorzy. Uważam, że istnieje pewien sposób myślenia, który sprawia, że nauka VIM-a staje się dużo prostsza. Omawiam również nawyki, dzięki którym zaprzyjaźnisz się z tym edytorem. Szczerze mówiąc nie wiem, czy ktoś przedstawił to w ten sposób.\\ +Długo układałem (i układałem i układałem\ldots) ten tutorial tak, żeby materiał był w odpowiedniej kolejności. Cały czas stawiając sobie za cel napisanie tego poradnika tak, żeby czytelnik, po dobrnięciu do końca, umiał korzystać z VIM-a w jak najbardziej profesjonalny sposób. Prawdopodobnie lepiej niż niejeden ich bardziej doświadczony kolega.\\ +Doradzam cierpliwość i poleganie na pamięci długoterminowej, ale jednocześnie uważam, że ten poradnik to jeden z najszybszych sposobów na usprawnienie Twojej pracy z VIM-em, jak również całkiem niezły na naukę od zera. Pisałem ten poradnik dla raczej niecierpliwego programisty.\\ +Zdecydowałem, że nie chcę pisać i sprzedawać książki, ponieważ każdy powinien mieć możliwość używania VIM-a jak zawodowiec, w każdym miejscu i czasie, bez konieczności wnoszenia dodatkowych opłat. + +\subsection{Jak korzystać z tutoriala? (czyli instrukcja obsługi)} +Traktuj każdy punkt poradnika jako osobną lekcję i poświęć chwilę czasu na wypróbowanie danych komend, zanim przejdziesz do następnej. Możesz poświęcić cały dzień na każdą lekcję, a może nawet kilka, jeżeli dany materiał okaże się wyjątkowo trudny do przyswojenia.\\ +Postaraj się przerabiać po kilka lekcji tygodniowo. Nie spiesz się. Nie przeciążaj swojego mózgu ucząc się ciągle nowych rzeczy, bo zapomnisz o tym, czego uczyłeś się prędzej. Tutorial ten będzie istniał tak długo, jak będziesz tego potrzebował. Możesz złapać oddech.\\ +Nie nauczysz się VIM-a nie używając go, więc powinieneś przygotować sobie jakieś pliki (najlepiej kod jakiegoś wolnodostępnego programu), na których będziesz pracował. Jeszcze lepiej, jeżeli używasz VIM-a w pracy. Pomocne może być również przerabianie tego “kursu” we dwie osoby, żebyście z partnerem mogli się nawzajem wspierać. +\subsection{Co mogę z tym zrobić? (czyli licencja)} +Praca ta jest udostępniona na zasadach \href{http://creativecommons.org/licenses/by/3.0/pl/}{licencji Creative Commons Attribution 3.0}. Kopiuj, dziel się, udostępnij na swojej stronie. Nie udawaj, że to Twój tekst i dodaj informację o autorze. W ramach uprzejmości – jeśli uznasz, że jest to warte zachodu – nie będę miał nic przeciwko poinformowaniu mnie o tym. +\section{Tutorial (czyli część zasadnicza)} + +Nikt nie zna całego VIM-a. Jest tyle różnych poleceń, że wystarczy dla tysięcy istnień ludzkich, z których każde może używać VIM-a na swój własny sposób. Na szczęście nie musisz znać ich wszystkich. Wystarczy Ci tyle, ile potrzebujesz, żeby wykonać swoje zadanie.\\ +Z tego również powodu, przez cały czas używania VIM-a będziesz poznawał nowe sztuczki. Sekret polega na tym, żeby nie poprzestawać na jednym konkretnym (kiepskim) sposobie wykonania danej czynności.\\ +VIM ma uzupełnianie składni, historię operacji, skróty klawiszowe, personalizację ustawień klawiatury, makra i skrypty. Możesz go przemienić w {\bf swój} edytor, przystosowany do {\bf twojego} środowiska. Brzmi świetnie, ale pewnie ucieszysz się z faktu, że możesz być dużo wydajniejszy nawet bez dotykania tych zaawansowanych funkcji.\\ +Jak mówi {\it Bram Moolenaar} (główny autor VIM-a), najlepszym sposobem na naukę VIM-a jest używanie go i zadawanie pytań. Ten poradnik pełen jest pytań, o których mogłeś nawet nie pomyśleć, żeby je zadać. To najbardziej wartościowa rzecz, którą mogę Ci przekazać.\\ +VIM ma wbudowany tutorial. Możesz go wypróbować, zwłaszcza jeśli nie spodoba Ci się mój. Żeby z niego skorzystać, wystarczy wywołać polecenie vimtutor z poziomu wiersza poleceń Twojego systemu. Jest on bardzo przystępny i raczej kompletny (w przeciwieństwie do mojego, który jest raczej przyjemny, ale na pewno nie kompletny).\\ +Proponuję również rozważyć GVIM-a. Sprawi on, że będzie Ci się pracować dużo przyjemniej. Jeżeli masz pod ręką tylko VIM-a, to oczywiście nadal możesz korzystać z tego poradnika, ale GVIM wygląda dużo lepiej, pozwala na używanie myszy i ma menu oraz ikony dla tych z Was, którzy przywykli do takich rzeczy. +\subsection{Tryby pracy} +Oryginalny VI powstał w czasach, gdy czarno-zielone ekrany były szczytem osiągnięć techniki (zapytaj dziadka o terminale ASCII). Nie było wtedy tak wielu klawiszy modyfikujących (shift, alt, ctrl, super, fn), jak również urządzeń wskazujących. Przyjmijmy, że mieliśmy do dyspozycji tylko klawisze shift i ctrl (nawet jeśli to nieprawda).\\ +Programując (tak jak i robiąc cokolwiek innego na komputerze) mieliśmy oczy cały czas skierowane na ekran, a dłonie położone na klawiaturze. VI sprawił, że pisanie programów odbywało się {\bf szybko}, ponieważ VI jest trochę jak gra komputerowa, w której każde naciśnięcia klawisza sprawia, że coś się dzieje.\\ +Jeżeli używasz vima i wciskanie klawiszy sprawia, że dzieją się albo rzeczy cudowne, albo straszne, to wiesz, że jesteś w trybie komend, który jest domyślnym trybem edytora. Komendy są przypisane do zwykłych klawiszy takich jak {\tt o}, {\tt y} czy {\tt g}, zamiast kombinacji w stylu {\tt Ctrl+Alt+Shift+Esc}.\\ +VIM jest wyposażony w kombinacje klawiszy pozwalające wykorzystać specjalne moce, takie jak nawigacja między funkcjami w oddzielnych plikach, poprawianie formatowania całych list w samym środku dokumentu, uzupełnianie składni, skróty, szablony i inne takie, ale o tym później.\\ +Musi istnieć również sposób na wprowadzanie tekstu, ale większość klawiszy ma już przypisane magiczne funkcje! Jedynym sensownym rozwiązaniem było stworzenie “trybu wprowadzania”, dzięki któremu wciśnięcie klawisza a sprawi, że w tekście pojawi się litera a. Zupełnie jak na maszynie do pisania (spytaj ojca co to). Nazywamy to “trybem wprowadzania”. Niewiele się w tym trybie dzieje, poza zwykły, starym, nudnym pisaniem. Powinieneś używać tego trybu tylko jeżeli chcesz coś napisać, bo fajne rzeczy dzieją się tylko w trybie zwykłym (komend).\\ +Poznasz wiele wygodnych sposobów na przejście w tryb wprowadzania, ale na chwilę obecną powinieneś wiedzieć, że aby ten tryb opuścić i powrócić do trybu gry zręcznościowej, należy wcisnąć klawisz {\tt Escape}. +Gdy zrozumiesz, że w VIM-ie istnieją dwa zasadnicze tryby pracy, twoja praca z nim przestanie wprawiać Cię w zakłopotanie i otworzy się przed Tobą droga do zostania guru tego edytora. +\subsection{Poznaj schemat komend VIM-a} +Przez większość czasu albo będziesz uzyskiwał rezultaty po pojedynczym wciśnięciu klawisza, albo będziesz wprowadzał komendy kończąc je komendą ruchu (często również powtarzając te same naciśnięcia: tzw. “podwójny skok”). Kiedy rozpoczniesz naukę innych rzeczy (rejestry, powtórzenia itd.) może Ci się wydać, że VIM nie jest spójny, ale tak nie jest. Schemat komend jest raczej spójny. Po prostu niektóre jego części są opcjonalne.\\ + + {\bf Rejestr} (opcjonalnie, domyślnie rejestr {\tt “}) + + {\bf Powtórzenia} (opcjonalnie): np. 13 + + {\bf Operacja}: {\tt y} (Od angielskiego {\it yank} – {\it szarpać}. Możemy to rozumieć jako {\it wyszarpnięcie} tekstu) + + {\bf Przesunięcie} (w zależności od operacji): {\tt yy} ({\it podwójny skok}, żeby wykonać operację na aktualnym wierszu, konwencja używana w VI) \\ + +\noindent +Komendy VIM-a działają zgodnie z powyższym schematem. Są komendy, które nie używają rejestrów i takie, które nie przyjmują polecenia przesunięcia, ale w większości przypadków tak to właśnie wygląda.\\ +{\bf Rejestr} to w zasadzie po prostu schowek (dla operacji typu kopiuj/wklej). Większość edytorów udostępnia tylko jeden taki schowek. W VIM-ie masz ich aż nadto, ale nie musisz ich wszystkich używać, więc się nimi nie przejmuj aż nie dotrzesz do lekcji o rejestrach.\\ +{\bf Powtórzenia} to liczba oznaczająca ile razy chcesz daną operację wykonać. Jeżeli nie podasz żadnej liczby, domyślną wartością jest 1.\\ +{\bf Operacja} to klawisz, który rozkazuje VIM-owi coś zrobić. Najczęściej są to zwykłe naciśnięcia klawiszy i większość z nim nie wymaga klawiszy modyfikujących jak {\tt Shift}, {\tt Ctrl} czy {\tt Alt}.\\ +{\bf Przesunięcie} to polecenie oznaczające ruch kursora. Jest ich całkiem sporo, ponieważ jest wiele sposobów na poruszanie się. Nie panikuj jednak – na początku możesz używać klawiszy strzałek, jeżeli koniecznie musisz. Poświęciłem w tym poradniku całą sekcję na polecenia przesunięcia.\\ +Spróbujmy wyjaśnić jak taki schemat działa. Jeżeli chcę skopiować 13 wierszy do mojego domyślnego rejestru, mogę pominąć rejestr, wpisać 13 jako liczbę powtórzeń, wcisnąć {\tt y} jako komendę kopiowania i potem jeszcze raz {\tt y} jako komendę ruchu (co oznacza aktualny wiersz). Takie polecenie ({\tt 13yy}) skopiuje 13 wierszy do domyślnego rejestru, poczynając od aktualnego. Jeżeli nacisnę teraz {\tt p} (nie precyzując rejestru, pomijając liczbę powtórzeń i wiedząc, że komenda {\tt put} nie przyjmuje polecenia ruchu), to te wiersze zostaną wklejone zaraz za bieżącym.\\ +Znając ten schemat będziesz mógł wpływać na wszystko, czego się nauczysz o VIM-ie. Naucz się wszystkich sposobów poruszania się, a będziesz wiedział jak wycinać, wklejać, poprawiać formatowanie, zmieniać poziom wcięcia i wiele innych rzeczy, które chciałbyś zrobić. +\subsection{WYJDŹ!} + +Po tym jak uruchomisz sesję VIM, pewnie chciałbyś z niej kiedyś wyjść. Jest na to kilka sposobów. Spróbuj tych: + +\begin{tabular}{ l | p{9cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt :q} & \small{Zamyka aktualne okno (lub edytor, jeżeli to jest jedyne), jeżeli nie ma w nim niezapisanych zmian} \\ +{\tt :q!} & Zamyka aktualne okno, nawet jeżeli były w nim niezapisane zmiany \\ +{\tt :qa} & Zamyka wszystkie okna, jeżeli nie ma w nich niezapisanych zmian \\ +{\tt :qa!} & Zamyka wszystkie okna, nawet jeżeli były w nich niezapisane zmiany \\ +{\tt :wq} lub {\tt :x} lub {\tt ZZ} & Zapisuje zmiany i zamyka aktualne okno \\ \hline +\end{tabular}\\ + +\noindent +Kiedy wciśniesz dwukropek, kursor przeniesie się do lewego dolnego rogu ekranu. Później dowiesz się dlaczego. Na razie wystarczy, że będziesz wiedział, że tak powinno się dziać, a te polecenia działają. Zauważ, że przed {\tt ZZ} nie ma dwukropka.\\ +{\it Od tłumacza: Po poleceniach rozpoczynających się dwukropkiem należy wcisnąć klawisz \textit{\texttt{Enter}}, inaczej nie odniosą one skutku.}\\ +Jeżeli nie możesz sobie poradzić z wyjściem z VIM-a, upewnij się, że Caps-Lock jest wyłączony i wciśnij Escape. Jeśli sprawi Ci to radość, możesz go nacisnąć kilkukrotnie. Jeżeli usłyszysz brzęczyk, będziesz wiedział, że wcisnąłeś go wystarczającą liczbę razy. Wtedy podane wyżej polecenia na pewno zadziałają. +\subsection{Mnemonika} + +Nie wszystkie komendy są łatwe do zapamiętania. Twórcy VIM-a bardzo się starali, ale łatwo jest znaleźć więcej niż 26 czynności, które chciałbyś wykonywać korzystając z edytora, a poza tym tak się dziwnie składa, że niewiele jest słów zaczynających się na literę {\it q} i mających jakiś sens w programie do edycji tekstu. Jednakże wiele komend da się łatwo zapamiętać. Są to komendy do odnajdywania najbliższego znaku (ang. {\it Find} – {\tt f}), przesunięcia o jedno słowo do tyłu ({\it Back one word} – {\tt b}) lub do przodu ({\it Word} – {\tt w}) itd.\\ +Wiele poleceń jest mnemonicznych, pod warunkiem, że znasz żargon. Przykładowo: ponieważ zarówno {\it copy} (kopiuj) jak i {\it cut} (wytnij) zaczynają się na {\it c}, używamy slangowych {\it yank} (wyszarpnij – jako kopiuj), {\it delete} (usuń – jako wytnij) i {\it put} (połóż – jako wklej). {\tt Y}, {\tt D}, {\tt P}. Może się to wydawać nieco dziwne, ale da się to zapamiętać. Pamiętaj, że z czasem przechodzi to do pamięci mięśniowej, ale autorzy VI i VIM-a starali się nie być całkowicie abstrakcyjni, gdy wszystko leżało w ich gestii. Czasem nie mieli jednak wielkiego wyboru. +\subsection{Wywołanie} +Gdy już wiesz jak wyjść z VIM-a, pora się nauczyć jak się do niego wejść. Zazwyczaj uruchamiamy VIM-a z wiersza poleceń, aczkolwiek całkiem możliwe, że masz do dyspozycji jakieś menu bądź inne sposoby na uruchamianie programów.\\ +Jest kilka sposobów na uruchomienie VIM-a: + +\begin{tabular}{ l | p{5,4cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt vim} & Uruchomienie z pustym oknem \\ +{\tt vim plik.txt} & Uruchomienie z załadowanym i gotowym do edycji plikiem plik.txt \\ +{\tt vim +N plik.txt} & Uruchomienie z załadowanym i gotowym do edycji plikiem plik.txt; rozpoczyna edycję w linii N \\ +{\tt vimtutor} & Uruchomienie w trybie samouczka -- całkiem niezły pomysł \\ +{\tt vimdiff plik1.txt plik2.txt} & Uruchomienie w trybie porównywania i łączenia dwóch plików \\ +{\tt vim .} & Uruchomienie w trybie przeglądarki plików \\ \hline +\end{tabular}\\ + +\noindent +Oprócz tych wymienionych powyżej, jest jeszcze więcej. Na początek te powinny jednak wystarczyć. Wypróbuj {\tt vimdiff} i {\tt vimtutor}. Niektóre ze sposobów uruchamiania nie zadziałają dopóki nie skonfigurujesz swojego {\it .vimrc}, ale o tym później.\\ +Jeżeli zamiast {\tt vim} napiszesz {\tt gvim}, to uruchomi się wybajerzona wersja graficzna VIM-a (oczywiście zakładając, że jest zainstalowana). Ma ona kilka dodatkowych możliwości. Zapewne spodoba Ci się bardziej niż czysty VIM, bo jest ona jak VIM z polewą czekoladową. Wszystko, co mówimy tutaj o VIM-ie działa również w gVIM-ie, więc możesz bez obaw używać tego tutoriala.\\ +Nie jesteś skazany na edycję tylko jednego pliku jednocześnie. Możesz uruchomić (g)VIM-a z wieloma nazwami plików jako argumentami. Jeżeli tak zrobisz, to jest kilka parametrów, dzięki którym możesz uzyskać ciekawe efekty. Oczywiście ciekawsze będą jak nauczysz się obsługiwać podzielone okna, więc pewnie będziesz chciał zajrzeć do nich później. + +\begin{tabular}{ l | p{8,4cm} } +{\bf Parametr} & {\bf Rezultat} \\ \hline +{\tt -o} (mała litera “o”) & Otwiera wiele plików w oknach ułożonych w poziomie \\ +{\tt -O} (wielka litera “O”) & Otwiera wiele plików w oknach ułożonych w pionie \\ +{\tt -p} & Otwiera wiele plików w osobnych kartach. (Osobiście nie cierpię tego) \\ \hline +\end{tabular} + +\subsection{Kontekst jest ważniejszy niż pozycja} +Biedna duszyczka, używająca VIM-a po raz pierwszy będzie wciskać klawisze strzałek, poruszając się w kodzie strasznie nieefektywnie. Będzie przewijać ekran o całą stronę w górę i w dół (przy okazji: to odpowiednio {\tt \^f} i {\tt \^b}) i przeczesywać kod swoimi zmęczonymi oczami. Ta biedna osoba jest powolna, jeszcze nie uświadomiona i zapewne bierze VIM-a za kiepską wersję windowsowego notatnika, zamiast za potężne narzędzie jakim jest.\\ +Przy okazji -- klawisze strzałek nie zawsze działają w VIM-ie. Nie obarczaj jednak winą za to VIM-a! Tak naprawdę jest to sposób w jaki Twój terminal obsługuje te klawisze. Przez to VIM nie potrafi rozpoznać, że Twoje strzałki to strzałki. Jeżeli masz ten problem, będziesz musiał poszukać rozwiązania na własną rękę.\\ +Żeby używać VIM-a porządnie, musisz się najpierw nauczyć porządnie poruszać.\\ +Nie przewijaj w poszukiwaniu tekstu. Nie używaj do tego swoich oczu. Nie wiem czy zauważyłeś, ale od jakiegoś czasu komputery robią to za nas. Masz tutaj garść najważniejszych poleceń ruchu. Najłatwiej jest się poruszać szukając: + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt /} & Wyszukaj do przodu; zostaniesz zapytany o wzór \\ +{\tt ?} & Wyszukaj do tyłu; zostaniesz zapytany o wzór \\ +{\tt n} & Powtórz ostatnie wyszukiwanie (tak jak kropka powtarza komendy) \\ +{\tt N} & Powtórz ostatnie wyszukiwanie, w przeciwnym kierunku \\ +{\tt tx} & Przesuń do (ang. {\it to}) litery x, zatrzymując się tuż przed nią -- przydatne przy komendach usunięcia i zmiany \\ +{\tt fx} & Znajdź (ang. {\it find}) literę x, zatrzymując się na niej -- również przydatne przy komendach usunięcia i zmiany \\ \hline +\end{tabular}\newpage + +\noindent +Jeżeli szukanie zbytnio Ci nie pomoże, rozważ skoki: + +\begin{tabular}{ l | p{9,9cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt gg} & Początek pliku \\ +{\tt G} & Koniec pliku \\ +{\tt 0} (cyfra zero) & Początek wiersza \\ +{\tt w} & Jedno słowo do przodu \\ +{\tt W} & Następne słowo rozdzielone spacjami (pomija znaki specjalne) \\ +{\tt b} & Jedno słowo do tyłu \\ +{\tt B} & Poprzednie słowo rozdzielone spacjami (pomija znaki specjalne) \\ +{\tt e} & Koniec aktualnego słowa, lub następnego, jeżeli już jesteśmy na końcu \\ +{\tt E} & Koniec aktualnego słowa rozdzielonego spacjami (pomija znaki specjalne) \\ \hline +\end{tabular}\\ + +\noindent +Poniższe komendy są bardzo przydatne, a przy okazji łatwe do zapamiętania, jeżeli znasz wyrażenia regularne: + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt \^{}} & Początek tekstu w danej linii - zdecydowanie lepsze niż korzystanie z klawiszy strzałek bądź komendy {\tt h} \\ +{\tt \$} & Koniec tekstu w danej linii. Zdecydowanie lepsze niż korzystanie z klawiszy strzałek bądź komendy {\tt l} \\ \hline +\end{tabular}\\ + +\noindent +Kilka ciekawszych komend: + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt \%} & Odpowiadający nawias, klamra itp. \\ +{\tt \{} & Początek akapitu \\ +{\tt \}} & Koniec akapitu (najbliższa pusta linia) \\ +{\tt (} & Początek zdania (zdania są oddzielone kropką i spacją) \\ +{\tt )} & Koniec zdania \\ +{\tt \"{}} & Miejsce ostatniej zmiany w aktualnym wierszu \\ +{\tt ]]} & Następna funkcja/klasa (C, Java, C++, Python) \\ +{\tt [[} & Poprzednia funkcja/klasa (C, Java, C++, Python) \\ \hline +\end{tabular}\newpage + +\noindent +Ostatecznie, jeżeli nie jesteś w stanie wykorzystać wyszukiwania, skoków itd., nadal możesz korzystać z klawiatury, więc odłóż mysz na bok: + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt h} & W lewo o jeden znak \\ +{\tt l} & W prawo o jeden znak \\ +{\tt k} & W górę o jeden wiersz \\ +{\tt j} & W dół o jeden wiersz \\ +{\tt \^{}f} & W dół o jeden ekran \\ +{\tt \^{}b} & W górę o jeden ekran \\ \hline +\end{tabular}\\ + +\noindent +Dobrym pomysłem jest ustawienie opcji {\tt hls} ({\it highlight search} – podświetlaj wyszukiwane) w pliku .vimrc. Niedługo się dowiesz jak to zrobić. Tymczasowo możesz wpisać {\tt :set hls} i wcisnąć {\tt Enter}. +\subsection{Cytowanie metaznaków w wyrażeniach regularnych} +Jeżeli nie wiesz czym są wyrażenia regularne, pomiń tę sekcję. Dla tych, który wiedzą i zdają sobie sprawę z tego, że komenda {\tt /} przyjmuje wyrażenie regularne, a nie tylko zwykły tekst, będzie ona ważna. W pozostałych przypadkach wyda się pewnie kompletnie nie na miejscu i powinna zostać pominięta.\\ +Powinieneś wiedzieć jak używać regeksów, bo kilka sztuczek z ich wykorzystaniem może sprawić, że będzie Ci się lepiej korzystało z Uniksa/Linuksa/Maca. Jest to zbyt rozległy temat, żeby go tutaj przedstawiać, ale możesz zerknąć na któryś ze świetnych tutoriali czy referencji dostępnych w sieci.\\ +Najważniejszą sprawą do zapamiętania jest to, że VIM stawia na wygodę jeżeli chodzi o wyrażenia regularne. Ponieważ często szukasz, VIM zakłada, że wpisując {\tt /+} chcesz znaleźć najbliższy znak +. W wyniku tego założenia wszystkie metaznaki muszą być poprzedzone wstecznym ukośnikiem ({\tt $\backslash$}). Czasem jest to problematyczne, ale jeżeli naprawdę chcesz znaleźć nawias poprzedzony plusem, jest to znaczne ułatwienie. +\subsection{Nie panikuj, masz historię poleceń} +Komendą cofającą zmiany jest {\tt u} (ang. {\it undo}). Niezbyt trudne do zapamiętania, prawda? Jak już prędzej wspomniałem, wiele poleceń VIM-a jest mnemonicznych.\\ +Komendą powtórzenie cofniętych zmian powinna być litera {\tt r} (ang. {\it repeat}), ale jest już zajęta przez polecenie zamiany ({\it replace}); powiemy o tym nieco później. Pozostaje nam {\tt Ctrl-R} ({\tt \^{}r}). Cóż\ldots nie można mieć wszystkiego.\\ +Jest jeszcze troche odnośnie cofania i powtarzania, ale na razie tyle powinno wystarczyć. Ciesz się, że już możesz cofać i potwarzać zmiany. VIM nie jest już taki nieudolny i niewybaczający, jak mogło Ci się wydawać, chociaż wciąż nie musisz go lubić. Poczekaj tylko, aż do gry wejdzie pamięć mięśniowa.\\ +Jeżeli narobisz naprawdę niezłego bałaganu, to po prostu wyłącz edytor bez zapisywania ({\tt :qa!}).\\ +Jeżeli bardzo się obawiasz o swoje pliki, albo jesteś po prostu bardzo ostrożny, powinieneś używać jakiegoś systemu kontroli wersji. Zalecam, żebyś tak czy siak zaczynał naukę na bezwartościowych plikach, w jakimś tymczasowym katalogu, ale gdy przejdziesz do prawdziwej pracy, nie powinieneś się obawiać wprowadzania zmian. Kontrola wersji jest dobrym zabezpieczeniem i może być z powodzeniem stosowana jako sposób na kopie bezpieczeństwa. Proponuję rozważyć \href{http://git-scm.com/}{Gita} i \href{http://mercurial.selenic.com/}{Mercuriala} -- oba są jednocześnie proste i potężne. +\subsection{Wielkie litery i ŚMIERĆ PRZEZ CAPSLOCK} +W przypadku wielu poleceń {\tt Shift} albo odwraca kierunek ({\tt N} jest przeciwieństwem {\tt n}; zobacz: następny punkt), albo całkowicie zmienia sposób działania. Poruszając się do przodu o jedno słowo ({\tt w}) można wcisnąć {\tt W}, żeby nadal przesuwać się o jedno słowo, ale traktując znaki specjalne jako jego część. To samo tyczy się przeciwnego kierunku – {\tt b} i {\tt B}.\\ +Ponieważ jednak wielkie litery mogą mieć zupełnie inne znaczenie niż ich małe odpowiedniki, powinieneś uważać, żeby nie wcisnąć klawisza {\tt CapsLock}! Czasem zdarzy się, że przez przypadek wciśniesz {\tt CapsLock} i gdy będziesz chciał przejść do kolejnego wiersza ({\tt j}), połączysz go z obecnym. Wiele innych niepożądanych zmian może się zdarzyć w takiej sytuacji, jeżeli Twoje palce będą szybko przemierzać klawiaturę w celu wykonania jakiegoś skomplikowanego ciągu komend. To okropne.\\ +Kiedy spotka Cię ŚMIERĆ PRZEZ CAPSLOCK, powinieneś od razu go wyłączyć i wciskać {\tt u} tak długo, aż cofniesz niechciane zmiany. Jeżeli uważasz jednak, że to gra nie warta świeczki, wpisz po prostu {\tt :e!} i zatwierdź enterem, a VIM wczyta plik ponownie z dysku. Trochę to kłopotliwe, ale na pewno kiedyś Ci się to zdarzy, więc warto, żebyś o tym wiedział. Niektórzy z tego powodu wyłączają {\tt CapsLock} na stałe. +\subsection{Wstaw, nadpisz, zmień} +W VIM-ie jest kilka różnych sposobów na rozpoczęcie wprowadzania tekstu, jak już zostało wspomniane w sekcji {\it Tryby pracy}.\\ +Twoim standardowym trybem pracy powinien być tryb komend. Po wciśnięciu niektórych klawiszy przechodzisz w tryb wstawiania lub nadpisywania. W trybie wstawiania, wszystko co piszesz zostaje wstawione w miejsce kursora, a to co było za nim jest spychane do prawej bądź do kolejnego wiersza.\\ +Z kolei w trybie nadpisywania, wszystkie naciśnięcia klawiszy są wpisywane podobnie jak w trybie wstawiania, z tym wyjątkiem, że tekst za kursorem zamiast zostać odepchniętym, jest zastępowany przez kolejne wpisywane znaki. Aby przejść do tego trybu, musisz wydać odpowiednie polecenie w trybie komend.\\ +W trybie wykonywania (ang. {\it ex mode}) wpisujesz łańcuch znaków w pole u dołu ekranu. Przejdziemy do tego później, bo jest to potężna rzecz. Jest też nieco zawiła, więc poczekamy z nią trochę. Do tego trybu przechodzisz wciskając {\tt :} w trybie komend.\\ +Z każdego tych trybów możesz powrócić do trybu normalnego (komend) wciskając Escape. Bardzo przydatny klawisz. + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt i} & Rozpocznij pisanie w miejscu kursora \\ +{\tt I} & Rozpocznij pisanie na początku wiersza. Zdecydowanie lepsze niż wciskanie \^{}, a następnie {\tt i} \\ +{\tt a} & Rozpocznij pisanie za kursorem \\ +{\tt A} & Rozpocznij pisanie na końcu wiersza. Zdecydowanie lepsze niż wciskanie $\backslash\$$, a następnie {\tt a} \\ +{\tt r} & Zamień pojedynczy znak w miejscu kursora \\ +{\tt R} & Przejdź do trybu nadpisywania, w którym niszczycielsko nadpisujesz wszystko, aż do naciśnięcia {\tt Escape} \\ +{\tt s} & Zamień pojedynczy znak w miejscu kursora i przejdź do trybu wstawiania \\ +{\tt c} & Komenda zastąpienia. Wymaga komendy przesunięcia następującej po niej. Najczęściej używam {\tt cw} i {\tt cc} \\ +{\tt C} & Jak {\tt c}, ale stosowane do całej linii \\ +{\tt o} & Wstawia pustą linię pod bieżącą \\ +{\tt O} & Wstawia pustą linię nad bieżącą \\ +{\tt :} & Przejdź w tryb wykonywania poleceń (dla zaawansowanych uczniów) \\ +{\tt !} & Przejdź w tryb filtrowania przy pomocy powłoki systemowej (dla bardzo zaawansowanych uczniów) \\ \hline +\end{tabular}\\ + +\noindent +Zastanów się przez chwilę nad wagą komendy {\tt c}. Jeżeli użyjesz jej w połączeniu z {\tt t} lub {\tt f}, staje się ona naprawdę potężnym narzędziem. Gdybyś miał kursor na literze {\it Z} na początku tego akapitu, mógłbyś wykonać komendę {\tt ct.}, żeby przepisać całe zdanie, zachowując kropkę. To samo tyczy się innych, jak na przykład {\tt d} do usuwania. Polecenia ruchu znacząco zwiększają możliwości komendy {\tt c} i dlatego tak ważne jest, abyś je dobrze znał. +\subsection{NIE POZOSTAWAJ W TRYBIE WSTAWIANIA} +VIM jest stworzony do tego, żeby więcej się przemieszczać po tekście, niż edytować. Nagradza Cię za dostosowanie się do takiego trybu pracy – głównie tryb komend, z krótkimi przerwami na wprowadzanie. \\ +Jeżeli będziesz próbował używać VIM-a jako kiepskiego zamiennika notatnika, tryby i nawigacja sprawią, że nigdy nie będziesz wydajny. Jak chcesz żeglować, musisz wsiąść do łódki. Jak chcesz efektywnie korzystać z VIM-a, musisz zaprzyjaźnić się z trybem komend.\\ +Jeśli więc zatrzymujesz się, żeby nad czymś pomyśleć, wciśnij {\tt Escape}. Jeżeli nie jesteś w trakcie pisania, powinieneś być w trybie komend. Jak chcesz przejsć do następnej linijki czy w jakiekolwiek inne miejsce w pliku, wciśnij {\tt Escape}. Jak chcesz odejść od klawiatury, wciśnij {\tt Escape}. W przeciwnym wypadku, zaczniesz wprowadzać komendy i zanim zorientujesz się, że nie jesteś w trybie komend, stracisz możliwość sensownego używania {\tt .} czy cofania. Natomiast kiedy chcesz w trakcie pisania wydać jedno polecenie możesz zrobić to przez wciśnięcie kombinacji {\tt Ctrl+o}. Vim po wykonaniu go automatycznie powróci do trybu wstawiania. +\subsection{Dobry .vimrc to szczęście} +Kiedy uruchamiasz VIM-a, ten najpierw wczytuje Twoje ustawienia, zanim zacznie robić cokolwiek interesującego. Możesz edytować plik .vimrc w swoim katalogu domowym. Dotychczasowe lekcje dostarczyły Ci wystarczającej ilości informacji, żebyś był w stanie zmodyfikować .vimrc i dodać do niego poniższe komendy. Zabawa polega na tym, żebyś wprowadził komendy z lewej kolumny tabeli. Będziesz musiał je przepisać i poprawić ewentualne literówki. Kiedy już to zrobisz, zapiszesz plik i wyjdziesz z VIM-a, a gdy następnym razem go uruchomisz, Twoje ustawienia zostaną wczytane. Możesz edytować ten plik w dowolnej chwili.\\ +W VIM-ie jest nieco wyrafinowanej magii. Często jednak zdarza się, że ta magia jest domyślnie wyłączona w dystrybucji. {\it Brakuje} uzupełniania składni wiersza poleceń, kolorowania składni, przeglądarki plików i wielu innych elementów, dopóki nie włączysz ich w swoim .vimrc.\\ +Istnieje bardzo przyjemny przewodnik po ustawieniach VIM-a, a nawet interfejs do łatwego włączania i wyłączania poszczególnych opcji. Zdaje się, że nie jest to zbyt powszechna wiedza, bo dowiedziałem się o tym dopiero w tym roku. Chciałbym wiedzieć o tym od samego początku\ldots + +{\tt :options} + +{\tt :browse options} + +{\tt :browse} + +\noindent +W oknie tym możesz przeglądać wszystkie dostępne opcje, a nawet zmieniać je. Możesz przeczytać krótki opis przypisany do każdej opcji, albo wcisnąć na nim {\tt Enter} i przeczytać dokładniejszy opis. Jeżeli wciśniesz {\tt Enter} na którejś z opcji, zostanie ona przełączona lub jej wartość zostanie zmieniona.\\ +Każda z poniższych komend ma również wersję skróconą, ale te możesz poznać później. Na początek spróbuj wprowadzić pierwsze pięć komend (każdą w osobnej linii), zapisz plik i otwórz go ponownie, aby dodać kolejne. Zauważysz, że druga sesja będzie miała włączone kolorowanie składni i będzie wyświetlać dodatkowe informacje. + +\noindent +\begin{tabular}{ p{4,9cm} | p{8cm} } +{\bf Komenda w .vimrc} & {\bf Znaczenie} \\ \hline +{\tt syntax enable} & Włącza magię. Włączając w to przeglądarkę plików i kolorowanie składni \\ +{\tt set showmode} & Pokazuje kiedy jesteś w trybie wprowadzania/nadpisywania \\ +{\tt set showcmd} & Kiedy komenda się wykonuje, pokazuj ją w pasku stanu \\ +{\tt set wildmenu} & Włącza magię dla uzupełniania poleceń w trybie wykonywania \\ +{\tt set ruler} & Włącza {\it liniał} (informacje o stanie edytora) u dołu ekranu \\ +{\tt runtime ftplugin/man.vim} & Włączę obsługę stron man (wpisz {\tt :Man }) \\ +{\tt set autoindent} & Dodawaj wcięcia inteligentnie, zamiast cały czas powracać do samego początku wiersza \\ +{\tt set expandtab} & Zamieniaj znak tabulacji na ciąg spacji \\ +{\tt set nowrap} & Nie zawijaj tekstu (sprawia, że okna wyglądają brzydko) \\ +{\tt set hlsearch} & Podświetlaj wszystkie wyniki wyszukiwania \\ +{\tt set showmatch} & Podświetlaj odpowiadające nawiasy, klamry itd. \\ +{\tt set ignorecase} & Ignoruj wielkość znaków przy wyszukiwaniu \\ +{\tt set smartcase} & Jeżeli wyszukiwana fraza zawiera wielkie litery, przestań ignorować wielkość znaków \\ +{\tt set path=., .., /usr/include/*, /usr/share/*} & Wskaż ścieżki, w których VIM ma szukać plików \\ +{\tt set spelllang=pl\_pl} & Kiedy chcę sprawdzania pisowni, to chcę jej w języku polskim\\ \hline +\end{tabular}\\ + +\subsection{Pomoc jest w drodze} +VIM jest wyposażony w mechanizm pomocy. Powinieneś wiedzieć jak z niego korzystać.\\ +Wpisz {\tt :help}, a otworzy się nowe okno z treścią pomocy. Możesz się po nim poruszać przy pomocy klawiszy strzałek lub dowolnych komend ruchu, które poznałeś.\\ +Zawsze możesz wprowadzać {\it dziwne} klawisze wciskając najpierw {\tt \^{}v}, a następnie ten klawisz. Jest to najbardziej przydatne właśnie w przypadku pomocy. Możesz wpisać {\tt :help \^{}v\^{}t} ({\tt Ctrl+v}, {\tt Ctrl+t}), by uzyskać pomoc na temat komendy {\tt \^{}t}. Zgodnie z konwencją, możesz uzyskać ten sam rezultat wpisując {\tt :help CTRL-T}. To naprawdę ważna rzecz.\\ +Większość dystrybucji VIM-a dostarcza program {\tt vimtutor}. Program ten nauczy Cię jak używać VIM-a\ldots przy pomocy VIM-a. Całkiem przydatne narzędzie (brawa dla autora!).\\ +System pomocy jest wyposażony w linki. Jeżeli się na jakiś natkniesz, możesz przesunąć do niego kursor (tylko nie waż się korzystać ze strzałek!) i wcisnąć {\tt \^{}]} ({\tt Ctrl+]}). Tak, to dziwna i dość abstrakcyjna kombinacja klawiszy. Nie tylko przeniesie Cię do miejsca wskazywanego przez link, ale też umieści Twoją aktualną pozycję na stosie, pozwalając Ci do niej wrócić. Jeżeli będziesz chciał to uczyć, po prostu wciśnij {\tt \^{}t} (tak, kolejny abstrakcyjny skrót), aby zdjąć aktualny link ze stosu i powrócić do poprzedniej pozycji. Komendy {\tt \^{}]} i {\tt \^{}t} nie są zbyt łatwe do zapamiętania, ale będziemy ich również używać do nawigacji w kodzie, więc nauczenie się ich nie będzie kompletną stratą energii. +\subsection{Podwójny skok} +Zgodnie z przyjętą konwencją, wciśnięcie tego samego klawisza polecenia podwójnie, spowoduje, że zadziała on dla całego bieżącego wiersza. Jeżeli chcesz skopiować daną linię, wciśnij {\tt yy}. Jak chcesz ją usunąć, wciśnij {\tt dd}. Przepisać na nowo – {\tt cc}. Ta konwencja jest używana w całym VIM-ie, łącznie ze specjalnym przypadkiem pt. {\it zapisz i wyjdź} – {\tt ZZ}. Wykonywanie operacji na całym wierszu jest dość częste, więc sensownym było sprawienie, żeby było to wygodne. +\subsection{Pozbywanie się zbędnych rzeczy} +Możesz się pozbyć znaku pod kursorem wciskając {\tt x}. Jeśli chcesz go wcisnąć dziesięć razy, oszczędź sobie trudu i wpisz {\tt 10x}. Może to być przydatne, ale zapewne szybko się znudzisz albo liczeniem ile razy chcesz wykonać tę operację, albo przytrzymywaniem klawisza {\it x}. Ja bym się znudził.\\ +Zdecydowanie wygodniejszą komendą do usuwania tekstu jest {\tt d} (ang. {\it delete}). To jedna z komend łatwych do zapamiętania.\\ +{\tt d} przyjmuje polecenie ruchu. Powinieneś poznać kilka z nich w trakcie poprzednich lekcji. Podstawowym założeniem jest, że będziesz usuwał tekst od znaku pod kursorem do jakiegoś innego miejsca w pliku.\\ +Możesz usunąć bieżący wiersz, wciskając {\tt dd}, albo linię aktualną wraz z następną, wciskając {\tt dj}. W podobny sposób {\tt d\}} usunie tekst aż do końca akapitu, a {\tt dG} – do końca pliku. Możesz zauważyć, że wszystkie komendy, które przyjmują polecenie ruchu działają w ten sposób (włącznie z {\tt c}). Każda komenda ruchu, której się nauczysz, zwiększa Twoje umiejętności kopiowania, usuwania i poprawiania tekstu. Te dodatkowe moce są przyczyną, dla której powinieneś umieć się dobrze poruszać w VIM-ie.\\ +{\tt d} przyjmuje także licznik powtórzeń, więc jeśli wpiszesz {\tt 23dd}, usuniesz 23 wiersze, począwszy od bieżącego. To może się przydać.\\ +I w końcu – mamy do dyspozycji rejestry. Rejestr w VIM-ie jest jak schowek, którego używałeś w innych programach. Kiedy usuwasz tekst jest on zapisywany do rejestru, żebyś mógł go potem wkleić w innym miejscu, wciskając {\tt p} ({\it put} lub {\it paste}). Oczywiście możesz użyć innego rejestru niż domyślny. Definiuje się go przy pomocy cudzysłowu, po którym następuje nazwa rejestru (dowolna litera, z uwzględnieniem wielkości). Oznacza to, że możesz kopiować różne fragmenty tekstu przez {\it wyszarpywanie} ({\tt y} – {\it yank}) lub usuwanie, i przechowywać je w różnych rejestrach. Potem wystarczy, że wklejając wybierzesz odpowiedni rejestr.\\ +Wklejanie również używa rejestrów. Wygląda to wtedy tak: {\tt \"{}ap} (dla rejestru o nazwie {\it a}). Możesz nawet wkleić zawartość danego rejestru wielokrotnie, jeżeli użyjesz licznika powtórzeń (zerknij do lekcji o schemacie komend).\\ +Tak naprawdę masz więcej rejestrów niż wymieniłem i możesz z nimi robić również inne rzeczy, ale tyle powinno wystarczyć na szybką lekcję o usuwaniu. +\subsection{Używaj kropki} +Każda akcja edycji jest nagrywana. Powiedzmy, że właśnie usunąłeś wiersz (wciskając {\tt dd}). Edytor wie, że usunąłeś linię. Możesz powtórzyć akcję edycji (tj. usunąć kolejną linię) wciskając kropkę ({\tt .}). Możesz nawet zastosować standardowy wzór i wskazać rejestr oraz liczbę powtórzeń i dopiero wtedy wcisnąć kropkę (ona pamięta komendę i przesunięcie). Jest to szczególnie przydatne, gdy ostatnio wykonaną komendą było {\tt cw} – powtórzy operację zmiany na tekście pod kursorem.\\ +Ponieważ kropka powtarza ostatnią edycję, jest to jeden z najważniejszy klawiszy. Powinieneś nauczyć się na nim polegać. Jest to jedna z najlepszych rzeczy, jakie daje Ci VIM. +\subsection{Używaj gwiazdki} +Gwiazdka ({\it asterysk}, {\tt *}) jest świetną komendą, szczególnie jeżeli w swoim .vimrc masz włączoną opcję {\tt hlsearch}. Przeskakuje ona do kolejnego wystąpienia słowa, na którym masz kursor. Jednocześnie podświetla wszystkie wystąpienia danego słowa w tekście. + +\begin{tabular}{ l | p{10,5cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt *} & Przeskocz do następnego wystąpienia aktualnego słowa w tekście\\ +{\tt \#} & Przeskocz do poprzedniego wystąpienia aktualnego słowa w tekście \\ \hline +\end{tabular} +\subsection{Rejestry} +Większość edytorów udostępnia pojedynczy schowek. Kiedy kopiujesz bądź wycinasz tekst, tracisz to, co w nim do tej pory było. W rezultacie skaczesz po pliku kopiując z jednego miejsca w drugie. Jeżeli masz szczęście, możesz podzielić okno na dwie części i skakać między nimi. Dostarcza to sporo ciężkiej, ręcznej pracy i ćwiczeń koordynacji wzrokowo-ruchowej, żeby znaleźć tekst, zaznaczyć, wyciąć, znaleźć miejsce i wreszcie wkleić tekst w drodze do nirwany.\\ +Najprawdopodobniej wystarczy kilka minut takiego przeklejania, żeby zrobiło Ci się niedobrze.\\ +VIM daje nam inne rozwiązanie tego problemu. Niestety, ma też inną terminologię. Zamiast buforów mamy rejestry. Ten sam pomysł, inna nazwa ({\it bufor} oznacza coś zupełnie innego w VIM-ie). Możesz znaleźć miejsce, z którego chcesz kopiować, skopiować lub wyciąć tekst do różnych rejestrów, przeskoczyć do miejsca docelowego i wkleić zawartość tychże rejestrów. To wszystko wymaga tylko jednego większego ruchu.\\ +Lista dostępnych rejestrów: (za dokumentacją VIM-a, dostępne przez {\tt :help registers}) + +\begin{tabular}{ l | p{10,5cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt \"{}} & Domyślny rejestr \\ +{\tt a-z}, {\tt A-Z} & Małe i wielkie litery \\ +{\tt +} i {\tt *} & Rejestry zaznaczenia, powiązane ze schowkiem systemowym (pozwalają na kopiowanie tekstu z i do VIM-a) \\ +{\tt \_} & Czarna dziura - używany jeżeli nie chcemy nadpisać zawartości domyślnego rejestru \\ \hline +\end{tabular}\\ + +\noindent +{\it Od tłumacza: W systemach z rodziny Windows rejestry \textit{\texttt{+}} i \textit{\texttt{*}} oznaczają to samo – schowek systemowy, natomiast w systemach korzystających z X11 odpowiednio – schowek (wklejanie zazwyczaj przez \textit{\texttt{ Ctrl+C}}) i bieżące zaznaczenie (wklejanie środkowym przyciskiem myszy).} \\ +Jest jeszcze kilka innych rejestrów specjalnego przeznaczenia, ale zostawiam je jako ciekawostkę, do doczytania w systemie pomocy. Są to takie rejestry jak rejestr {\it małych usunięć} czy rejestry numerowane. Naprawdę, nie musisz ich znać.\\ +Żeby rozróżnić rejestr {\tt y} od komendy {\tt y}, VIM wymaga, żebyś poprzedził nazwę rejestru znakiem cudzysłowu. Tak więc {\tt y} oznacza komendę, a {\tt \"{}y} – rejestr. Jeżeli wpiszesz {\tt \"{}y}, to VIM będzie oczekiwał na dokończenie wzoru, zapewne przez opcjonalną liczbę powtórzeń, komendę i polecenie ruchu (jeśli jest wymagane). Oto kilka przykładów o rosnącym stopniu skomplikowania: + +\begin{tabular}{ l | p{10,5cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt dd} & Wytnij bieżący wiersz do domyślnego rejestru \\ +{\tt \"{}add} & Wytnij bieżący wiersz do rejestru {\it a} \\ +{\tt \"{}y\$} & Skopiuj tekst od kursora do końca wiersza, do rejestru {\it y} \\ +{\tt \"{}byy} & Skopiuj bieżący wiersz do rejestru {\it b} \\ +{\tt \"{}c24dd} & Wytnij 24 linie poczynając od bieżącej i wstaw je do rejestru {\it c} \\ \hline +\end{tabular}\\ + +\noindent +Jestem przekonany, że {\tt \"{}c24dd} wydaje się nieco szalone, ale pomyśl jak byś to zrobił korzystając z notatnika czy czegoś w tym rodzaju. Tutaj mamy tylko 6 klawiszy, tylko jeden z nich wciśnięty z shiftem, i nie musisz ani razu sięgać po mysz. Byłby to niesamowicie wydajny sposób na wycięcie 24 linii do nazwanego rejestru, zakładając że akurat wiesz ile linii chcesz skopiować. Bez tej wiedzy, praca włożona w policzenie wierszy bez problemu przeważy wygodę komendy. Przykład ten pozostaje więc w sferze akademickich rozważań, ale jednocześnie otwiera furtkę do wizualnego zaznaczania tekstu do skopiowania/wycięcia. +\subsection{Zaznaczanie} +VIM posiada dwa tryby zaznaczania tekstu: wizualny i niewizualny. Istnieje spore prawdopodobieństwo, że będziesz chciał skorzystać z trybu wizualnego do łatwiejszego kopiowania, więc poświęćmy mu chwilę. + +\begin{tabular}{ l | p{9,9cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt v} & Zaznaczanie znaków \\ +{\tt V} & Zaznaczanie wierszy \\ +{\tt \^{}v} ({\tt Ctrl+v}) & Zaznaczanie prostokątnego obszaru \\ +{\tt gv} & Ponowne zaznaczenie ostatnio zaznaczonego obszaru \\ \hline +\end{tabular}\\ + +\noindent +Komenda do zaznaczania wizualnego to {\tt v}. Możesz wcisnąć {\tt v}, przejść do (lub wyszukać) końca interesującego Cię obszaru i wykonać polecenie kopiowania ({\tt y}) bądź usuwania ({\tt d}). Tak właściwie powinieneś to zrobić i powrócić. Wciśnij {\tt v} ponownie, żeby opuścić tryb wizualny.\\ +Czasem chcesz zaznaczać całe wiersze od razu. VIM korzysta w tym celu z komendy {\tt V}. Działa ona dokładnie tak jak małe {\tt v}, z tym że zawsze zaznacza całe linie. Oczywiście ponowne wciśnięcie {\tt V} wyłącza tryb zaznaczania wierszy.\\ +Innym razem może się zdarzyć tak, że będziesz chciał zaznaczyć prostokątny obszar zamiast całych wierszy czy ciągu znaków. Żeby wejść do trybu zaznaczania prostokątnego (blokowego), wciśnij {\tt \^{}v} ({\tt Ctrl+v}). Zauważ, że gdy jesteś w trybie wprowadzania, {\tt \^{}v} ma zupełnie inne znaczenie. Niech Cię to nie zdziwi. Wklejanie prostokątnych obszarów to naprawdę świetna funkcja.\\ +Inną fajną rzeczą jest to, że możesz wejść do trybu wizualnego przy pomocy {\tt v}, zaznaczyć kilka znaków, a potem przełączyć się na zaznaczanie wierszy wciskając {\tt V} albo nawet {\tt \^{}v}, żeby zaznaczyć prostokątny obszar.\\ +Po tym jak opuścisz tryb wizualny, obszar, który zaznaczyłeś, nie jest już podświetlony. System pomocy VIM-a podpowiada, że możemy powrócić do poprzedniego trybu zaznaczania z ostatnio zaznaczonym obszarem wydając polecenie gv. Bawiłem się tym trochę i muszę powiedzieć, że jest to całkiem przydatne.\\ +Zaznaczałem cały plik ({\tt ggVG}) i kopiowałem go do systemowego schowka ({\tt \"{}+y}). Potem przełączałem się do edytora bloga i wciskałem standardowe {\tt \^{}a\^{}v}, żeby nadpisać zawartość wpisu tekstem z VIM-a. Teraz mogę oszczędzić kilka uderzeń w klawisze korzystając z {\tt gv} zamiast {\tt ggVG} (po tym jak już wydałem to polecenie).\\ +Zaznaczony obszar staje się kontekstem dla innych komend, więc możesz zrobić dużo więcej niż tylko proste kopiuj-wklej. Możesz wcisnąć {\tt r}, a potem inny znak – na przykład {\tt X}, żeby zamienić wszystkie znaki w zaznaczeniu na {\tt X}. Możesz użyć tego obszaru do wywoływania na nim poleceń (o tym jeszcze nie mówiliśmy). Jest naprawdę sporo możliwości, ale zakończymy w tym miejscu lekcję o zaznaczaniu. \\ +Skoro już i tak to czytasz, to chciałbym przypomnieć, żebyś unikał śmierci przez {\tt CapsLock} i nigdy nie zostawał w trybie wprowadzania bez potrzeby. Nie należy to co prawda do materiału tej lekcji, ale po prostu musiałeś to usłyszeć ponownie. +\subsection{Uzupełnianie} +Nie bój się używać długich nazw i wyrazów, bo VIM ma uzupełnianie. Od razu uprzedzam, że to nie jest {\it intellisense}, ale spokojnie sobie poradzi z kończeniem słów za Ciebie. Wpisz wystarczająco dużo znaków, żeby słowo było rozpoznawalne i (bez wychodzenia z trybu wprowadzania) wciśnij {\tt \^{}n}. Jeżeli słowo, którego szukasz znajduje się w którymkolwiek z aktualnie otwartych plików (lub buforów), to VIM zaproponuje Ci najlepsze dopasowanie. Jeżeli to nie będzie słowo, które chciałeś wpisać, po prostu wciskaj {\tt \^{}n} tak długo, aż znajdziesz pasujące słowo albo skończą Ci się dostępne możliwości. Możesz też wcisnąć {\tt \^{}p}, aby powrócić do poprzedniej podpowiedzi. + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt \^{}n} & W trybie wprowadzania – znajdź następne dopasowanie \\ +{\tt \^{}p} & W trybie wprowadzania – znajdź poprzednie dopasowanie \\ \hline +\end{tabular}\\ + +\noindent +W nowszych wersjach GVIM-a (graficznego [{\it i konsolowego VIM-a od wersji 7.0 – dop. tłum.}]) pojawi się lista, z której będziesz mógł wybrać słowo albo wpisując tak dużo liter, aż będzie to jedyne dopasowanie, albo korzystając z klawiszy strzałek {\it [albo \texttt{\textit{\^{}n}} i \texttt{\textit{\^{}p}} – dop. tłum.]}.\\ +Dostępny jest również mechanizm {\it uzupełniania całych wierszy}. Możesz wcisnąć {\tt \^{}x\^{}l} ({\tt Ctrl+x}, {\tt Ctrl+l} – mała litera {\it L}), aby przejść do specjalnego trybu uzupełniania. Dostępne opcje przeglądasz – podobnie jak w przypadku pojedynczych wyrazów – korzystając z {\tt \^{}n} i {\tt \^{}p} oraz klawiszy strzałek (jeżeli Twój VIM je obsługuje). Ponownie, jeżeli korzystasz z graficznego GVIM-a, pojawi się lista wyboru [{\it i ponownie – do konsolowego VIM-a od wersji 7.0 również się to odnosi – dop. tłum.}]. Bywa, że jest to bardziej przydatne niż kopiowanie w starym stylu.\\ +Istnieje również mniej znany mechanizm uzupełniania nazw plików, dostępny przy pomocy {\tt \^{}x\^{}f}. Zazwyczaj z niego nie korzystam, więc potrzebuję ściągi takiej jak ten tutorial w tych rzadkich przypadkach. Mając pod ręką tryb przeglądania plików i wildmenu zazwyczaj nie potrzebuję uzupełniania nazw plików. + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt \^{}x\^{}l} & W trybie wprowadzania – uzupełnianie wierszy \\ +{\tt \^{}n} & Następne dopasowanie \\ +{\tt \^{}n} & Poprzednie dopasowanie \\ \hline +\end{tabular}\\ + +\noindent +Kiedy trafisz już na odpowiednie dopasowanie, po prostu kontynuuj pisanie. Dowolny klawisz inny niż klawisze wyboru ({\tt $\uparrow$/$\downarrow$/\^{}n/\^{}p}) zostanie zaakceptowany jako nowy tekst, zarówno w trybie normalnym, jak i wprowadzania. Jest to nieco nieintuicyjne, ponieważ jesteś przyzwyczajony do zatwierdzania wyboru enterem lub tabulatorem.\\ +Oprócz wymienionych, jest jeszcze kilka specjalnych komend dostępnych tylko w trybie wprowadzania.\\ +Ponieważ jesteś wyposażony w uzupełnianie słów i wierszy, nie masz powodu, żeby używać krótkich i tajemniczych nazw zmiennych. Długie nazwy, które mają sens, są naprawdę wykonalne i wcale nie powoduja znużenia. +\subsection{Zawsze miej tekst przed oczami} +Są komendy, do przesuwania bieżącej linii. Programistom VIM-a zapewne zaczynało już brakować liter, więc przypięli je do klawisza {\tt z}. + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt zt} & Ustaw bieżący wiersz u góry ekranu \\ +{\tt zz} & Ustaw bieżący wiersz na środku ekranu \\ +{\tt zb} & Ustaw bieżący wiersz na dole ekranu \\ \hline +\end{tabular}\\ + +\noindent +Możesz również ułatwić sobie zerkanie na kod referencyjny, używając podzielonych okien (ang. {\it split windows}). Załóżmy, że piszesz kod w pliku code.cpp i chcesz na chwilę zajrzeć do code.h. + +\begin{tabular}{ l | p{7cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt :split code.h} & Dzieli okno w poziomie i ładuje plik code.h w nowym oknie \\ +{\tt :vsplit code.h} & Dzieli okno w pionie i ładuje plik code.h w nowym oknie \\ \hline +\end{tabular}\\ + +\noindent +Kiedy już podzielisz swoje okna, powinieneś wiedzieć jak się między nimi poruszać. Poniżej znajdziesz krótką listę komend (wszystkie podpięte pod {\tt \^{}w}), które Ci w tym pomogą. Zawsze możesz zamknąć okno (nawet podzielone) wykorzystując jedną z metod przedstawionych w rozdziale {\it WYJDŹ} ({\tt :qq}, {\tt ZZ} itd.). + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt j} lub {\tt $\downarrow$} & Przejdź do okna poniżej \\ +{\tt k} lub {\tt $\uparrow$} & Przejdź do okna powyżej \\ +{\tt h} lub {\tt $\leftarrow$} & Przejdź do okna po lewej \\ +{\tt l} lub {\tt $\rightarrow$} & Przejdź do okna po prawej \\ +{\tt c} & Zamknij bieżące okno \\ +{\tt o} & Zamknij wszystkie okna, poza bieżącym \\ \hline +\end{tabular}\\ + +\noindent +Wszystkie powyższe komendy muszą zostać poprzedzone kombinacją {\tt \^{}c}. Zajrzyj do {\tt :help CTRL-W}, żeby uzyskać więcej informacji na temat korzystania z okien. + +\subsection{Pzeglądarka plików} +VIM pozwala Ci na zarządzanie plikami i katalogami. Spróbuj. Jest dostępny odpowiedni rozdział w systemie pomocy, a więcej informacji możesz uzyskać wciskając i [{\it gdy już jesteś w trybie przeglądarki – dop. tłum.}]. VIM-owa przeglądarka plików to taki {\it Midnight Commander dla ubogich} albo też całkiem niezły zamiennik dla Eksploratora Windows. Jest całkiem poręczny i mocno polecany. Do działania wymagane jest ustawienie {\tt syntax enable} w pliku .vimrc. + +\begin{tabular}{ l | p{10,5cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt o} & Otwórz plik w poziomo podzielonym oknie \\ +{\tt v} & Otwórz plik w pionowo podzielonym oknie \\ +{\tt i} & Przełącza między różnymi trybami wyświetlania listy plików (lista, szczegóły, drzewo) \\ +{\tt s} & Sortuj po kolumnie pod kursorem \\ +{\tt r} & Sortuj w odwrotnej kolejności \\ +{\tt D} & Usuń plik \\ +{\tt d} & Utwórz nowy katalog \\ +{\tt enter} & Otwórz plik w bieżącym oknie \\ +{\tt \%} & Utwórz nowy plik w bieżącym katalogu i otwórz go do edycji (zapyta o nazwę) \\ \hline +\end{tabular}\\ + +\subsection{Zmiana wcięcia} +Zapomnij o używaniu taba. Zbyt wiele narzędzi używa standardowych tabów o szerokości 8 znaków. Jeżeli będziesz używał taba, to nawet jeśli zmienisz ustawienie {\tt tabstop}, wiele programów będzie niepoprawnie wyświetlać i drukować Twój kod. Taby umarły, niech żyją wcięcia!\\ +Polecam więc, żebyś ustawił {\tt tabstop} na wartość 8 w pliku .vimrc, a\\ {\tt shiftwidth} na taką wartość, jaką uznasz za odpowiednią. Nie, tak naprawdę nie polecam, a wymagam od Ciebie, żebyś dodał te dwa polecenia do swojego .vimrc. Teraz. Poczekam. Naprawdę\ldots idź to zrobić\ldots + +\begin{tabular}{ l | p{8,7cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt set tabstop=8} & Używaj standardowych tabów o szerokości 8 znaków \\ +{\tt set shiftwidth=4} & Używaj 4-znakowych wcięć \\ +{\tt set shiftround} & Zmieniaj wcięcie wyrównując do wartości zmiennej {\tt shiftwidth} \\ +{\tt set autoindent} & Automatycznie ustawiaj wcięcie nowej linii \\ \hline +\end{tabular}\\ + +\noindent +Potrzebujesz również włączonej opcji {\tt autoindent}, żebyś nie musiał ręcznie ustawiać wcięcia za każdym razem jak przejdziesz do nowej linii. Autoindent jest na tyle przydatną opcją, że dołączyłem ją w sekcji o niezbędnych ustawieniach w .vimrc. Jeżeli wykonywałeś polecenia z tego tutoriala, powinieneś mieć ją już włączoną. Nie włączenie jej jest głupotą -- naprawdę chcesz ją mieć.\\ +W trybie komend: + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt <} & Przesunięcie w lewo (wymaga polecenia ruchu, działa na całych wierszach)\\ +{\tt >} & Przesunięcie w prawo (wymaga polecenia ruchu, działa na całych wierszach) \\ \hline +\end{tabular}\\ + +\noindent +Jeżeli chcesz przesunąć cały akapit w lewo, to {\tt <\}} jest komendą, której potrzebujesz. Żeby przesunąć 3 wiersze w prawo, użyj {\tt 3>>}. Komendy wcięcia są zgodne ze standardowym wzorem komend VIM-a (dlatego nazywa się on standardowym wzorem). Nie używają buforów.\\ +W trybie wprowadzania/nadpisywania: + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt \^{}t} & Zwiększ wcięcie \\ +{\tt \^{}d} & Zmniejsz wcięcie \\ \hline +\end{tabular} +\subsection{Sprawdzanie pisowni} +VIM może również sprawdzać Twoją pisownię. Wprowadź komendę\\{\tt :set spell}, żeby włączyć sprawdzanie pisowni. Możesz również zdefiniować słownik i inne opcje, ale w tym celu odsyłam Cię do {\tt :help spell}.\\ +Nie polecam włączenia tej opcji na stałe. Wiele plików, które będziesz edytował będzie zawierało słowa, których nie znajdziesz w słowniku i może to być nieco denerwujące. Osobiście preferuję przełączanie tej opcji przy pomocy {\tt :set spell} i {\tt :set nospell}.\\ +Bardziej dociekliwi mogą nauczyć się przełączać to ustawienie przy pomocy specjalnych skryptów uruchamianych w momencie ładowania pliku. Reszta może spokojnie to pominąć.\\ +\subsection{Drobne podpowiedzi} +Istnieją pewne komendy pokazujące informacje w linii stanu lub w przewijalnym widoku. Kiedy potrzebujesz przypomnienia, ale nie chcesz przechodzić do innej części kodu, możesz z nich skorzystać. + +\begin{tabular}{ l | p{10,3cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt [i} & Pokazuje pierwszy wiersz, w którym pojawiło się słowo pod kursorem \\ +{\tt [I} & Pokazuje wszystkie wiersze, w których pojawiło się słowo pod kursorem \\ +{\tt :g/wzór/} & Pokazuje wszystkie wiersze pasujące do wzoru (wyrażenia regularnego)\\ \hline +\end{tabular} +\subsection{Filtrowanie przy pomocy powłoki} +Jeżeli pracowałeś już z wierszem poleceń, to możliwe, że wiesz jak korzystać z takich programów jak {\it sort} czy {\it grep}, a być może także jak wykonywać różne zadania przy pomocy {\it perla} czy {\it awk}. Wszystkie te programy to swego rodzaju filtry. Wczytują ze standardowego wejścia i zwracają wynik na standardowe wyjście.\\ +Kiedy jesteś w VIM-ie, możesz robić dokładnie te same rzeczy. Niewątpliwie uciążliwe jest zapisanie fragmentu, który chcesz posortować, do pliku, przejście do linii komend, posortowanie tego pliku i załadowanie go z powrotem w miejsce nieposortowanych danych.\\ +Co musisz wiedzieć, to to, że cała ta praca jest zbędna. Jeżeli chcesz posortować akapit, wystarczy że ustawisz kursor na jego początku i wciśniesz {\tt !\}sort}, a magia się dokona.\\ +VIM jest napisany tak, że używa filtrów bezpośrednio. Jest to przydatne nie tylko ze względu na mnogość przydatnych filtrów dostarczanych razem z systemami uniksopodobnymi, ale także dlatego, że możesz w prosty sposób pisać swoje własne. Każdy program działający jak filtr, który napiszesz, będzie częścią zarówno Twojego edytora jak i powłoki systemowej. Ma to ogromny wpływ na sposób, w jaki edytujesz pliki. Jest to szczególnie ekscytujące, jeżeli już korzystasz z linii komend jak guru. + +\begin{tabular}{ l | p{9,3cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt !!polecenie} & Przefiltruj tylko bieżący wiersz \\ +{\tt !\}polecenie} & Przefiltruj linie od bieżącej do końca akapitu \\ +{\tt !Gpolecenie} & Przefiltruj linie od bieżącej do końca pliku \\ +{\tt :\%!polecenie} & Przefiltruj cały plik \\ \hline +\end{tabular} +\subsection{Poprawianie formatowania kodu} +Możesz zmieniać formatowanie kodu na kilka różnych sposobów. Jeden z nich to filtr powłoki: + +\begin{tabular}{ l | p{10,4cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt \%!astyle} & Przeformatuj kod korzystając z programu astyle (Niezły program do poprawy formatowania)\\ +{\tt \%!indent} & Przeformatuj kod korzystając z programu indent (Też dobry program, choć trochę starszy) \\ \hline +\end{tabular}\newpage + +\noindent +Innym sposobem jest komenda {\tt gq}, która ponownie wykonuje zawijanie wierszy i potrafi poprawnie zawijać komentarze. + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt gqq} & Popraw zawijanie bieżącego wiersza (podwójny skok!)\\ +{\tt gqj} & Popraw zawijanie bieżącego i kolejnego wiersza \\ +{\tt gq\}} & Popraw zawijanie od bieżącego wiersza do końca akapitu \\ \hline +\end{tabular}\\ + +\noindent +Możesz również zamienić znaki tabulacji na spacje, żeby u każdego wcięcia wyświetlały się tak samo. Aby to zrobić, ustaw zmienną {\tt tabstop} na odpowiedni poziom wcięcia, włącz ustawienie {\tt expandtab} i wykonaj polecenie {\tt :retab}. Byłoby to zdecydowanie za dużo roboty, gdybym nie miał ustawionych {\tt tabstop} i {\tt expandtab} w domyślnej konfiguracji. Zazwyczaj ustawiam {\tt tabstop}, wykonuję {\tt :retab} i zapisuję plik. Jest to ciąg poleceń, który mogę zmapować pod jakiś klawisz lub zapisać jako makro.\\ +Możesz również sprawić, że edytor będzie zawijał długie linie na bieżąco, zachowując poziom wcięć. Wszystko to ustawiasz przy pomocy opcji {\tt linebreak}, {\tt textwidth} i {\tt autoindent}, o których możesz poczytać w systemie pomocy.\\ +\subsection{Tryb szybkich po prawej (QuickFix) Twoim przyjacielem} +VIM potrafi uruchomić Twój plik Makefile i poprowadzić Cię przez wszystkie zmienne po kolei. Jeżeli korzystasz z testów jednostkowych jako części procesu budowania, a ich wynik zwracany jest w kompatybilnym formacie, to zostaniesz poprowadzony przez błędnie wykonane testy w taki sposób, jakby to były błędy kompilacji. Podobnie rzecz się ma z wszelkimi narzędziami do sprawdzania stylu, zakładając że zwracają wynik w odpowiednim formacie.\\ +Jeżeli stosujesz technikę rozwoju sterowanego testami (Test Driven Development), to jest to krytyczna funkcja. Mając do dyspozycji tryb {\it QuickFix}, szybko wpadniesz w odpowiedni rytm pracy. Możesz nawet przypisać komendę {\tt :make} pod jeden z klawiszy (patrz: {\tt :help map}), żebyś nie musiał jej ciągle wpisywać. VIM jest pod tym względem dość elastyczny. W osobnej publikacji przedstawię swoje ustawienia VIM-a, nakierowane pod kątem TDD.\\ +Podstawowe komendy trybu QuickFix: + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt :make} & Wykonaj plik Makefile określony przez zmienną makefile \\ +{\tt :cw} & Pokaż okno z błędami kompilacji, jeżeli jakieś wystąpiły \\ +{\tt :cn} & Przejdź do następnego błędu kompilacji \\ +{\tt :cp} & Przejdź do poprzedniego błędu kompilacji \\ \hline +\end{tabular}\\ + +\noindent +Jak zwykle, odsyłam do {\tt :help quickfix} po więcej informacji na temat tego trybu. +\subsection{Dostęp do stron podręcznika (man)} +W rozdziale poświęconym plikowi .vimrc zalecałem włączenie funkcji {\tt Man}. Ponieważ wykonywałeś moje polecenia, masz teraz dostęp do stron podręcznika z poziomu VIM-a. + +{\tt :Man 5 crontab} otworzy stronę dotyczącą tabeli {\tt cron} w dzielonym oknie. Kursor będzie znajdował się w oknie pomocy, po którym będziesz mógł się poruszać tak jak w przypadku tagów: {\tt \^{}]}, żeby przejść do danego taga, {\tt \^{}t} - żeby powrócić. Kiedy skończysz korzystać z podręcznika, po prostu zamknij okno przez {\tt :q} bądź {\tt ZZ}.\\ +Jeżeli szukasz strony podręcznika na temat czegoś w pliku, który edytujesz, nie musisz wciskać dwukropka i wpisywać słowa {\tt Man}. Wystarczy, że wciśniesz znak lidera ({\tt :help mapleader}) - domyślnie {\tt $\backslash$} - a następnie wielką literę {\it K}, żeby VIM znalazł odpowiednią stronę podręcznika i wyświetlił ją w nowym oknie. Oczywiście jeżeli zmienisz znak lidera, będziesz musiał odpowiednio dostosować poniższe komendy. Funkcja ta jest bardzo przydatna, jeżeli piszesz skrypty powłoki lub korzystasz z API języka C systemu Linux (lub Unix).\\ + +\begin{tabular}{ l | p{9,7cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt :Man temat} & Wyświetl stronę podręcznika dotyczącą tematu \\ +{\tt $\backslash$K} & Wyświetl stronę podręcznika dla słowa pod kursorem \\ \hline +\end{tabular}\\ + +\noindent +Możesz poprawić przydatność tej funkcji upewniając się, że masz zainstalowane strony podręcznika dla wszystkich narzędzi i bibliotek, z których korzystasz. Albo przynajmniej prosząc administratora swojego systemu, żeby to zrobił. Jeżeli programujesz w perlu i nie masz zainstalowanych odpowiednich stron podręcznika, ta funkcja będzie dla Ciebie bezużyteczna. \\ +\subsection{Ctags pozwoli Ci na profesjonalną nawigację} +Z całego serca polecam exuberant ctags jako program tagujący, dla niemal każdego języka. Potrafi on szybko przeskanować Twój kod i utworzyć plik {\it tagów}, który mówi VIM-owi wszystko, czego ten potrzebuje, żeby znaleźć odpowiednie symbole w kodzie. Plik tagów zawiera nazwy plików i wyrażenia regularne pozwalające znaleźć odpowiednią linię. Naprawdę nieźle sobie radzi. + +\begin{tabular}{ l | p{9,5cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt !ctags -R *} & Uruchamia ctags (najlepiej dodać to do pliku Makefile) \\ +{\tt \^{}]} & Przejdź do definicji terminu znajdującego się pod kursorem (klasy/metody/zmiennej...)\\ +{\tt \^{}t} & Powróć do poprzedniego miejsca\\ \hline +\end{tabular} +\subsection{Zakładki} +VIM pozwala na ustawienie zakładki na wierszu i skakanie od jednej zakładki, do drugiej. + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt mx} & Utwórz zakładkę x w bieżącym wierszu\\ +{\tt 'x} & Skocz do zakładki x\\ \hline +\end{tabular}\\ + +\noindent +Możesz użyć dowolnej litery jako nazwy zakładki, ale jest różnica między wielkimi i małymi literami.\\ +\begin{itemize} + \item Małe litery ustawiają zakładkę dla danego pliku, tak że {\tt 'a} w jednym pliku może Cię przenieść w zupełnie inne miejsce niż w innym. + \item Wielkie litery ustawiają zakładkę globalną, więc {\tt 'A} przeniesie Cię do pliku i linii, w którym daną zakładkę utworzyłeś. Jest to bardzo przydatne, ale czasem może nie być do końca tym, czego byś chciał, ponieważ plik z zakładką jest ładowany w bieżącym oknie. +\end{itemize} +\subsection{Wklejanie w trybie wstawiania} +W trybie wstawiania nie jesteś ograniczony jedynie do pisania i uzupełniania wierszy. Są też inne komendy, a jedną z nich jest {\tt \^{}r}, która wkleja zawartość rejestru w miejscu kursora.\\ +Załóżmy, że usunąłeś jakieś słowo - powiedzmy {\it kanarek} - i piszesz właśnie w zupełnie innym miejscu dokumentu. Wystarczy teraz, że wciśniesz {\tt \^{}r}, a następnie {\tt \"{}} (cudzysłów, nazwa domyślnego rejestru), żeby wkleić słowo {\it kanarek} w danym miejscu i kontynuować pisanie, pozostając w trybie wstawiania.\\ +Jest to szczególnie przydatne przy operacjach typu {\tt cw}, ponieważ komenda zmiany usuwa bieżące słowo (ładując je do rejestru) i przełącza w tryb wprowadzania. Załóżmy więc, że mój kursor jest umieszczony na słowie {\it kanarek}. Wykonuję następujące operacje: + +\begin{tabular}{ l | p{10,5cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt cw} & Usuwa bieżące słowo, umieszcza je w rejestrze {\tt \"{}} i przełącza VIM-a w tryb wstawiania \\ +{\tt } & Wprowadza tekst (jesteśmy w trybie wstawiania). Ten tekst to początek taga HTML oznaczającego tekst wytłuszczony\\ +{\tt \^{}r} & Rozpoczyna wklejanie-w-trybie-wprowadzania \\ +{\tt \"{}} & Wkleja zawartość domyślnego rejestru ({\it kanarek}) w aktualnym położeniu kursora\\ +{\tt } & Wprowadza tag zamykający\\ +{\tt Escape} & Powraca do trybu komend \\ +{\tt u} & Usuwa tag {\tt } ze słowa {\it kanarek}!\\ \hline +\end{tabular}\\ + +\noindent +Uważaj, bo {\tt .} nie wie o tym, że użyłeś komendy {\tt \^{}r}, więc jeśli przejdziesz do kolejnego słowa i wciśniesz kropkę, to zostanie ono zamienione na słowo {\it kanarek} objęte w tag wytłuszczenia. Jeżeli chcesz wytłuszczać wiele słów, to powinieneś nauczyć się nagrywać i odtwarzać makra - {\tt :help q} +\subsection{Skracaj!} +Jeden z najprostszych sposobów, w jaki możesz dostosować swój edytor, to skróty. Dla przykładu, jedną z najczęściej wpisywanych błędnie linijek w języku Python jest ta słynna inwokacja funkcji {\tt main}: + +{\tt if \_\_name\_\_ == \"{}\_\_main\_\_\"{}:} + +\noindent +Chciałbym, żeby po wpisaniu słowa {\tt pymain}, edytor wprowadzał tę inwokację za mnie. Banalne: + +{\tt :ab pymain if \_\_name\_\_ = \"{}\_\_main\_\_\"{}:} + +\noindent +Teraz za każdym razem, gdy wpiszę dowolny znak spoza alfabetu po słowie pymain, zostanie ono automatycznie rozwinięte. Wszystko czego VIM-owi potrzeba to komenda ab i cały wyraz w trybie wprowdzania. Rozwinięcie jest natychmiastowe i automatyczne, nie trzeba wciskać żadnej kombinacji klawiszy. W rezultacie VIM będzie rozwijał wyrazy nawet wtedy, gdy tego nie chcesz. Za każdym razem, gdy wpiszę pymain, otrzymuję powyższe rozwinięcie; nawet jeżeli wpisałem to przez przypadek. Właściwie muszę intencjonalnie pisać to słowo z błędem, wychodzić z trybu wprowadzania i wracać, żeby je poprawić, bo nie mam innej możliwości wpisania tego słowa.\\ +Mogę dodać to rozwinięcie do mojego .vimrc, o ile oczywiście pominę początkowy dwukropek. Mam w swoim .vimrc już kilka takich rozwinięć, ponieważ dobieram je bardzo starannie.\\ +Zauważyłem, że czasem wpisuję {\it teh} zamiast {\it the}. Jest to proste to naprawienia: + +{\tt :ab teh the} + +\noindent +Nigdy nie piszę {\it teh} specjalnie, więc jest to całkiem niezły kandydat do {\it skrócenia}.\\ +Dodając własne skróty dobrze je przemyśl, żebyś nie otrzymywał niechcianych rozwinięć. Jednak dobrze jest uwzględnić częste literówki czy dłuższe fragmenty kodu, które w przeciwnym razie musiałbyś wpisywać ręcznie. +\subsection{Nagrywaj i odtwarzaj makra} +W systemie pomocy nazywa się to {\it złożonym powtórzeniem} (ang. {\it complex-repeat}).\\ +Do trybu nagrywania makra przełączasz się wciskając {\tt q}, a następnie nazwę rejestru, do którego makro ma zostać zapisane. Możesz użyć dowolnej litery alfabetu (małej lub wielkiej) oraz cyfr. Oczywiście możesz mieć wszystkie 26 mały liter, 26 wielkich oraz 10 cyfr przypisanych jednocześnie do różnych makr, jeśli taka jest Twoja wola.\\ +Każde klawisz, który naciśniesz zostanie nagrany, aż do ponownego naciśnięcia {\tt q}.\\ +Żeby odtworzyć makro, wciśnij {\tt @} i nazwę rejestru.\\ +Po tym jak odtworzysz dane makro, komenda u będzie je widziała jako jedną operację. Jest to bardzo przydatne, ponieważ makro może wykonywać zmiany w wielu wierszach w całym pliku.\\ +VIM zapamiętuje ostatnie makro, które odtworzyłeś i pozwala Ci na powtórzenie go przy wykorzystaniu {\it podwójnego skoku}. W tym wypadku będzie to {\tt @@}.\\ +Komenda {\tt .} również postrzega makro jako jedną operację. Jest to świetne, bo powyższa lekcja staje się dużo bardziej przydatna. Działa to jakoś tak: + +\begin{tabular}{ l | p{10,6cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt qa} & Rozpoczyna nagrywanie makra {\it a}\\ +{\tt cw} & Usuwa bieżące słowo, umieszcza je w rejestrze \"{} i przełącza VIM-a w tryb wstawiania\\ +{\tt } & Wprowadza tekst (jesteśmy w trybie wstawiania). Ten tekst to początek taga HTML oznaczającego tekst wytłuszczony\\ +{\tt \^{}r} & Rozpoczyna wklejanie-w-trybie-wprowadzania\\ +{\tt \"{}} & Wkleja zawartość domyślnego rejestru ({\it kanarek}) w aktualnym położeniu kursora \\ +{\tt } & Wprowadza tag zamykający \\ +{\tt Escape} & Powraca do trybu komend \\ +{\tt q} & Kończy nagrywanie makra\\ +{\tt W} & Przechodzi do kolejnego słowa \\ +{\tt @@} & Odtwarza makro, obejmując słowo w tag wytłuszczenia \\ +{\tt W} & Przechodzi do kolejnego słowa\\ +{\tt .} & Ponownie odtwarza makro\\ \hline +\end{tabular}\\ + +\noindent +Makro, które nagrałeś, to po prostu tekst w rejestrze. Możesz je wkleić do dokumentu, usprawnić jego działanie, skopiować z powrotem do rejestru, etc. \\Makra to niezły sposób na usprawnienie skomplikowanych zmian.\\ +Wpisz {\tt :help q}, żeby dowiedzieć się więcej o używaniu makr. Nie powiedziałem wszystkiego. +\subsection{Mapowanie klawiszy} +Wszystko, co możesz zrobić ręcznie lub przy pomocy makra, możesz również zmapować pod jakiś klawisz. Mapowanie po prostu podpina makro pod dany klawisz. Na przykład: + +{\tt \"{}} Przełączanie pomiędzy plikami na długiej liście {\tt map :prev map :next} + +\noindent +Poczytaj więcej o mapowaniu wpisując {\tt :help map}. +\subsection{Kolory i inne takie} +VIM-a ma niesamowite możliwości dostosowania, włącznie z kolorami, których używa. Niektórzy udostępniają swoje schematy kolorów w Internecie, a kilka jest również dostarczanych wraz ze standardową dystrybucją. Ten, który najczęściej spotykasz to zapewne {\it default} (ang. {\it domyślny}). Jeżeli korzystasz z osobnego schematu kolorów, możesz go podejrzeć korzystając z komendy: + +{\tt :echo g:colors\_name} + +\noindent +Wypróbuj istniejące schematy, takie jak {\it delek, darkblue, desert, koehler, elflord, peachpuff}, czy {\it slate}. Zawsze możesz powrócić do domyślnego albo po prostu opuścić edytor i włączyć go ponownie. Komenda, której potrzebujesz to: + +{\tt :colorscheme nazwa\_schematu} + +\noindent +Możesz przejrzeć dostępne schematy w trybie przeglądarki wpisując: + +{\tt :e \$VIM/vim73/colors} + +\noindent +(Zakładając, że używasz VIM-a 7.3. Możliwe, że będziesz musiał dostosować tę komendę do swojej wersji.)\\ +Schematy kolorów zbudowane są z komend, które ustawiają poszczególne elementy, takie jak kolor tekstu czy tła linii stanu. Możesz się naprawdę wiele nauczyć analizując jeden czy dwa takie schematy.\\ +Komendy kolorów zaczynają się od {\tt hi} (skrót od highlight), po którym następuje nazwa elementu, który chcesz pokolorować (zwana nazwą grupy), oraz łańcuchy znaków odpowiadająće kolorom do użycia odpowiednio w: zwykłym terminalu (spytaj ojca) - {\it term}, kolorowym terminalu - {\it cterm} i wreszcie w graficznym interfejsie - {\it gui}.\\ +Poniżej znajdziesz kilka ustawień, które lubię w gvimie: + +{\tt hi LineNr guibg=lightgray guifg=black} + +{\tt hi StatusLine guifg=yellow guifg=darkblue} + +{\tt hi NonText guibg=darkgray hi ToDo guifg=DarkRed} + +\noindent +Kolorują one obszar, który znajduje się poza tekstem, kolumnę numerów linii po lewej stronie (jeśli wykonasz {\tt set nu}) i koloruje aktywny pasek stanu odmiennie od nieaktywnego.\\ +Po więcej informacji na temat schematów kolorów odsyłam do wbudowanej pomocy ({\tt :help hi}) lub do jakiegoś innego, bardziej rozbudowanego przewodnika po VIM-ie. +\subsection{Wykorzystywanie ścieżki (ang. {\it path})} +Istnieje specjalna zmienna, zwana {\tt path}, która pomoże Ci odnaleźć pliki, do których odwołują się aktualnie przez Ciebie edytowane. Jest to szczególnie przydatne, gdy piszesz program w języku C i skierujesz zmienną path na katalogi {\tt /usr/include/*}.\\ +Wartość, którą przyjmuje ta zmienna, to lista ścieżek rozdzielonych przecinkami, w których VIM powinien szukać plików. Pozwala to na wskazanie standardowych katalogów plików dołączanych, jak również plików Twojego projektu czy dowolnych innych, które uznasz za przydatne.\\ +Żeby skorzystać z tej funkcji, umieść kursor na nazwie pliku i (w trybie komend) wciśnij {\tt gf} lub {\tt\^{}wf}. Plik zostanie załadowany w aktualnym oknie. + +\begin{tabular}{ p{4cm} | p{8,2cm} } +{\bf Polecenie} & {\bf Rezultat} \\ \hline +{\tt set path=., .*, /usr/include/*, /usr/share/*} & Prawdopodobnie nadmiarowe, ale ustawia zmienną path na przeszukiwanie praktycznie wszystkiego - może zająć trochę czasu. \\ +{\tt gf} & Przejdź do pliku (ang. {\it Goto File}): otwiera plik, którego nazwa znajduje się pod kursorem. \\ +{\tt \^{}wf} & Otwórz w oknie (ang. {\it Window File}): podobne do {\tt gf} z tym, że otwiera plik w nowym oknie.\\ +{\tt :e\#} & Powraca do poprzedniego pliku\\ \hline +\end{tabular}\\ + +\noindent +Uważam, że otwieranie w nowym oknie jest generalnie bardziej przydatne, ale jednocześnie {\tt gf} jest na tyle łatwiejsze do wpisania, że używam go częściej. Chciałbym, żeby kolejne edytowane pliki były odkładane na stosie, żeby można było do nich powracać przy pomocy {\tt \^{}t}, ale niestety tak nie jest. Można to obejść ustawiając zakładkę nazwaną wielką literą, żeby można było do niej powrócić z innego pliku. Wiem, że brzmi to nieco okropnie, bo takie jest, ale przynajmniej działa.\\ +Mimo wszystko, programiście C/C++, {tt $\backslash$K} w połączeniu z {\tt \^{}wf} pozwala na całkiem niezłe poruszanie się między plikami, a zakładki są przydatne do przechodzenia z/do plików nagłówkowych i innych.\\ +Zmienna {\tt path} jest również wykorzystywana przez mechanizm uzupełniania ({\tt \^{}n}) do znajdywania plików, w których szuka dopełnień.\newpage +\pagestyle{empty} +\AddToShipoutPicture*{\put(0,0){\includegraphics{/home/marcin/reklama4.jpg}}}% +\phantom{Invisible, but important} +\end{document} diff --git a/Use Vim Like A Pro.tex b/Use Vim Like A Pro.tex new file mode 100644 index 0000000..7182b40 --- /dev/null +++ b/Use Vim Like A Pro.tex @@ -0,0 +1,668 @@ +%%% Use\ Vim\ Like\ A\ Pro.tex --- +\documentclass[a4paper, 12pt]{article} + +\usepackage{amsfonts} +\usepackage{amssymb} +\usepackage[utf8]{inputenc} +\usepackage{times} +\usepackage{graphicx} +\usepackage{eso-pic} +\usepackage{hyperref} + +\hypersetup{ + colorlinks=true, + linkcolor=black, + pdfauthor={Marcin Karpezo}, + pdftitle={Use Vim Like A Pro}, + urlcolor=blue +} +\title{Use Vim Like A Pro} +\author{Tim Ottinger} +\date{15 December 2010} +\newcommand{\myline}{\rule{\linewidth}{0.4mm}} + +\begin{document} +\section{Introduction} +\label{"Introduction"} +\subsection{Why Bother? (reasons)} +\label{"Why Bother? (reasons)"} +There are many other editors, some being quite excellent. There is no reason why you cannot use one of them, however, there are some advantages in using VIM. Likewise none of these reasons are unique to VIM.\\ +\begin{itemize} +\item With the sudden rise in Unix use (Linux and Mac OS X, in particular) the text editor known as VIM ("vi improved") has become ubiquitous +\item Vim has a small footprint in RAM and on the CPU. A given system can support a great many VIM users at once. +\item Vim has a lot of "superpowers", which make editing quite efficient. +\item Vim has "geek appeal". +\item Vim has a very active user/developer community. It always has. +\end{itemize} + +\subsection{Why Write This Tutorial (approach)} +\label{"Why Write This Tutorial (approach)"} +There are other tutorials that are very good, and Google will help you find them all. Maybe the greatest need in this world is not for another vim tutorial, but this one is mine. \\ +I have taken a slighltly different approach. I think that there is a certain mental model that makes mastering VIM much easier. Also, I include habits that make VIM your friend. I don't know who else does this. \\ +I've agonized and organized (and reorganized, and reorganized) the tutorial for top-to-bottom learning, with the goal that anyone who manages to emerge at the other end of this tutorial will have professional-grade editing skills, probably better than many of their experienced colleagues.\\ +While I advise patience and deep memory, I think this is one of the fastest ways to improve your use of vim, and a pretty good way to start using vim from scratch. I wrote this for the moderately impatient developer.\\ +I decided not to try to write a for-sale book, because anyone should be able to use vim like a pro, any time and place they choose, and without paying me any kind of "vim toll".\\ +\subsection{How should one use the tutorial? (usage)} +\label{"How should one use the tutorial? (usage)"} +Look at each numbered item in this page as a separate lesson, and spend a little time with it before moving onward. Maybe spend a day with each bit of knowledge, and maybe a several days when the lesson is particularly meaty.\\ +Consider doing a few lessons a week. Don't be in a hurry. Don't rush your brain so that each time you learn something new, you lose something old. The tutorial will last as long as you need it. You have permission to breathe.\\ +You can't learn vim without using vim, so you should have some text files (preferably open source program code) to work with. It is better yet if you are using vim at work. It also helps if you work with a partner who is also reading this tutorial, so that you can reinforce each other.\\ +\subsection{What can I do with this tutorial? (license)} +\label{"What can I do with this tutorial? (license)"} +This work is \href{http://creativecommons.org/licenses/by/3.0/}{licensed under a Creative Commons Attribution 3.0 License}. Copy it, share it, paste it into your web page. Don't pretend it is your own stuff, and please give me some attribution. As a courtesy, if you find it worth distributing, I wouldn't mind getting a copy or a link. \href{mailto:tottinge@gmail.com}{Just let me know}. +\section{The Tutorial} +\label{"The Tutorial"} +\subsection{A little reassurance first} +\label{"A little reassurance first"} +Nobody knows all of VIM. There is enough in VIM's command system to keep thousands of human beings all using it in their own idiosyncratic way. Luckily, you don't have to know it all. You only need to know how to do your own work. \\ +Because there is so much capability in this program, you will be learning new tricks as long as you continue to use it. The secret is to not settle for crummy ways of doing work.\\ +VIM has word completion, and undo, and shortcuts, and abbreviations, and keyboard customization, and macros, and scripts. You can turn this into {\bf your} editor for {\bf your} environment. That's cool, but it's also reassuring to know that you can probably be much more productive than you are without touching any of those advanced features.\\ +As Bram Moolenaar (VIM's primary author) says, the best way to learn VIM is to use it and ask questions. This little tutorial is full of questions you might not have thought to ask. That's the main value I can give you. \\ +Vim has a built-in tutorial. You might want to try it, especially if you don't like my tutorial. All you have to do is type {\tt vimtutor} at the command line. It is a very nice tutorial, and is rather complete (compared to mine, which is fairly nice but not very complete at all).\\ +Finally, please consider GVIM. It will make your experience much more pleasant. If you only have VIM, then you can still use it and learn, but GVIM has a much nicer look, lets you use your mouse and scroll wheel, and has menus and icons for those of you who are used to such things.\\ +\subsection{Modality} +\label{"Modality"} +The original vi was invented back when "green screen" ascii terminals were the UI innovation of the day (ask your dad about {\it ascii terminals}). There weren't so many Shift-like keys ({\tt Shift}, {\tt Alt}, {\tt Ctrl}, {\tt Windows}, {\tt fn}) and there was no such thing as a pointing device. Let's pretend that there was only a {\tt Ctrl} key and a {\tt Shift} key, whether it's true or not.\\ +Programming (and all other computer use) was done with your eyes on the screen and two hands on the keyboard. Vi made it possible to do so quickly, because vi is a bit like a video game, where any little gesture on the keyboard causes something to happen.\\ +If you are using vim and pressing keys causes either cool or unfortunate things to happen, you know you are in the command mode, which is the default state of the editor. Commands are assigned to the ordinary everyday keys like {\tt p} and {\tt y} and {\tt g}, not chords like {\tt Control-Alt-Shift-Escape}.\\ +VIM has combinations and sequences to get the special power-ups like navigating between functions in separate files and reformatting entire lists in the middle of a document, code completion, abbreviations, templates and the like but that is for later.\\ +There has to also be a way to type text into a document, but most of the keys already have special meanings! The only reasonable option was for the developers to create an {\it insert mode} which would make the {\tt a} key type an {\tt a} character, just like a typewriter (ask your dad what a {\it typewriter} is). This is called {\it insert mode}. Not much happens in insert mode except normal, old, boring typing. You only want to use insert mode when you must do typing, but all the cool stuff happens in the normal (control) mode.\\ +You will learn many convenient ways to get into insert mode, but for now you should know that the way out of insert mode, back to the {\it video-game-like} control mode, is to press the {\tt Escape} key.\\ +Understanding that you have basically two modes of operation will make your stay in VIM less confusing, and starts you on your way to VIM guruhood. +\subsection{Know the VIM command pattern} +\label{"Know the VIM command pattern"} +Most of the time you will either get an immediate result from a keystroke, or you will type a command and a movement command (often repeating the same keystroke: the {\it double-jump}). When you start to learn the other bits and pieces (registers, repeats, etc) then you might think vim is inconsistent, and this is not so. The command pattern is rather consistent, but some parts are optional. + +\begin{itemize} +\item {\bf Register name} (optional, with default cut/paste register used if not otherwise specified) +\item {\bf Repeats} (optional): 13 +\item {\bf Operation}: {\tt y} (for {\it yank}) +\item {\bf Movement} (depending on the operation): {\tt yy} (repeated to take current line, a convention used in vi) +\end{itemize} + +VIM commands work with the pattern shown above. There are some commands that don't use register and some that don't take movement, but for the most part this is the way it goes.\\ +A {\bf register} is essencially a cut-n-paste buffer. In most editors you get only one. In VIM you have too many, but you don't have to use them, so don't worry about it untl you get to the lesson on buffers.\\ +A {\bf repeat} is a number of times you want to do something. If you don't type in a number, the default is 1. +An {\bf operation} is a keystroke that tells VIM to do something. These are mostly normal keypresses, and most operators do not require shifts or alts or controls.\\ +{\bf Movement} is a command that takes the cursor somewhere. There are a lot of them, because there are lots of ways you need to move. Don't panic, though, because you can use the arrow keys if you really have to. There is a whole section of this tutor on moving around.\\ +Lets try an example to clarify how the pattern works. If I want to copy 13 lines into my copy/paste register, I can skip specifying a register name, type {\tt 13} for a repeat count, press {\tt y} for yank, and then press one more {\tt y} as a movement command (meaning current line). That yanks 13 lines into the default cut-n-paste register. If I press {\tt p} (choosing to use no register name and no repeat, recognizing that put has no movement command), then those lines are pasted back into my document just after my current line.\\ +If you know this pattern, then you will know how to leverage everything else you learn about vi. Learn all the convenient ways to move, and you will know how to cut, paste, reformat, shift, and many other things you want to do. +\subsection{GET OUT!} +\label{"GET OUT!"} +You should be able to get out of a VIM session once you are in it. There are a few ways to do so. Try these: + +\begin{tabular}{ l | p{8cm} } + {\bf Command} & {\bf Result} \\ \hline + {\tt :q} & Quit the current window (or editor if you're out of windows) if there are no unsaved changes\\ + {\tt :q!} & Quit the current window even if there are unsaved changes\\ + {\tt :qa} & Quit all windows unless there are unsaved changes\\ + {\tt :qa!} & Quit all windows even if there are unsaved changes\\ + {\tt :wq} & Save changes and quit the current window\\ + {\tt ZZ} & Save changes and quit current window\\ \hline +\end{tabular}\\ + +When you type a colon, the cursor drops to the lower left corner of the screen. Later you will know why. For now, it's enough to know that it is supposed to do that, and that these {\tt :q} commands will work. Notice that there is no {\tt :} in front of {\tt ZZ}.\\ +If you can't get out of VIM, you should check that {\tt Caps Lock} is OFF, and press the {\tt Escape} button. If it feels good, press it a couple of times. If it beeps, you know that you've escaped enough. Then these exit commands should work.\\ +\subsection{Mnemonics} +\label{"Mnemonics"} +Not all commands are mnemonic. They tried, but there are more than 26 things you might want to do in a text editor, and the distribution of letters means that not that many words start with a {\tt q} and happen to be meaningful in editing. However, many commands are mnemonic. There are commands for moving Forward, Back, a Word at a time, etc.\\ +A great many are mnemonic if you know the jargon. Since {\it copy} and {\it cut} both start with {\it c}, we have the vernacular of {\it yank} (for copy), {\it delete} (for cut), and {\it put} (for paste). {\tt Y}, {\tt D}, {\tt P}. It seems a little funky but it is possible to remember these. Remember, eventually it becomes muscle memory, but the authors of VI and VIM tried not to be arbitrary when it was totally up to them. Sometimes, there wasn't much of an option. +\subsection{Invocation} +\label{"Invocation"} +Now that you know how to get out of VIM, maybe it's time to learn how to get into VIM. We typically start VIM from the command line, though you may have menues or other ways.\\ +There are a few ways you can start VIM: + + +\begin{tabular}{ l | p{8cm} } + {\bf Command} & {\bf Result} \\ \hline + {\tt vim} & Start with an empty window \\ + {\tt vim file.txt} & Start with an file.txt loaded and ready to edit \\ + {\tt vim +23 file.txt} & Start with an file.txt loaded and ready to edit at line 23\\ + {\tt vimtutor} & Start in tutorial mode - this is a good idea\\ + {\tt vimdiff oldfile.txt newfile.txt} & Start VIM as a really fancy code merge tool\\ + {\tt vimdiff .} & Start VIM as a file explorer\\ \hline +\end{tabular}\\ + +There is more, not shown. For now, knowing these will help you to get started. Do try out the {\tt vimtutor} and the {\tt vimdiff}. Some of these won't work until you set up a .vimrc, but that is explained later.\\ +If you type {\tt gvim} instead of vim then you will get the gee-whiz, cool, gui version of VIM (if it's installed). It has some extra powers. You'll typically like it better than the plain VIM. It is like VIM with chocolate icing. Everything we say about VIM here is also true of GVIM, so you can use the same tutorial with either.\\ +You don't have to edit one file at a time. You can start (g)vim with multiple filename arguments. When you do, there are a few options you can pass to get some fun additional effects. Of course, these are more fun after you learn how to work with split windows, so you can refer back to it later. + + +\begin{tabular}{ l | p{8cm} } + {\bf Parameter} & {\bf Result} \\ \hline + {\tt -o} & Open multiple files in horizontally tiled windows\\ + {\tt -O} & Open multiple files in vertically tiled windows\\ + {\tt -p} & Open multiple files in separate tabs (I hate this)\\ \hline +\end{tabular}\\ +\subsection{Move by context, not position} +\label{"Move by context, not position"} +The poor soul who is using VIM for the first time will be found pressing up and down arrows and executing key repeats, moving horribly inefficiently through any body of code. He will be scrolling or paging (btw: {\tt \^{}f} moves forward one page, {\tt \^{}b} moves backward one page) and searching with his poor eyeballs through piles of code. This poor soul is slow and clueless, and probably considers VIM to be a really bad version of windows notepad instead of seeing it as the powerful tool it is.\\ +By the way, the arrow keys don't always work for vim, but don't blame vim. It's actually an issue with the way your terminal is set up. Vim can't tell that your arrow keys are arrow keys. If you have the problem, you have more research to do.\\ +To use VIM well, it is essential that you learn how to move well.\\ +Do not search and scroll. Do not use your eyes to find text. They have computers for that now. Here are a handful of the most important movement commands. The best way to move is by searching: + + +\begin{tabular}{ l | p{9cm}} + {\bf Parameter} & {\bf Result} \\ \hline + {\tt /} & Search forward: will prompt for a pattern\\ + {\tt ?} & Search backward: will prompt for a pattern \\ + {\tt n} & Repeat last search (like dot for searches!)\\ + {\tt N} & Repeat last search but in the opposite direction.\\ + {\tt tx} & Move "to" letter 'x' (any letter will do), stopping just before the 'x'. Handy for change/delete commands.\\ + {\tt fx} & "Find" letter 'x' (any letter will do), stopping on the letter 'x'. Also handy for change/delete commands \\ \hline +\end{tabular}\\ + +\noindent +If you're not searching, at least consider jumping: + +\begin{tabular}{ l | p{9cm}} + {\bf Parameter} & {\bf Result} \\ \hline + \texttt{gg} & Move to beginning of file\\ + \texttt{G} & Move to end of file\\ + \texttt{0} & Jump to the very start of the current line\\ + \texttt{w} & Move forward to the beginning of the next word \\ + \texttt{W} & Move forward to the beginning of the next space-terminated word (ignore punctuation)\\ + \texttt{b} & Move backward to the beginning of the current word, or backward one word if already at start\\ + \texttt{B} & Move backward to the beginning of the current space-terminated word, ignoring punctuation\\ + \texttt{e} & Move to end of word, or to next word if already at end\\ + \texttt{E} & Move to end of space-terminated word, ignoring punctuation\\ \hline +\end{tabular}\\ + +\noindent +The following commands are handy, and are even sensible and memorable if you know regex: + +\begin{tabular}{ l | p{9cm}} + {\bf Parameter} & {\bf Result} \\ \hline + \texttt{\^{}} & Jump to start of text on the current line. Far superior to leaning on $\leftarrow$ or \texttt{h} key.\\ + \texttt{\$} & Jump to end of the current line. Far superior to leaning on $\rightarrow$ or \texttt{k} key\\ \hline +\end{tabular}\\ + +\noindent +Here is some fancy movement: + +\begin{tabular}{ l | p{9cm}} + {\bf Parameter} & {\bf Result} \\ \hline + \texttt{\%} & Move to matching brace, paren, etc\\ + \texttt{\}} & Move to end of paragraph (first empty line)\\ + \texttt{\{} & Move to start of paragraph\\ + \texttt{(} & Move to start of sentence (separator is both period and space)\\ + \texttt{)} & Move to start of next sentence (separator is both period and space)\\ + \texttt{''} & Move to location of your last edit in the current file\\ + \texttt{]]} & Move to next function (in c/java/c++/python)\\ + \texttt{[[} & Move to previous function/class (in c/java/c++/python)\\ \hline +\end{tabular}\\ + +\noindent +Finally, if you can't move by searching, jumping, etc, you can still move with the keyboard, so put your mouse down. + +\begin{tabular}{ l | p{9cm}} + {\bf Parameter} & {\bf Result} \\ \hline + \texttt{h} & Move cursor to the left\\ + \texttt{l} & Move cursor to the right\\ + \texttt{k} & Move cursor up one line\\ + \texttt{j} & Move cursor down one line\\ + \texttt{\^{}f} & Move forward one page\\ + \texttt{\^{}b} & Move backward one page\\ \hline +\end{tabular}\\ + +You want to use the option \texttt{hls} (for "highlight search") in your vimrc. You will learn about that soon enough. In the short term you can type \texttt{:set hls} and press \texttt{Enter}. + +\subsection{Quoting Your Regex Metacharacters} +\label{QuotingYourRegeXMetacharacters} +If you don't know what a regex is, skip this section. For those who understand what a regex is, and who realize that the \texttt{/} command takes a regex rather than just normal text, this will be important. For the rest of you, it will seem totally out of place and should be skipped for now.\\ +You should know how to use regular expressions, because a few tricks in regex will make your whole Unix/Linux/Mac experience a little better. It is too large a topic to expose fully here, but you might try looking at on of the good references or tutorials elsewhere on the web.\\ +The main thing to remember is that VIM will side with convenience when it comes to regex. Since you search a lot, vim will assume that \texttt{/+} means that you want to search for the nearest + character. As a result, all the metacharacters have to be quoted with the backslash (\texttt{$\backslash$}) character. It's sometimes a pain, but if you really want to find a plus sign followed by a left-parenthesis, it is very easy. +\subsection{Don't panic. You have undo/redo} +\label{"Don't panic. You have undo/redo"} +The command for undo is \texttt{u}. That's not too hard to remember, is it? A lot of VIM commands are pretty mnemonic-friendly.\\ +The redo would be the \texttt{r} key, but the \textit{replace} (we'll talk later about this). We're stuck with \texttt{Ctrl-R} instead. Ah, well. You can't have everything.\\ +There is a lot more to undo and redo, but this is enough. Be happy that you can revert changes, and un-revert them. VIM isn't as powerless and unforgiving as you feared it might be, though you might still not like it very much. Just wait for that muscle memory to kick in.\\ +If you get into a real mess, then exit the editor without saving.\\ +If you are really afraid, or really cautious, then you should have version control for your text files. I recommend you start editing with junk files in a junk directory anyway, but when you are working on something important, you should not be afraid to make changes. Version control is a good security blanket and a useful backup strategy. Consider using \href{http://git-scm.com/}{Git} or \href{http://mercurial.selenic.com/}{Mercurial}, both of which are easy and powerful. +\subsection{Shifted letters and DEATH BY CAPS!} +\label{"Shifted letters and DEATH BY CAPS!"} +For a number of commands, \texttt{Shift} will either reverse the direction of a command (so \texttt{N} is the opposite of \texttt{n}, see next bullet) or will modify how the command works. When moving forward by one word at a time (pressing \texttt{w}), one may press \texttt{W} to move forward by one word but with \texttt{W} the editor will consider punctuation to be part of the word. The same is true when moving backward with \texttt{b} or \texttt{B}.\\ +Because a shifted letter may mean something very different from the same letter unshifted, you must be very careful not to turn on the \texttt{Caps Lock}! Sometimes a poor unwary soul will accidentally hit the \texttt{Caps Lock}. When he intends to move left with \texttt{j}, he instead joins the current line with the next. Many other unwanted edits can take place as his fingers make a quick strafing run for some complex edit. It is ugly.\\ +If you encounter DEATH BY CAPS, you should turn off the \texttt{Caps Lock}, and then try pressing \texttt{u} repeatedly to get rid of unwanted edits. If you feel that it's a lost cause, press \texttt{:e!} followed by pressing the \texttt{Enter} key. That will reload the file from disk, abandoning all changes. It's a troublesome thing that will eventually happen to you. Some people turn off their \texttt{Caps Lock} key entirely for this reason. +\subsection{Insert, Overwrite, Change} +\label{"Insert, Overwrite, Change"} +In VIM you have a variety of ways to start entering text, as mentioned above in the section on Modality.\\ +You are normally in command mode. When you type certain keys, you are placed in insert mode or overtype mode. In insert mode, the text you type goes before the cursor position, and everything after the cursor is pushed to the right or to the next line.\\ +In overtype mode your keystrokes are input, just as they are in insert mode, but instead of inserting the keystrokes VIM will replace the next character in the document with the character you type. You get to overtype mode by pressing an overtype key command while in command mode.\\ +In ex mode you are typing a string of commands to run into a little window at the bottom of the screen. We'll talk about this later on, because it's powerful stuff. It's also a little cryptic, so we will wait. You get into ex mode by typing \texttt{:} in command mode.\\ +You always return to command mode from overtype, insert, or command mode by pressing escape. That is one handy key. + +\begin{tabular}{ l | p{9cm}} + {\bf Parameter} & {\bf Result} \\ \hline + \texttt{i} & Insert before the current cursor position\\ + \texttt{I} & Insert at the beginning of the current line. Far better than pressing \texttt{\^{}} and then \texttt{i}\\ + \texttt{a} & Insert after the current cursor position\\ + \texttt{A} & Insert/append at the end of the current line. Far better than pressing \texttt{\$} and then \texttt{i}\\ + \texttt{r} & Retype just the character under the cursor\\ + \texttt{R} & Enter overtype (replace) mode, where you destructively retype everything until you press \texttt{Escape}\\ + \texttt{s} & (substitute) delete the character (letter, number, punctuation, space, etc) under the cursor and enter insert mode\\ + \texttt{c} & The \textit{change} (retype) command. Follow with a movement command. \texttt{cw} is a favorite, as is \texttt{cc}\\ + \texttt{C} & Like \texttt{c}, but for the entire line\\ + \texttt{o} & Insert in a new line below the current line\\ + \texttt{O} & Insert in a new line above the current line\\ + \texttt{:} & Enter command mode (for the advanced student)\\ + \texttt{!} & Enter shell filter mode (for the very advanced student)\\ \hline +\end{tabular}\\ + +Consider the value of the c command. If you use it with the t or f commands, it becomes very powerful. If you were at the C at the beginning of the previous sentence, you could type ct. and retype the whole first sentence, preserving the period. The same is true with other commands, such as the d for delete. The movement commands add a lot of power to the change command, and that's one reason why it is important to learn to move well. + +\subsection{NEVER PARK IN INSERT MODE} +\label{"NEVER PARK IN INSERT MODE"} +Vim is set up to do more navigating than editing. It rewards you for working in the same way, mostly in control mode with spurts of time in an insert mode.\\ +If you try to use vim as a weak form of notepad, modality and navigation will ensure that you are never really efficient. If you want to sail, you have to get in the boat, and if you want to get good at vim, you need to get good in command mode.\\ +So, if you are stopping to think, hit \texttt{Escape}. If you aren't in the middle of text typing, you should be in command mode. If you are wanting to move up or down a line, or to some other place, hit \texttt{Escape}. If you walk away from the keyboard, hit \texttt{Escape}. Otherwise, you will start to type commands and find that you're not in command mode and you have lost your ability to meaningfully use \texttt{.} or \texttt{u}. Also if You want to run one command during typing in insert mode just press \texttt{Ctrl-o} combination and type Your command. After that Vim would automatically return into insert mode. +\subsection{Happiness is a good .vimrc} +\label{"Happiness is a good .vimrc"} +When VIM starts up, it reads your personal settings before it does anything interesting. You can edit a file named \texttt{.vimrc} in your home directory. The above instructions give you enough information that you should be able to edit your .vimrc file and add all the commands listed below. The idea is to enter the commands in the leftmost column of the table. You will have to type them, and correct any spelling errors. Once the file has been created, you will save and exit and the next you start VIM it will have your settings. You can edit this file at any time.\\ +There is very fine magic in VIM. However, it often comes without the magic turned on. Command line completion, color syntax highlighting, the file explorer, and many other features are {\it missing} unless you turn them on in ~/.vimrc.\\ +There is a very nice guide to the various settings in vim, and even an interactive display so that you can turn them on and off. This is not very well-known, I suspect, because I only learned it this year. I wish I had known when I was first starting. + + \texttt{:options} + + \texttt{:browse options} + + \texttt{:browse set} + +In this window, you can browse through all the available options, and can even set them. You can read the short help messages associated with each, or you can hit the enter button on any short help to see the longer help text. If you press the enter key on an option, it will toggle that option or set a new value.\\ +Each of these commands has a shortcut, but you can learn those later. Try entering just the first five commands (one-per-line), save the file, and then edit it again to add the other commands. You will find that the second session will have color syntax highlighting, and will give you more hints and help as you work. + + +\begin{tabular}{ p{4cm} | p {5cm}} + \textbf{Command in .vimrc} & \textbf{Meaning} \\ \hline + \texttt{syntax enable} & Turn on all the magic, including Explorer and syntax highlighting\\ + \texttt{set showmode} & Show me when I'm in insert/overtype mode\\ + \texttt{set showcmd} & When a command is in progress, show it in the status bar\\ + \texttt{set wildmenu} & Magic for completion at the \texttt{:} command line\\ + \texttt{set ruler} & Turn on the \textit{ruler} (status info) at the bottom of the screen\\ + \texttt{runtime ftplugin/man.vim} & Turn on man pages (type \texttt{:Man})\\ + \texttt{set autoindent} & Indent in a smart way, instead of returning to the left margin all the time\\ + \texttt{set expandtab} & Expand tabs to spaces\\ + \texttt{set nowrap} & Don't wrap text (makes windows ugly)\\ + \texttt{set hlsearch} & Highlight all matches in text when you search\\ + \texttt{set showmatch} & Show matches for braces, parens, etc.\\ + \texttt{set ignorecase} & Do case-insensitive searching\\ + \texttt{set smartcase} & When a search phrase has uppercase, don't be case insensitive\\ + \texttt{set path=., .., /usr/include/*, /usr/share/*} & Tell the editor where to search for files\\ + \texttt{set spelllang=en\_us} & When I want spell-checking, I want it to be english\\ \hline +\end{tabular} +\subsection{Help is on its way} +\label{"Help is on its way"} +There is an online help mechanism in VIM. You should know how to use it.\\ +Type \texttt{:help} and you will get a split window with help text in it. You can move around with the arrow keys, or with any of the VIM movement commands you will learn.\\ +You can always enter funky keys by pressing \texttt{\^{}v} first, and then the keystroke. This is most useful in help. You can type \texttt{:help \^{}v\^{}t} to get help for the keystroke \texttt{\^{}t}. By convention you can usually get what you want by typing \texttt{:help Ctrl-T} also. Don't underestimate how handy this is.\\ +Most distributions of VIM will install a program called \texttt{vimtutor}. This program will teach you to use VIM. It will do so by using VIM. It is a handy piece of work (props to the author!).\\ +Help has links. If you see one you like, you can move the cursor to the link (lets not just beat on the arrow keys, here!) and press {\tt \^{}]}. Yeah, it's an odd and arbitrary-looking command. That will not only navigate to the link, but also push it on a stack. If you want to go back, you can press \texttt{\^{}t} (yes, also pretty arbitrary) to pop the current link off the stack and return to the previous location in the help. The commands \texttt{\^{}]} and \texttt{\^{}t} aren't very memorable, but we'll use them for code navigation later, so learning them is not a total waste of mental energy. +\subsection{The Double-Jump} +\label{"The Double-Jump"} +By convention pressing any command twice will tell it to operate on the current line. If you want to yank (copy) the current line, press \texttt{yy}. If you want to delete the current line, press \texttt{dd}. If you want to change (retype) the current line, press \texttt{cc}. This is a pretty consistent convention, down to the special case of "save and exit" being \texttt{ZZ}. Doing operations on the entire current line is very common, and it made sense to make it convenient. +\subsection{Getting rid of things} +\label{"Getting rid of things"} +You can get rid of the character under the cursor by pressing \texttt{x}. If you want to press it 10 times, you can save effort by typing \texttt{10x}. It can be pretty handy, but you could very quickly get tired of counting how many times you want to press \texttt{x}, or you could get tired of holding down the \texttt{x} key. I know I would.\\ +The more flexible delete command is very simple. It is the letter \texttt{d} for \textit{delete}. It is one of the lucky mnemonic commands.\\ +\texttt{D} will take a movement command. You should have learned several in the earlier paragraph. The basic concept is that you will delete from the character under the cursor to some other point in the file.\\ +You can delete the current line by typing \texttt{dd}, or you can delete the current line and the one under it by typing \texttt{d} followed by the \texttt{j} or $\downarrow$. Likewise, \texttt{d} followed by the \texttt{\}} command (end of paragraph) deletes to the end of the current paragraph. \texttt{d} followed by \texttt{G} will delete to the end of the file. You'll find that all commands that take a movement command will work this way (including \texttt{c}). Every movement command you learn increases your power to copy, delete, and retype. This added power is why it is essential that you learn to move well in VIM.\\ +\texttt{d} will also take a repeat count, so you can type \texttt{23dd} to delete 23 lines starting with the current line. This can be handy.\\ +Finally, we have registers. A VIM register is like the copy-and-paste buffer you have used in lesser gui tools. When you delete, the deleted text is saved for pasting and you can get it back by pressing the \texttt{p} (mnemonic: \textit{put} or \textit{paste}) key. The delete key can take another register if you want to specify one. A register is specified with a double-qoute character, followed by the name of a register (which is a lower-case or upper-case letter, where case is significant). That means you may copy multiple bits of text by yanking or deleting them into different register and pasting them into a new place (or new file) by using a register-specific paste.\\ +Pasting also takes a register specification, which is always a double-quote followed by a letter, followed by the \texttt{p} for \textit{paste}. You could even paste a register many times if you specify a repeat count (see the lesson on the basic command pattern).\\ +You actually have more registers than I told you, and can do more with them than I said, but this is enough for a quick lesson on deleting. +\subsection{Use the Dot} +\label{"Use the Dot"} +Edits actions in VIM are recorded. Say that you just deleted a line (by typing \texttt{dd}). The editor knows you deleted a line. You can repeat the edit (that is, delete another line) by pressing the period key (\texttt{.}). You can even apply the standard pattern and give a register, repeat, and then a dot (the dot knows the command and movement). This is particularly handy if the command you last used was \texttt{cw}. It will repeat the replace operation on the text under the cursor.\\ +Because the dot command repeats the last edit you did, it is one of the most powerful keys on the keyboard. You should learn to rely on it. It is one of the most wonderful things VIM gives you.\\ +\subsection{Use the Star} +\label{"Use the Star"} +The star is a great command, especially if you have the option \texttt{hlsearch} turned on in your .vimrc file. It will move to the next use of the word under the cursor. In doing so, it will highlight all uses of the word under the cursor. + + +\begin{tabular}{ l | p{8cm} } + \textbf{Command} & \textbf{Result}\\ \hline + \texttt{*} & Move to next instance of word under cursor\\ + \texttt{\#} & Move to previous instance of word under cursor\\ \hline +\end{tabular} + +\subsection{Registers} +\label{"Registers"} +In most editors you get a single cut-n-paste buffer. When you use the cut or copy command, you lose whatever is in the buffer. As a result you end up zipping back and forth in a file, cutting from one place, and pasting in another. If you are lucky you can split the window and go back and forth between tiles, but it's a lot of manual labor and an exercise in hand-eye coordination as you seek, cursor, mark, cut, seek, cursor, paste your way to authoring nirvana.\\ +It probably took a couple of minutes to get sick of that.\\ +In VIM, they have a different answer. Sadly they have different terminology, too. Instead of editing buffers, we have \textit{registers}. Same concept, different term (the word \textit{buffer} means something else in VIM). You can find a source in your code, yank/copy to many different registers, move to the destination site in your code, and then paste the various register contents. It's all one move.\\ +The registers are (from the VIM documents, available via \texttt{:help} registers): + +\begin{tabular}{ l | p{8cm} } + \textbf{Command} & \textbf{Result}\\ \hline + \texttt{\"{}} & (literally, the quote character) The unnamed or default register\\ + \texttt{a-z},\texttt{A-Z} & The lowercase letters and the uppercase letters\\ + \texttt{+} & The system default register (the normal cut/paste one)\\ + \texttt{*} & Select/drop registers\\ + \texttt{\_} & The black hole -- essentially /dev/null, used to avoid wiping out register \texttt{\"{}} (the unnamed register)\\ \hline +\end{tabular}\\ + +There are also a few other special-purpose registers which I leave for your exploration in the help system, such as the small delete register and the numbered ones. You don't really need to know these.\\ +To tell the difference between the command \texttt{y} and register \textit{y}, VIM expects you to prefix the register name with a double-quote character. Therefore, \texttt{y} is the yank command, and \texttt{\"{}y} is the \textit{y} register. If you type \texttt{\"{}y}, VIM will wait for you to complete the standard pattern with perhaps the optional repeat count, a command, and a movement command (if required). Examples of increasing power/complexity: + +\begin{tabular}{ l | p{8cm} } + \textbf{Command} & \textbf{Result}\\ \hline + \texttt{dd} & Delete the current line into the default, unnamed register (\texttt{\"{}\"{}} or quote-quote)\\ + \texttt{\"{}add} & Delete the current line into register \textit{a}\\ + \texttt{\"{}xy\$} & Yank from the current character to the end of the line into register \textit{x}\\ + \texttt{\"{}byy} & Yank the current line into register \textit{b}\\ + \texttt{\"{}c24dd} & Literally Into register \textit{c}, 24 times delete the current line. That's complex to read, maybe it's easier to just say delete the next 24 lines into the \textit{c} register\\ \hline +\end{tabular}\\ + +I'm sure that \texttt{\"{}c24dd} seems a little crazy, but think how you would do the same work if you were using notepad or the like. This is 6 keystrokes, and only one of the shifted, and you never had to leave the home row to grab a mouse. It would be an extremely efficient way to cut 24 lines into a named register if you happened to know that you had 24 lines. If you didn't know that, the work of counting the lines would more than make up for the convenience. That makes this a pretty academic example, and opens the door to visual marking of text for copy/cut, etc. +\subsection{Marking} +\label{"Marking"} +VIM has non-visual marking and it has visual marking. Chances are, you are interested in visual marking for cut-n-paste (yank-n-put) purposes, so let's look at that. + +\begin{tabular}{ l | p{8cm} } + \textbf{Command} & \textbf{Result}\\ \hline + \texttt{v} & Mark character-wise\\ + \texttt{V} & Mark line-wise\\ + \texttt{\^{}v} & Column-wise marking\\ + \texttt{gv} & Remark the area last marked\\ \hline +\end{tabular}\\ + +The command for visual marking is \texttt{v}. You can press \texttt{v}, cursor or search to the end of your current area of interest, and then do a yank or delete command. In fact, you probably should do that and come back. You can press \texttt{v} again to cancel out of visual marking.\\ +Sometimes you want to mark whole lines at a time. For this, VIM uses the shifted (uppercase) \texttt{V}. It works just like the lower-case \texttt{V} but always selects a whole line at a time. Of course a second press of \texttt{V} will cancel this mode.\\ +Other times, you might want to mark a rectangle instead of whole lines or contiguous characters. For rectangle (blockwise) marking, VIM uses the control character \texttt{\^{}V}. Notice that \texttt{\^{}V} has an entirely different behavior in insert mode. Don't get confused. Pasting rectangular regions is a cool feature.\\ +A cool feature is that you can start marking with \texttt{v}, then press \texttt{V} to switch to line mode, or press \texttt{\^{}V} to switch to rectangle selection.\\ +Once you leave the visual marking mode, the area is no longer marked. the VIM help tells us that we can go back into visual mode with the same marking mode and marked area by typing \texttt{gv}. I've been playing with it. It's handy.\\ +I've been marking the entire document (\texttt{ggVG}) and then yanking it to the machine's cut-n-paste buffer (\texttt{\"{}+y}) and switching to my blog editor. In the blog editor (not vi) I do the standard \texttt{\^{}a \^{}v} to paste my document in. Now I can save a few keystrokes by using \texttt{gv} rather than \texttt{ggVG} before pasting (after the first time).\\ +The marked area becomes a context for other commands, so you can do much more than simple yank and put. You can use the \texttt{r} command and another letter like \textit{X} , and change every character in the marked area to an \textit{X}. You can use the marked are for \texttt{ex} commands (which we've not talked about). There is rather a lot of power here, but we'll end the marking lesson here for now.\\ +And since you're reading this anyway I want to remind you to avoid death by caps, and never park in insert mode. It doesn't belong here, but you need to hear it again. +\subsection{Completion} +\label{"Completion"} +Feel free to use long names and big words, because VIM has completion. It's not intellisense, mind you, but it will finish your words for you. Type enough of a word to be unique, and (without leaving insert mode) press \texttt{\^{}n}. If the word you're looking for is in any of the loaded files (or buffers) then VIM will present its best guess. If it is not the one you want, press ^n again until either you find your word, or you run out of choices. You can also use \texttt{\^{}p} to go back to a previous selection. + +\begin{tabular}{ l | p{8cm} } + \textbf{Command} & \textbf{Result}\\ \hline + \texttt{\^{}n} & In insert mode, complete a word (forward to through choice list)\\ + \texttt{\^{}p} & In insert mode, complete a word (backward through choice list)\\ \hline +\end{tabular}\\ + +In newer version of GVIM (graphical version) a selection box will pop up, and you will pick your word by either typing a little more so it really is unique or else by using arrow keys.\\ +There is a more comprehensive \textit{whole line completion} mechanism available to you also. You can press \texttt{\^{}x\^{}l} to enter a special completion mode. You cycle through choices with ^n for next and ^p for previous, or with arrows (if your vim supports them). Again, if you are using GVIM you will get a popup window with choices. There are times this is more useful than doing cut-and-paste the old-fashioned way. + + Less well known, there is a filename completion mechanism, accessed with ^x ^f. I don't usually use this, and have to keep a note like this tutorial around for the few times that I do. Usually having the file explorer mode and wildmenu around means not having to do filename completion in a normal day. + + ^x^l In insert mode, complete a line + ^n Get next choice + ^p Get previous choice + + When you have your selection, just keep typing. Any key other than a selection key (up/down/^n/^p) will be accepted as new text as is normal in insert mode. This is a little counter-intuitive because you are accustomed to hitting enter or tab to accept the entry. + + There are a number of other special commands which are only available in insert mode. + + Since you have word-completion and line-completion, you have no excuse for writing short and cryptic variable names. Very long, meaningful names are quite feasible and not tedious at all. + 22. Keep text in front of your face + + There are commands for moving the current line. The VIM folks were running out of letters I think, so they attached these commands to the z key. + zt move current line to top of page + zz move current line to middle of page + zb move current line to bottom of page + + You also can do much to keep reference code in front of your face if you use split windows. Lets assume your are in code.cpp, and want to look at code.h for a while. + type effect + :split code.h splits window horizontally and loads code.h in a new window + :vsplit code.h splits window vertically and loads code.h in a new window + + Once you have split windows, you'll want to know how to move between them. Here is a small set of commands (all bound up in ^w sequences) that will help you move about. You can always close any window (even a split one) with the :q or ZZ tricks (from "GET OUT", far above). + ^W followed by Effect + j or leftarrow Move to next window to the left + l or rightarrow Move to next window to the right + k or uparrow Move to window above current window + j or downarrow Move to window below current window + c Close current window + o Close all windows except the current window + Check out :help CTRL-W for more information about window control and movement. + 23. The Explorer + + You can edit directories. Give it a shot. There is help available, and you can get more information on the screen by pressing i. This is a kind of "poor man's midnight commander", or maybe a reasonable substitute for the windows explorer. It's quite handy, and highly recommended. This only works if "syntax enable" is in your .gvimrc file. + o Open file in a (horizontal) split window + v Open file in a (vertical) split window + i show more info + s sort by column under the cursor + r sort in reverse order + D delete file + d make new directory + enter Open file in current window. + + 24. Indenting and unindenting + + Forget using tab. Too many tools use 8-character tabs, which is the standard. if you use tabs, even if you change the tabstop parameter in your code, a lot of programs will display or print your code incorrectly. Tabbing is dead, shifting is king. + + So I recommend you set your tabstops to 8 in your .vimrc (set tabstop=8) and set your shiftwidth to the desired level (set shiftwidth=4). No, rather than recommend, I demand you go and add those two commands to your .vimrc right now. I'll wait. Really... go do it.. + set tabstop=8 Use industry standard 8-char tabs + set shiftwidth=4 Use standard 4-char indentation + set shiftround Indent/Dedent to nearest 4-char boundary + set autoindent Automatically indent when adding a new line + + You need to also have autoindent turned on, so you don't have to manually space or indent every line. Autoindent is so handy, I included it as a necessary feature in the .vimrc section. If you followed the tutorial, you will have it turned on already. Not having it on is stupid. You really want it. + + In CONTROL mode: + < left-shift (requires a movement cmd, works on whole lines) + > right-shift (requires a movement cmd, works on whole lines) + + If you want to move a paragraph to the left, then <} is your command. For shifting three lines right, it would be 3>>. The shift commands follow the standard VIM command pattern (hence the term "standard"). They do not use a buffer. + + In INSERT or OVERTYPE mode: + ^T Indent + ^D Dedent/unindent + 25. Spelling + + VIM can also check your spelling. You can enter the command :set spell to turn on spelling checker. You can also set the dictionary and other options, but :help spell will tell you all about it. + + I don't recommend turning this on normally. A lot of the things you will edit will contain stuff other than the dictionary's list of English words, and that can get to be annoying. I prefer to turn it on and off with :set spell and :set nospell. + + The earnest student can learn to turn this on and off via special scripts that are run whenever a file is loaded. The less interested can skip it. + 26. Little hints + + There are some handy commands for showing you information in the status line, or in a scrolling display. When you need a reminder, but don't need to navigate to some part of source, it can be handy to use these. + [i show first line containing word under the cursor + [I show every line containing word under the cursor + :g/pattern/ show every line matching the regular expression pattern + 27. Shell Filtering + + If you were working at the command line, you would know how to use sort, and filter with grep, maybe how to do various tasks with perl or awk. Those programs are all filters. They read the standard input and they write to standard output. + + When you are VIM, however, you may want to do the same things. It is sure a pain to save the part of a file you want to sort, escape to the command line, sort the piece of the file to a new file, and then load the sorted file fragment into the space in the editor where that piece of unsorted text used to be. + + What you need to know is that all that work is unnecessary. If you wanted to sort a paragraph, and your cursor were at the start of the paragraph, all you have to type is !}sort and the magic is done. + + VIM is written to use filters directly. Not only is this handy for using all those great Linux/Unix filters, but also because you can write your own. Any filter-type program you write is now part of you editor as well as your command-line environment. That is a major bit of editing leverage. It is exciting stuff if you are a command-line guru already. + !!command pass current line only through filter + !}command pass area from current line through end of paragraph through filter + !Gcommand pass area from current line through end of file through filter + :%!command pass the entire current buffer through filter + 28. Code Reformatting + + You can reformat code or text a number of different ways. One is using shell filtering: + %!astyle Restyle the entire file with astyle (a nice reformatting program). + %!indent Restyle the entire file with indent (a nice, older program). + + Another is using the gq command, which re-does the line wrapping, and which has intelligence for wrapping comments correctly. + gqq Re-wrap the current line (a double-jump!) + gqj Re-wrap the current line and the line following + gq} Re-wrap lines from the current line to the end of the paragraph. + + You can also retab a file. Retabbing converts tab stops to spaces, and ensures indentation is correct for each. It is done by setting your tabstop variable to the correct indent level, then setting expandtab, and finally by issuing the :retab command. It would be far too much work if I didn't have expandtab and tabstop set normally. Typically, I set tabstop and retab, and then save. That's a sequence I can map to a keyboard command, or can save as a macro. + + You can also have the editor wrap your text as you type, and preserve your indentation. This is all done via the linebreak, textwidth, and autoindent settings, which you can easily explore with the help facility. + 29. QuickFix mode is your friend + + VIM can run your makefile and take you to each variable in turn. If you have unit tests set up to run as part of the build, and the unit test framework produces messages in a compatible format, you will be guided through the failed tests just as if they were compile errors. Likewise, any style-checking tool you use may be treated likewise if it has a compatible format. + + If you are doing Test-Driven Development, this is a critical feature. with quickfix mode, you can find the rhythm that you're looking for. You can even assign the :mak command to a keystroke (see :help map) so that you don't have to type :make. VIM is a kind of agile editor in that regard. In a separate paper, I'll detail my vim settings for TDD. + + Basic quickfix commands + :make Run the makefile specified by the makefile variable + :cw Show the compile error window if there are compile errors. + :cn Go to the next compile error. + :cp Go to the previous compile error. + + As always, look at :help quickfix to learn more about this valuable mode of work. + 30. Manual page access + + In the .vimrc section I recommended that you turn on the Man feature. since you followed those instructions, you can now access man pages from VIM + + :Man 5 crontab shows you the crontab man page in a split window. Your cursor will be in the help window where you can navigate as you would with tags, using ^] to go to a tag, and ^t to return. When you are done, type :q or ZZ to quit the window. + + If you are looking for a man page for something in your file, you don't have to type the colon and the word man. You can type the leader character (by default "\") and the capital K and vim will find the man page and display it in a split window. By the way, if you change the leader character, you will of course have to adjust these instructions. This is very handy when you are working with scripts or the Linux/Unix C API. + + :Man subject Get manpage for subject + \K Get manpage for word currently under the cursor + + This feature is more valuable if you ensure that you install all of the man pages for the programming tools and libraries you use. Or at least that you urge your systems admin to do it for you. If you work in perl, and you don't have all the perl man pages, you will lose out on this fine feature of VIM. + 31. Ctags lets you navigate like a pro. + + I heartily recommend exuberant ctags as the tag program for almost any language. It will quickly span your code and create a 'tags' file, which tells vim all it needs to know to find a symbol in your source. The tag file gives a file and also a regular expression for finding the line you need. It does a very fine job. + !ctags -R * Run ctags (better to do this in your makefile) + ^] Jump to the definition of the term (class/method/var) under the cursor + ^t Pop the browsing stack, return to previous location + 32. Bookmarks. + + Vim allows you to set a bookmark on a line, and jump from one bookmark to another. + mx Put bookmark 'x' at the current line. + 'x Jump to mark 'x'. + + You can use any letter for a bookmark, however there is a difference between a lower-case letter and an upper-case letter. + + * The lower-case letters set a file-specific bookmark, so that 'a in one file will take you to a different place than 'a in another file. + * Uppercase letters set global bookmarks, so that jumping to 'A will take you to the line you marked in the file where you marked it. This is very handy, but is also sometimes not what you want, because it loads the marked file in the current window. + + 33. Pasting in Insert Mode + + When in insert mode, you're not just stuck with typing characters and doing line completion. There are other commands, and one of them is the ^r command which will read data from a register and type it for you. + + If you last deleted the word falsify and are typing in some part of the document, you can type ^r, followed by the default register named " (doublequote) and the editor will paste the word "falsify" into the text and continue onward in insert mode. + + This is particularly helpful when doing something like cw, because the change command will delete the current word (loading the buffer) and then enter insert mode. So say I place my cursor on the word falsify above: + Command Effect + cw deletes the current word to register ", and enter insert mode + enters the text (we're in insert mode). This text is the beginning of the html tag for bold text. + ^r start the paste-while-in insert mode + " paste from register ' ("falsify") into the current location in the file. + enter the closing tag fror bold + ESC Return to command mode. + u Removes the tag from "falsify"! + + Be warned, the '.' command doesn't see that you used the ^R command, so if you move to the next word and hit '.', vim will change that word to be be the bold-tagged "falsify", too. If you want to bold a bunch of different words, you should learn how to record and playback macros (:help q). + 34. Abbreviate! + + One of the easiest ways to customize your editor is with abbreviations. For instance, of the most commonly mistyped python lines is the famous "main" invocation: + + if __name__ == "__main__": + + + I would like to type the word "pymain" and have the editor replace it with the invocation above. Easy to do: + + :ab pymain if __name__ == "__main__": + + Now when I type any non-alphabetic character after the word pymain, it is expanded automatically. All that VIM needs is an "ab" command and a whole word to expand in insert mode. The expansion is immediate and automatic, there is no hotkey by which you request the expansion. As a result, it will happen when you don't want it to happen. Every time I type pymain, I get the expansion listed above, even if it is an accident. I actually have to type the word wrong exit insert mode and then go back to correct it, because I can't safely type it at all. + + I can add this line to my .vimrc, as long as I leave out the leading colon. My vimrc has a number of abbreviations in it currently, because I choose my abbreviations carefully. + + I find that I sometimes type 'teh' when I mean 'the'. This is easy to fix. + + :ab teh the + + I never type teh intentionally, so it is a good abbreviation candidate. + + You will want to use this feature carefully, so that you don't end up getting unwanted expansions, but it is quite nice if you have common misspellings or long sequences of code that you would otherwise have to type far too often. + 35. Record and playback macros. + + In the help system, this is referred to as "complex-repeat". + + You enter macro recording mode by pressing the command 'q', followed by a register into which the macro will be stored. You can use any of the alphabetic keys (upper or lower case), and any of the digits. Of course you can have all 26 lower case, all uppercase 26 and all digits assigned to macros at one time if you like. + + Every keystroke you type will be recorded until you press the 'q' key again. + + To replay a macro, you use the @ key, followed by the register name. + + Once you have replayed a macro, the undo key will see that macro as a single action. It's very handy, since a macro can make changes in many lines found throughout the file. + + VIM remembers what macro you last played, and can repeat it with the double-jump. The double-jump would be "@@". + + The dot command will see it as a single action as well. That's very cool, because the above lesson becomes much more useful. It works something like this: + Command Effect + qa Start recording the macro to register 'a' + cw deletes the current word to register ", and enter insert mode + enters the text (we're in insert mode). This text is the beginning of the html tag for bold text. + ^r start the paste-while-in insert mode + " paste from register ' ("falsify") into the current location in the file. + enter the closing tag fror bold + ESC Return to command mode. + q Stop recording + W Move one word to the right. + @@ replay the macro, wrapping the word under the cursor + W Move one more word to the right. + . replay the macro again, wrapping the word under the cursor + + The macro you recorded is just text in a register. You can paste it into a document, edit it to improve its operation, yank it back into the register, etc. Macros provide a nice way to simplify complex edits. + + Try ":help q" to see more about macro usage. I didn't tell it all. + 36. Mapping Keys + + Whatever you can do by hand, or with a macro, you can also do with key mapping. All a key mapping does is assign a macro to a keystroke. Here is an example: + + " Move between files in a long list + map :prev + map :next + + + Learn more about mapping via :help map. + 37. Colors and Stuff + + Vim is amazingly customizable, including the colors it uses. Some people make their vim themes available on the internet, and a number of color themes are included in the standard distribution. The one you have seen most is probably the one called "default". If you are in a separate color scheme, you can see it via the command: + + :echo g:colors_name + + Try some of the existing color schemes like delek, darkblue, desert, koehler, elflord, peachpuff, or slate. You can always return to default, or just exit and reload the editor. The command you need is: + + colorscheme delek + + For 'delek', substitue any scheme you like. You can see all the schemes in the explorer mode by typing: + + :e $VIM/vim70/colors + + (assuming you are using vim 7.0. You may have to adjust for verion numbers). + + The colorschemes are built from commands that set individual elements such as the foreground and background of the status line, You can learn an awful lot by reading one or two of the colors files. + The color commands start with "hi" (short for highlight), then the kind of thing to color (called a groupname), and then a string of colors to use for plain terminals (ask your dad) denoted as "term", color terminals denoted as "cterm", and guis (gvim) denoted as "gui". + + Here are a few settings I like for gvim: + + hi LineNr guibg=lightgray guifg=black + hi StatusLine guibg=yellow guifg=darkblue + hi NonText guibg=darkgray + hi ToDo guifg=DarkRed + + + These will color the nontext area that comes past the end of text, the number column on the left of the screen (if you do "set nu"), and colors the active status line (title bar) differently from the status line for inactive tiles/windows. + + For more on coloring and theming, you should consult the built-in help (:help hi) or perhaps some other more weighty and complete guide to VIM + 38. Exploiting the path. + + There is a special vim variable called path which will help you to find files which are referenced by the files you will be editing. This feature is specifically useful if you are editing C program files and you point the path variable to the /usr/include/* directories. + + The value you provide for path is a comma-separated list of paths where files can be found. This allows you to point to the standard include, and your project includes, and any other dirs you find useful. + + To use this feature, place the cursor on the name of a file, and (while in normal/control mode) type gf or ^wf. The file will be loaded into the current window. + set path=.,.**,/usr/include/**,/usr/share/** Probably excessive, but sets the path to find just about anything. May take a long time. + gf Goto File: Get the file whose name is under the cursor + ^Wf Window File: Same as gf except opens the file in a new window + :e# Return to the previous window + + I find the window version more useful generally, but I find the non-window version so much easier to type that I will use it instead. I wish that the file navigation would add to the tag stack, so that ^t would return you to the previous file, but no. Stefan Berglund informs me that the ^o will, however. Now it is much easier to jump backward through the jump list. + + The other workaround is to set a bookmark as a capital letter so that you can do a return to it from another file. I know that sounds a little awful, and it is a little awful, but it works. + + Still, for C/C++ programmers, the combination of \K and ^wf allows a lot of file navigation, and the bookmarks are handy for getting in/out of header files and the like. + + The path is also used by the name completion (^n) system to find the files in which it will search for word completions. + +\end{document} -- cgit v1.2.3