Emacs

Emacs:

emacs is open source editor to edit or create any text file. It's licensed under GPL. It's written in Lisp, and it's functionality can be extended by anyone, by writing macros in Lisp.

emacs can bw used to write programs in any language. Beauty is that it allows automatic indenting, braces, etc needed for that particular language, so that you can identify your mistakes even while typing.

Xemacs is a branched version of emacs, derived from emacs 19. Their features are roughly comparable, but they differ significantly at Lisp programming level. Xemacs is not currently being actively developed, so it's behind emacs in terms of features. So, stick with emacs, as there is nothing you can do on Xemacs and not on emacs. Plus emacs is the real gnu project.

A lot of good doc for emacs is on gnu website: https://www.gnu.org/software/emacs/manual/

especially the emacs pdf manual: https://www.gnu.org/software/emacs/manual/pdf/emacs.pdf

Remember, emacs is huge, so don't spend rest of your life reading all the manuals. Instead, just 10-20 cmds will suffice to get most work done. Then, you can search for additional cmds, as you need them.

Install:

You should always install GNU emacs GTK+ version, as other version of GNU emacs don't have graphical buttons for browsing thru dir, etc. This is usually referred to as "Emacs metapackage", and it's guaranteed to to be the latest recommended Emacs variant.

linux mint: sudo apt install emacs => installs latest emacs, as of 08/2019, it's emacs-25.

Ubuntu: Under Synaptics package manager (on Ubuntu Cinnamon), look for emacs (In description, it should say metapackage). Install it. Or run "apt search emacs metapackage" on cmdline in Terminal, and then install the right one. On my system, emacs got installed at /snap/bin/emacs, instead of at /usr/bin/emacs.

Settings:

When you type "emacs" or click on "emacs" shortcut, it brings up emacs gui based on default settings. You can customize the looks and feel of emacs based on your preference. One of the files that is used for this is ".emacs" in your home dir in linux. Anyfile with a "." in the front is a hidden file, so it doesn't show up via ls, but shows up as long listing, i.e cmd "ll".

If you don't already have a .emacs file, create one.

Syntax:

  • comments are written using ";;" at beginning of line, or via ";" at end of line.
  • All custom settings for variables are put in (custom-set-variables '(<SETTING1> <VALUE1>) '(<SETTING2> <VALUE2>) '(...)). We can use separate stmt for eah setting, but the syntax has to be followed.
  • All custom settings for faces are put in (custom-set-faces '(<SETTING1> <VALUE1>) '(<SETTING2> <VALUE2>) '(...)). 

1. show name of buffer: One of the important settings is where you want the name of the file to show up on the title bar. By default, emacs shows user@hostname on title bar. This becomes an issue when you have too many windows of emacs open, as you can't see at a glance which file is open on which window. If you usually keep more than 1 emacs open, it's best to add the below setting so that it shows the name of current file open in title bar.

;; add this so that titlebar shows name of buffer
(setq frame-title-format "%b")

2. inhibit annoying startup screen: You can use below settings for that:

(custom-set-variables
 '(inhibit-startup-screen t))

3. Display line numbers permanently: You can set this via below setting:

(custom-set-variables

'(global-display-line-numbers-mode t))

4. init file: prevent emacs from loading init file from xeamcs

(custom-set-variables

'(setq load-home-init-file t)) ; don't load init file from ~/.xemacs/init.el

5. verilog setting => not sure for what ? FIXME ?

(custom-set-variables
 '(verilog-typedef-regexp "_t$"))

Save settings automatically:

Instead of typing these settings in .emacs file, we can automatically save these settings by going to options->save_options in top menu of emacs. This will add pertinent lines to .emacs file automatically based on what you have currently.

Ex: For displaying lines, we goto: Options->ShowHide->Line_Numebers_for_all_lines->Global_Line_Numbers_Mode. This starts displaying line numbers. Now if we goto Options->Save_options then this option " '(global-display-line-numbers-mode t) " will be added to .emacs file. This way we don't have to remember all settings manually.

run emacs:

emacs /home/file.txt => opens file using emacs gui

commands in emacs:

emacs has a gui with buttons for file, edit, etc. It's very easy to use. Each button also has a shortcut. Any cmd that can be executed using buttons can be executed using short cut too. Common shortcuts here: https://shortcutworld.com/Emacs/linux/Emacs_23.2.1_Shortcuts

In shortcuts in above link, Meta key (M) refers to "Meta" key that was present on MIT keyboards where emacs was developed. Out side of MIT, Meta key didn't exist on Keyboards. So, 2 alternatives key were chosen => Esc and Alt key. Meta was mapped to both keys. Usually it's the left hand Alt key that it was mapped to. Since Alt key may not be present on all keyboards, emacs allowed Esc key also to be used as Meta key. On Mac notebooks, M key refers to "command" key (as command key is a substitute for Alt key). However, the way we use Esc key and Alt key for Meta key is different. With Alt key, we keep it pressed, while pressing other keys. With Esc key, we have to press Esc key, then let it go, before we press other keys. Generally, it's safe to stick with Alt as Meta key, since that always works.

Similarly Ctrl key (C) refers to "control" key on bottom left of keyboard.

When it says "ctrl + s" key, it means press 1st key (here it's "ctrl key") and then while it is still pressed, press the other key (here it's "s key").  When it says 3 keys as "Meta + Ctrl +s", it means first press Esc key, then let it go. now press "ctrl+s" in regular fashion.  When shortcut keys show comma in b/w, as in "ctrl + x, 1", it means press "ctrl+x" in regular fashion, then let your hands go off those keys, now press the 3rd key after comma ("1 key").

Built in functions: All these shortcuts are actually executing built in functions within emacs. We can run those function directly too. The way to execute function is "M + x" (Meta  and  "x" key where "x" is fr execute) followed by typing the function name.  Ex: To run function "forward-sexp" you need to hit Meta and x, keys and then type "forward-sexp" on the cmd line.

1. search:

emacs has a button for "search" under "edit" menu. To do simple string search, we do "string forward" or "string backward" (can also be done by using shortcut "ctrl + s" keys, i.e "ctrl" key followed by "s" key for forward string search, or "ctrl + r" for backward string search). Now, if we keep on pressing "ctrl+s", we will go to next searched item for that string, and continue going, until we are at last searched item.

emacs supports RE (not sure if ERE supported). More details in emacs section. Link: https://www.emacswiki.org/emacs/RegularExpression

So to do regular expression search, which is much more powerful, we need to do "regexp forward" or "regexp backward". This has a 3 key shortcut = "Meta + Ctrl +s". Pressing meta key changes meaning from string search to regexp search. Now we can press "ctrl+s" key, and it will start doing regexp search, with whatever regex pattern we provide. Now, if we keep on pressing "ctrl+s", we will go to next searched item for that regex, and not to the string. However, if somehow we lose the Esc key (because we pressed any other key or pressed on text), then pressing "ctrl+s", will bring us back to regular string search. We have to press "esc" again to get into meta mode. Then pressing "ctrl+s" will get us to regex search, with last searched regex pattern.

ex: press Meta+ctrl+s, type .*(me) => This searches for pattern "(me)" in all the lines. Since it's BRE search, we don't need to escape ( ) as by default parenthesis ( ) are treated as literals in BRE.

2. search and replace: This works the same way as search, except that it searches and replaces the matching pattern with your new replacement pattern. emacs has a button "replace" under edit menu. This is interactive search and replace, which replaces patterns one by one waiting for your yes/no (y or n) answer before each replacement. Instead of typing y or n, we can type "!" mark (exclamation mark without quotes), and it will search and replace globally

Link: https://www.oreilly.com/library/view/learning-gnu-emacs/1565921526/ch04s02.html

Just like in "search" option above, we have 2 flavors here => one is regular string "search and replace", while other is "regex" search and replace.

ex: add a / at the end of each line. For this we need to use "regex search and replace". To do this, first choose from top Edit->replace->replace regexp. Then type "\(.*\)$" (without the quotes), hit enter, and then type the replacement pattern, which is "\1/" (without the quotes). Since emacs is BRE, ( is escaped with backquotes to treat it as special character. We store everything before the end of line in (.*), which is later accessed using \1, then we put / at end. This pattern is useful as many times we want to add a comment or special char at end of each line.

ex: replace [text] with \[text\]: Again use regex for this. search = \[\(.*\)\] replace = \\[\1\\] . [] is BRE metacharacter, so escape it using \. () is treated as literal in BRE, so we escape it to be treated as metachar. So, this finds everything within [] and stores it in \1 as we used () which stores whatever matched inside it. Now we replace [ with \[. But \ by itself is escape char, so use \\ to treat it as literal. [ doesn't need to be escaped as it's understood to be a literal. []  is not treated as metachar as [] within a replacement string doesn't make sense as a metachar (i.e [abc] in search means match any of "abc" but in replace it would have no meaning). We can test this by trying to put \ infront of [ (i.e using \\\[\1\\\] would error out with msg "invalid use of \"). So, what we have works w/o issues. Finally try some text. As an ex: [5ty] will become \[5ty\]

3. select, cut/copy/paste:

To select a large region of text, it's inefficient to select start of text and keep rolling the cursor. A better way is to press CTRL + SPC (i.e "ctrl" + "space" key) with the cursor at the start of text that we want selected. This sets the mark at one end of text. Then we goto end of text,  and everything until that point is selected. Now we can use cut,/copy buttons to cut or copy the text. Then we can paste this text anywhere using paste button.

4. comment out regions of code:

Sometimes, you write a pgm using emacs, and want to comment out a large section of code. To do this, you first select the region to comment out, then press Meta+x keys (known as M-x), and then type comment-region in that bottom section where M-x appeared. Instead of writing long cmd "comment-region", we can also write shot form "comm-r". Then on pressing enter, all of the text within hselected region will be preceeded by a comment character. However, emacs may not know what is valid comment character for this particular file, so it will ask you to provide a comment character (i.e for python and many scripting languages, it's #). Once a comment character is provided, from next time, it won't ask you for a comment character.

Another way to comment or uncomment a selected regios is to press shortcut keys "Meta" key + ";" key (i.e press Meta and then ; while keeping Meta key pressed). This will comment out the whole selected region. If the region was already commented, then it will uncomment it. Other shortcut is press "ctrl + x" and then "ctrl + ;". This will comment or uncomment. However, uncomment sometimes didn't seem to work with these set of keys, and it ended up double commenting. Not sure what causes this indeterministic behaviour.

5. Finding/Matching balanced expressions:

Sometimes, you want help finding where the piece of code starts and where it ends. These are usually put in brackets, parenthesis, braces (called parenthetical group or PG), or may be words, numbers, etc. We can navigate thru these by using key combo:

  1. PG: we can use keys "M + C + n" (which is ctrl+alt+n key) to move to next one to closing PG, or " M +C + p" to move to previous one or opening PG.
  2. Balanced Expressions: Instead of using n or p keys, we use "f" and "b" to move forward or backward.
  3. Built in function: We can directly execute function "show-paren-mode" to highlight parenthesis. Hit "Meta" and "x" keys followed by typing function name "show-paren-mode"

 


 

variables:

Emacs uses variables internally to determine various settings. You can change those globally, or for just 1 buffer. A variable is a Lisp symbol which has a value. The symbol's name is also called the variable name. A variable name can contain any characters that can appear in a file, but most variable names consist of ordinary words separated by hyphens. There are various ways to read/change these variable values, or define new variables using gui. However, we can specify these variables within a file also, so that when we open the file using emacs, these var will get applied, and that file will open consistently with same looks and feel for anyone opening that file. However, there is a problem with this approach. These extra lines specifying emacs var values are not part of that file's syntax and will probably cause a syntax violation for that language, when run with a simulator. So, we put these var within comments for that kind of file (i.e if it's C pgm, we put it within /* */), but emacs is able to interpret that these var within comments are meant for it.

There are 2 ways to specify such var:

1. in first line of file, using "-*-" line: If first file specifies an interpretor(i.e #!/usr/bin/perl), then put this line as 2nd line of file. You can specify any number of variable/value pairs in b/w -*-, each pair with a colon and semicolon (i.e -*- var_name: value; ... -*-). NOTE: such lines are preceeded by comment syntax for that kind of file.

ex: In perl file, test.pl, we add below line as 1st or 2nd line. keyword "perl" in b/w -*- specifies to emacs that this file is perl file. So emacs sets it's display based on perl. NOTE: this line is put within perl comment "#", so that perl interpreter ignores it. Here, we do not have "var_name: value" format, not sure why? FIXME ?

#-*-perl-*-

ex: In tcl file, test.tcl, we add this line. This specifies various var_name and their values. special var name "mode" specifies major mode, here it's "tcl". That implies to emacs that it's a tcl file.

# -*- mode: tcl; basic-offset: 4; -*-

2. specify local var list at end of file: Emacs identifies anything within string "Local variables:" and "End:" as emacs local variables. In between these strings, come the variable names and values, one set per line. The set are specified as "variable_name:value", so that var name is assigned that value.

ex: In verilog file, test.v, we can add following lines at end of file. So, verilog var are assigned values as indicated. NOTE: all these lines are put within comments (i.e // or /* */)

// Local variables:

// verilog-library-flags:("-f vexpand.dirs")

// verilog-auto-inst-param-value:t

// End:

The above 2 methods are for specifying per file var, but we can also specify these var on per dir level, so that it applies these var to all files, within a particular dir. We can also do this on per buffer level. This is all explained here: https://www.gnu.org/software/emacs/manual/html_node/emacs/Variables.html

AutoSaved Files during Crash of emacs: whenever emacs crashes or your computer shuts down, emacs saves a file with same name but with #. i.e myfile is automatically saved as #myfile#. Since it saves this file periodically, you can get most of your edits. You have to open your file "myfile", and then type M-x (Esc key followed by letter x), and then type recover-file. emacs will guide you to recover the file. You have to enter the file name you want to recover (i.e myfile), and then it will auto prompt with that it will use to replace this file (i.e #myfile#). If this looks complicated, you can just copy #myfile# as "myfile" and all your last changes will get saved in original file.

Various modes for emacs:

emacs can have various modes to support writing your program in different languages. This support makes it easy to see visually different sections of code, identify syntax errors, missing parenthesis, etc. See  Verilog section for verilog mode of emacs. Other modes exist for languages as Python, C, tcl, bash, csh, etc. Now-a-days, IDE (Integrated Development Editor) do these things where they show the code written in a particular language very nicely formatted, colored and visually appealing.