Commit 679ffbe4 authored by psachin's avatar psachin 🎮

Article on magit

Signed-off-by: psachin's avatarSachin Patil <psachin@redhat.com>
parent 106688c2
Pipeline #40328840 passed with stage
in 1 minute and 9 seconds
---
layout: post
title: Emacs Still rocks
tags: emacs
category: article
permalink: /article/emacs-still-rocks/
author: sachin
comments: true
---
GNU Emacs has been around since 1976 and has been a popular choice
amongst Software developers and Writers. Its main focus was
extensible, customizable, self-documenting and real-time display.
Never before a text-editor was designed having a functionality of an
Operating System(Yes for me its an Operating System). Its core was
written in C and the wrapper around is written in <a
href="https://www.gnu.org/software/emacs/manual/html_node/elisp/index.html"
target="_blank">elisp</a> -- a dialect of lisp programming language.
<a
href="https://en.wikipedia.org/wiki/Lisp_%28programming_language%29"
target="_blank">lisp</a> is also a favorable language for Artificial
Intelligence research.
![splash-screen]({{ site.baseurl }}/images/emacs-opensource.com/fig-1.png "Emacs Splash screen")
**Splash screen**: Emacs Splash screen when emacs is started.
I came across Emacs when I was working as a Research Student at the
University. My work involved performing Physics simulations. The
simulation code was written in Python. While all my colleagues were
using VIM, I started with VIM too but soon found terrible to work with
VIM modes. I wanted something simpler, one which should act as a
simple editor but be powerful when needed. I saw few Linux kernel
developers using Emacs and decided to give it a try. Emacs was started
by <a href="https://www.stallman.org/" target="_blank">Richard
Stallman</a>. Without any second thought I installed it. It was
simple, it had menu-bar just like any other editor. I could use a
mouse if required but was also highly customizable. Soon I customized
it for Python(the primary language I used) and got acquainted with the
keystrokes. As time passed my Emacs was configured to my needs and I
was much faster with keyboard than mouse.
Today I don't even need to get out of Emacs to respond to emails, read
news, chat, browse files/directory, run commands, access files on
remote server, blog, and play songs. Emacs has all built-in. I even
program my <a href="https://www.raspberrypi.org/"
target="_blank">Raspberry-Pi</a> and write/burn a code in <a
href="https://www.arduino.cc/" target="_blank">Arduino</a>/Atmega32
micro-controllers from Emacs.
Emacs readily supports all the major programming languages. From
syntax highlighting, auto-completion to help & documentation are some
of the features available to developers. Installing additional
plugins(extensions) can be done using 'package-install'. Emacs binds
with the system so well that one hardly needs to open a terminal to
run commands. If configured, it can be an ideal IDE for developers.
For non-technical tasks like note-taking, agenda and blogs, Emacs
provides a (killer)mode known as <a href="http://orgmode.org/"
target="_blank">org-mode</a>. I manage all my notes and TODO list in
org-mode. Recently I used artist-mode with <a
href="http://ditaa.sourceforge.net/" target="_blank">ditaa</a> for
block diagrams and was surprised with the results. An org-file can be
exported to different formats such as HTML, <a
href="http://www.latex-project.org/" target="_blank">LaTeX</a>, Open
Document, and Markdown.
![artist-mode]({{ site.baseurl }}/images/emacs-opensource.com/fig-2.png "Emacs artist-mode with ditaa")
**artist-mode**: Emacs artist-mode on left-side with finished image
converted using ditaa on right.
For those who are new to Emacs, It is not just an editor but also a
file browser. Consider it just like any other editor. Use mouse and
menu-bar. Try to get familiar with it and then try its built-in
tutorial(or I would say 'self-tutorial'). After spending some time,
try to learn keystrokes and avoid using mouse eventually. You won't
need mouse unless you are using 'artist-mode'. Emacs does not impose
all the complexity at once, but all the functionality is made
available when needed.
### Some of the Emacs extensions I use:
- <a href="http://magit.vc/" target="_blank">magit</a>: A Git
Porcelain inside Emacs. Using magit one can handle <a href="http://www.git-scm.com/" target"_blank">Git</a> repository
within Emacs.
- <a href="https://github.com/pidu/git-timemachine" target="_blank">git-timemachine</a>: Browse
through historic version of a git-controlled file.
- <a href="https://github.com/capitaomorte/yasnippet"
target="_blank">yasnippet</a>: Emacs template system.
- <a href="https://tkf.github.io/emacs-jedi/latest/" target="_blank">emacs-jedi</a>: Python auto-completion library.
- <a href="https://github.com/magnars/multiple-cursors.el"
target="_blank">multiple-cursors</a>: Multiple cursors for Emacs.
- <a href="https://github.com/jekor/hidepw" target="_blank">hidepw</a>: Emacs minor mode for hiding passwords (anti-shoulder-surfing).
- <a href="https://company-mode.github.io/"
target="_blank">company</a>: Complete anything. One can complete any
word using company-mode.
![magit]({{ site.baseurl }}/images/emacs-opensource.com/fig-3.png "Magit interface showing commit logs")
**magit**: magit-log buffer showing Git commit logs.
### People who inspired me to Emacs:
- <a href="http://sachachua.com/blog/" target="_blank">Sacha Chua</a>:
Her blog site has plenty of posts on Emacs. Specially she writes
excellent posts on org-mode and agenda. She also hosts Emacs Hangout
where she regularly interviews Emacs users and developers.
- <a href="http://xahlee.org/" target="_blank">Xah Lee</a>: Xah is the
most inspiring person in Emacs world. He regularly posts on <a
href=""https://plus.google.com/u/0/113859563190964307534/posts"
target="_blank">Google-plus</a>. His tutorials on Emacs and elisp
are most recommended for newbies.
- <a href="http://jekor.com/" target="_blank">Chris Frono</a>: Chris
wrote hidepw and co-hosts <a href="http://www.haskellcast.com/"
target="_blank">The Haskell Cast</a>. His <a
href="https://www.youtube.com/playlist?list=PLxj9UAX4Em-IiOfvF2Qs742LxEK4owSkr"
target="_blank">YouTube</a> videos tutorials on Emacs can be of
great advantage.
- <a href="https://github.com/magnars" target="_blank">Magnar
Sveen</a>: Author and maintainer of multiple-cursors. Check out his
Emacs videos at <a href="http://emacsrocks.com/"
target="_blank">emacsrocks.com</a>
- <a href="https://github.com/jwiegley" target="_blank">John
Wiegley</a>: John is current Emacs maintainer. His Emacs hangout
video on <a href="https://www.youtube.com/watch?v=QRBcm6jFJ3Q"
target="_blank">Emacs Lisp Development Tips</a> is must watch.
I was lazy enough to write the shebang line at the top of a script so
I wrote <a href="https://github.com/psachin/insert-shebang"
target="_blank">insert-shebang</a> which can insert a shebang line at
the top. It works with most scripting languages like Python, Ruby, and
Bash. It can be customized to insert a header line in a C-program as
well. Besides, I maintain a site <a href="http://haqiba.org"
target="_blank">haqiba.org</a> which hosts Emacs config snippets.
Recently I wrote a function which capture screen-shot of a window or a
region using mouse. The code is hosted at <a
href="https://gist.github.com/psachin/6e42d303bc54a5d38798"
target="_blank">https://gist.github.com</a>.
Emacs has lot much to offer than just an editor. It is recommended for
both new users and core developers. Everyday I discover something new
in Emacs and this has never stopped. For many of us an OS is just a
bootloader for Emacs.
I'm impressed by the post titled [A introduction to creating documents
in LaTeX](https://opensource.com/article/17/6/introduction-latex) by
[Aaron Cocker](https://opensource.com/users/aaroncocker) where he
introduces [LaTeX typesetting system](https://www.latex-project.org)
and also explains creating LaTeX document using
[TexStudio](http://www.texstudio.org/). He also explains few LaTeX
editors which users find comfortable for creating LaTeX documents.
What derived my attention was the first comment to the post by [Greg
Pittman](https://opensource.com/users/greg-p) where is says "_LaTeX
seems like an awful lot of typing when you first start..._". In a way
this is true. For beginners, LaTeX is a lot if typing and debugging(if
you missed to escape a special character like an exclamation mark!).
Those reason are enough for a beginner to start searching for a
replacement. So in this post let me introduce you to GNU Emacs to
create LaTeX documents. I promise this will be fast and easy.
## Create your first document.
Launch Emacs by typing,
```
emacs -q --no-splash helloworld.org
```
`-q` flag ensures not to load any Emacs initialization if present. The
`--no-splash-screen` flag prevents displaying splash screen to ensure
you have only one window opened with file `helloworld.org`.
[IMAGE: emacs_startup.png]
(Caption: GNU Emacs with file helloworld.org opened in a buffer window.)
Its time to put some LaTeX headers. We do this the Emacs way. Go to
**Org** in menu-bar and select **Export/Publish**.
[IMAGE: insert_template_flow.png]
(Caption: Images illustrating how to insert a default template.)
In next window, Emacs give options to either export or insert a
template, insert the template by entering **#**([#] Insert template).
This will move a cursor to mini-buffer where the prompt says **Options
category:**. At this time you may not know the category names.
Pressing TAB will show possible completions. Type "default" and press
Enter. Following content will be inserted.
```
#+TITLE: helloworld
#+DATE: <2018-03-12 Mon>
#+AUTHOR:
#+EMAIL: makerpm@nubia
#+OPTIONS: ':nil *:t -:t ::t <:t H:3 \n:nil ^:t arch:headline
#+OPTIONS: author:t c:nil creator:comment d:(not "LOGBOOK") date:t
#+OPTIONS: e:t email:nil f:t inline:t num:t p:nil pri:nil stat:t
#+OPTIONS: tags:t tasks:t tex:t timestamp:t toc:t todo:t |:t
#+CREATOR: Emacs 25.3.1 (Org mode 8.2.10)
#+DESCRIPTION:
#+EXCLUDE_TAGS: noexport
#+KEYWORDS:
#+LANGUAGE: en
#+SELECT_TAGS: export
```
Change the title, date, author and email as you wish. Mine looks like
below.
```
#+TITLE: Hello World! My first LaTeX document
#+DATE: \today
#+AUTHOR: Sachin Patil
#+EMAIL: psachin@redhat.com
```
I don't want table of content to be created for now, hence I change value of
`toc` from `t` to `nil` in line as shown below.
```
#+OPTIONS: tags:t tasks:t tex:t timestamp:t toc:nil todo:t |:t
```
Its time for a section and paragraphs. A section starts with an
asterisk(*). I'll copy content of paragraphs from Aaron's post,
```
* Introduction
\paragraph{}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras lorem
nisi, tincidunt tempus sem nec, elementum feugiat ipsum. Nulla in
diam libero. Nunc tristique ex a nibh egestas sollicitudin.
\paragraph{}
Mauris efficitur vitae ex id egestas. Vestibulum ligula felis,
pulvinar a posuere id, luctus vitae leo. Sed ac imperdiet orci, non
elementum leo. Nullam molestie congue placerat. Phasellus tempor et
libero maximus commodo.
```
[IMAGE: helloworld_file.png]
(Caption: Contents of helloworld.org file)
With content in place, its time to export the content as PDF. Select
**Export/Publish** from **Org** menu again but this time type
**l**(**[l] Export to LaTeX**) followed by **o**(**[o] As PDF file and
open**). This not only opens PDF file for you to view but also save
file as `helloworld.pdf` in the same path as `helloworld.org`.
[IMAGE: org_to_pdf.png]
(Caption: Export helloworld.org to helloworld.pdf)
[IMAGE: org_and_pdf_file.png]
(Caption: helloworld.pdf file opened at the bottom)
You can also export org to PDF by pressing `Alt + x` followed by
typing "org-latex-export-to-pdf". Use TAB to auto-complete.
Guess what's more? Emacs also creates `helloworld.tex` file for you to
have fine control over the content.
[IMAGE: org_tex_pdf.png]
(Caption: Emacs with LaTeX, org and PDF file opened in three different windows)
You can compile `.tex` file to `.pdf` using the
command,
```
pdflatex helloworld.tex
```
The `.org` file as more to offer. It can be exported to HTML or as
simple text file. What I like about org files is they can be pushed to
[GitHub](https://github.com) where they are rendered just like any
other markdown formats.
## Create LaTeX Beamer presentation
Lets go a step ahead and see how to create a LaTeX beamer presentation
using the same file with some modifications as below,
```
#+TITLE: LaTeX Beamer presentation
#+DATE: \today
#+AUTHOR: Sachin Patil
#+EMAIL: psachin@redhat.com
#+OPTIONS: ':nil *:t -:t ::t <:t H:3 \n:nil ^:t arch:headline
#+OPTIONS: author:t c:nil creator:comment d:(not "LOGBOOK") date:t
#+OPTIONS: e:t email:nil f:t inline:t num:t p:nil pri:nil stat:t
#+OPTIONS: tags:t tasks:t tex:t timestamp:t toc:nil todo:t |:t
#+CREATOR: Emacs 25.3.1 (Org mode 8.2.10)
#+DESCRIPTION:
#+EXCLUDE_TAGS: noexport
#+KEYWORDS:
#+LANGUAGE: en
#+SELECT_TAGS: export
#+LATEX_CLASS: beamer
#+BEAMER_THEME: Frankfurt
#+BEAMER_INNER_THEME: rounded
* Introduction
*** Programming
- Python
- Ruby
*** Paragraph one
Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Cras lorem nisi, tincidunt tempus sem nec, elementum feugiat
ipsum. Nulla in diam libero. Nunc tristique ex a nibh egestas
sollicitudin.
*** Paragraph two
Mauris efficitur vitae ex id egestas. Vestibulum
ligula felis, pulvinar a posuere id, luctus vitae leo. Sed ac
imperdiet orci, non elementum leo. Nullam molestie congue
placerat. Phasellus tempor et libero maximus commodo.
* Thanks
*** Links
- Link one
- Link two
```
I have just added three more lines to header,
```
#+LATEX_CLASS: beamer
#+BEAMER_THEME: Frankfurt
#+BEAMER_INNER_THEME: rounded
```
To export to PDF press `Alt + x` followed by typing
"org-beamer-export-to-pdf".
[IMAGE: LaTeX_Beamer_presentation.png]
(Caption: Latex Beamer presentation created using Emacs and Org mode)
Hope it was fun creating a LaTeX and Beamer document using Emacs. It
is faster when using keyboard shortcuts than a mouse. Emacs Org-mode
has lot more to offers than we covered in this post. Please refer
[orgmode.org](https://orgmode.org/worg/org-tutorials/org-latex-export.html)
to learn more.
How do I kill a process / stop a program in Linux?
==================================================
Often times a process misbehaves and you may want to terminate or kill
it. In this post, lets see few ways to terminate a process or
application from Command line as well as via Graphical interface. We
will take [gedit](https://wiki.gnome.org/Apps/Gedit) as an example
application.
Kill/Stop process using Command line
------------------------------------
1. Using termination characters
Ctrl + C
--------
One of the problem invoking gedit from command-line(if you have
not started using `gedit &`) is that it will not free up the
prompt. As a result that shell session is blocked. In such case
Ctrl+C(press Control key in combination with 'C') comes handy.
That will terminate `gedit` and all work is lost(unless the file
was saved).
What Ctrl+C does in background is, it sends
[SIGINT](http://man7.org/linux/man-pages/man7/signal.7.html)
signal to gedit. This is a stop signal. The default action of this
signal is to terminate the process. It instructs shell to stop
gedit and return to main loop and you get the prompt back.
```
$ gedit
^C
```
Ctrl + Z
--------
This is called a _suspend character_. It sends
[SIGTSTP](http://man7.org/linux/man-pages/man7/signal.7.html)
signal to process. This is also a stop signal but the default
action is not to kill but to suspend the process.
It will stop(not kill/terminate) gedit and return back the shell
prompt.
```
$ gedit
^Z
[1]+ Stopped gedit
$
```
Once the process is suspended(gedit in this case), it is not
possible to write or do anything in gedit. In the background, the
process becomes a _job_. This can be verified by `jobs` command.
```
$ jobs
[1]+ Stopped gedit
```
_jobs_ allows user to control multiple processes within a single
shell session. One can stop, resume, and move job to background or
foreground as needed.
Lets resume gedit in background and free up a prompt to run other
commands. This can be done using a command `bg` followed by job
ID(Notice `[1]` from output of `jobs` above. 1 is the job ID)
```
$ bg 1
[1]+ gedit &
```
This is similar to starting `gedit` with `&` as in,
```
$ gedit &
```
2. Using `kill`
`kill` allows a fine controls over signals allowing a user to send
a signal to a process by specifying either a signal name or signal
number followed by process ID or PID.
What I like about `kill` is, it can also work with job IDs. Lets
start gedit in background using `gedit &`. Assuming I have a job ID
of gedit by from `jobs` command, lets send SIGINT to gedit,
```
$ kill -s SIGINT %1
```
Notice that the job ID should be prefixed with '%', else `kill`
will consider it as PID.
`kill` can work without specifying a signal explicitly. In that
case a default action is to send SIGTERM which will terminate the
process. Execute `kill -l` to list all signal names and use `man
kill` command to read the man-page.
3. Using `killall`
If you don't like specifying job ID or PID, `killall` lets you
specify process by name. A simplest way to terminate gedit using
`killall` is,
```
$ killall gedit
```
This will kill all the processes with name "gedit". Like `kill`,
the default signal is SIGTERM. It has fancy option to ignore case
using '-I'. For example,
```
$ gedit &
[1] 14852
$ killall -I GEDIT
[1]+ Terminated gedit
```
Learn various flags provided by `killall`, the one like '-u' which
allows to kill user owned process by exploring its man-page(`man
killall`)
Kill/Stop graphical application
-------------------------------
1. Using `xkill`
Ever encountered an issue where media player like
[VLC](https://www.videolan.org/vlc/index.html) grayed out or in
hung state? Well now you can certainly find PID and kill the
application using above commands or use `xkill` instead.
[IMAGE: xkill_gedit.png]
Caption: Using xkill
`xkill` allows you to kill a windows using a mouse. Simply execute
`xkill` in a terminal which should change the mouse cursor to
**x** or a tiny skull icon and click **x** on a windows you want
to close. Be careful using `xkill` though, it can be dangerous as
the man-page says. You have been warned!
This brings to the end of this article. We learned few techniques to
kill & stop processes. Refer man-page of each command we discussed to
understand it's usage & working. I have left commands like `pkill` and
`pgrep` for you to explore.
# What is a Makefile and how does it work?
If you want to run or update a task when certain files are updated,
the `make` utility can comes handy. The `make` utility requires a file
`Makefile`(or `makefile`) which defines set of tasks to be executed.
You may have used `make` to compile a program from source code. Most
of the Open Source projects uses `make` to compile a final executable
binary which can then be installed using `make install`.
In this post, we'll explore `make` & `Makefile` using basic and
advance examples. Make sure you have `make` installed in your system.
## Basic examples
Lets start by printing the classic "Hello World" on the terminal.
Create a empty directory `myproject` having a file `Makefile` with
below content:
```
say_hello:
echo "Hello World"
```
Now run the file by typing `make` inside the directory `myproject`.
The output will be as below:
```
$ make
echo "Hello World"
Hello World
```
In above example `say_hello` behaves like a function name as in any
programming language. This is called the **target**. The
**prerequisites** or **dependencies** follow the target. But for the
sake of simplicity, we have not defined any prerequisites in the above
example. The command `echo "Hello World"` is called the **recipe**.
The *recipe* uses *prerequisites* to make a *target*. The target,
prerequisites, & recipes together makes a **rule**. To summarize,
below is the syntax of a typical rule:
```
target: prerequisites
<TAB> recipe
```
As an example, a target might be a binary file which depends on
prerequisites(source files). On the other hand, a prerequisite can
also be a target which depends other dependencies. Something like:
```
final_target: sub_target final_target.c
Recipe_to_create_final_target
sub_target: sub_target.c
Recipe_to_create_sub_target
```
It is not necessary that the target should be a file. Like in our
example, the target can just be a name for the recipe. We call such
targets as "Phony targets".
Lets go back to the example above. When `make` was executed, the
entire command - `echo "Hello World"` got displayed followed by actual
command output. We often don't want that. To suppress echoing the
actual command, we have to start `echo` with `@`:
```
say_hello:
@echo "Hello World"
```
Now try to run `make` again. The output should only be display on the
terminal:
```
$ make
Hello World
```
Lets add few more phony targets - `generate` and `clean` to the
`Makefile`:
```
say_hello:
@echo "Hello World"
generate:
@echo "Creating empty text files..."
touch file-{1..10}.txt
clean:
@echo "Cleaning up..."
rm *.txt
```
If we try to run `make` after the changes, only the target `say_hello`
will be executed run. That's because only the first target in the makefile is the
default target. Often called as *default goal*. This is the reason you
will see `all` as the first target in most projects. It is the
responsibility of `all` to call other targets. We can override this
behavior using a special phony target called `.DEFAULT_GOAL`. Lets
include that at the beginning of our makefile:
```
.DEFAULT_GOAL := generate
```
This will ensure to run the target `generate` as default:
```
$ make
Creating empty text files...
touch file-{1..10}.txt
```
As the name suggest the phony target `.DEFAULT_GOAL` can only run one
target at a time. This is also the reason most makefiles includes
`all` as a target which can call as many targets as needed. Lets
include the phony target `all` and remove `.DEFAULT_GOAL`:
```
all: say_hello generate
say_hello:
@echo "Hello World"
generate:
@echo "Creating empty text files..."
touch file-{1..10}.txt
clean:
@echo "Cleaning up..."
rm *.txt
```
Before running `make` lets include another special phony target `.PHONY`
where we define all the target which are not files. `make` will run
its recipe un-conditionally, regardless of whether a file with that
name exists or what its last-modification time is. Here is the
complete makefile:
```
.PHONY: all say_hello generate clean
all: say_hello generate
say_hello:
@echo "Hello World"
generate:
@echo "Creating empty text files..."
touch file-{1..10}.txt
clean:
@echo "Cleaning up..."
rm *.txt
```
The `make` should call `say_hello` and `generate`:
```
$ make
Hello World
Creating empty text files...
touch file-{1..10}.txt
```
It is a good practice not to call `clean` in `all` or put it as the
first target. `clean` should be called manually when cleaning is
needed as a first argument to `make`:
```
$ make clean
Cleaning up...
rm *.txt
```
Now you got an idea how a basic makefile works and how to write a
simple makefile. Lets see some advance usage of makefile.
## Advance examples
### Variables
In above example most of target and prerequisite values are hard coded
but in real life projects those are replaces with variables and
patterns.
A simplest way to define a variable in a makefile is using `=`
operator. For example to assign the command `gcc` to a variable `CC`:
```
CC = gcc
```
This is also called *recursive expanded variable* and used in a rule as below:
```
hello: hello.c
${CC} hello.c -o hello
```
As you might have guessed, the recipe expands as below when it is
passed to the terminal:
```
gcc hello.c -o hello
```
Both `${CC}` and `$(CC)` are valid references to call `gcc`. But if
one tries to reassign a variable to itself, it will cause an
infinite loop. Lets verify this:
```
CC = gcc
CC = ${CC}
all:
@echo ${CC}
```
Running `make` will result in: