Skip navigation

Category Archives: Uncategorized

When in need to enter special character inside emacs you can quote it with “C-q” and enter the octal character code, so for instance to type “ñ” you will do: “C-q 361

I found a thorough description of iso-latin-1 on the web, plus a great deal of general info on character and encodings available there as well http://www.cs.tut.fi/~jkorpela/chars/index.html

Within emacs it’s easy to pull any charset-table by doing “M-x list-charset-chars“, say if we type latin-iso8859-1 at the prompt the program shows:

character set

Then, for specifics about any character, simply highlight it and do “M-x describe-char” to get a full detailed view like:

character: ñ (241, #o361, #xf1)
preferred charset: latin-iso8859-1
(Right-Hand Part of ISO/IEC 8859/1 (Latin-1): ISO-IR-100)
code point: 0x71
syntax: w which means: word
category: .:Base, j:Japanese, l:Latin
buffer code: #xC3 #xB1
file code: #xF1 (encoded by coding system iso-latin-1-unix)
display: by this font (glyph code)
uniscribe:-outline-Bitstream Vera Sans Mono-normal-normal-normal-mono-13-*-*-*-c-*-iso8859-1 (#x78)

Character code properties: customize what to show
name: LATIN SMALL LETTER N WITH TILDE
old-name: LATIN SMALL LETTER N TILDE
general-category: Ll (Letter, Lowercase)
decomposition: (110 771) (‘n’ ‘̃’)

There are text properties here:
charset latin-iso8859-1

Awesome power!

Advertisements

Despite being dealing with databases for some years it was just recently that I started to run mysql queries straight from the shell by doing something like:

mysql -u(user) -p(password)  -t -e ‘whatever sql query here in one line’

Although a handy way to use every now and then, I still felt this sort of limited since the query to be passed in the “-e” argument must go inside a single line. In search of  a better alternative I was pleased to figure instead that it’s possible to combine heredoc sintaxis with the sql execution in the command line. Heredoc is a mechanism to break text into multiple lines, just as a file would be treated, after the “<<” sign, the parser says: “here follows a document” which gets wrapped inside the pair of whatever text delimeters we choose. The obvious convenience is that without having to create a file we could easily run multiline queries -which read more naturally with line breaks and indentation- in the same way we would write them inside a file.

To quickly see what I’m talking about type

mysql -u(yourDatabaseUserName) -p(your Password)   -t<<eof
show databases
eof

Now hit “Control D” and then, “Enter” to see the output directly thrown at your shell

To speed things up, since  I use the shell inside emacs, I bound the following to C-S f11 adding  what is below into my .emacs file:

(set-register ?q “mysql -u kabul -p ******** -t <<eofsql”)
(defalias ‘Q
(read-kbd-macro “M-x insert-register RET Q C-e “))
(global-set-key [C-S-f11] ‘Q)

here’s an example of how to run php in the command line, something I almost never do and would like to remember by writing it down.
Simply echo the php statement (within its corresponding tags) and pipe it to the php service. Eg:

echo ‘<?php $str = ‘2144338’; echo substr($str,0,2); ?>’ | php

or even more usefully:

echo ‘<?php  phpinfo(); ?>’ | php

Having discovered the command cpio (wich acts like tar but preserving symbolic links) to recursively put into a single file all the directory structure and files of an entire website, I started to explore its use along with other ways to securely move files between hosts. The command rsync seems like an extraordinary find in that regard.

Here are some neat examples for backing up (or mirroring) sites with ssh I don’t want to miss:

There’s a really easy way to make a remote directory be an exact match of a local directory via an ssh connection. And that’s to use rsync to do the job. It’s smart and only sends enough data to sync the remote dir to the local one. Assuming that you have a local dir named master-copy and the remote system’s repository is in a directory named slave-copy you’d do:

rsync --rsh=ssh --delete -Cav master-copy/* user-name@remote.dom.tld:/path-to/slave-copy

That command will recursively sync everything found in master-copy to the remote. Any files found on the remote that aren’t in master-copy or one of its sub-dirs will be deleted from master-copy. Only changed or new files will be transferred to the remote.

to which another expert adds:

The rsync idea is good — but I for my part always try NOT to install any additional software not essentially required. Today, ssh is “a must” on most systems and you can go with the cpio approach I’ve mentioned.
I must admit the rsync thing is transferring less data if stuff is already on the target side, but this is not the case when running
source=/var/tmp ; target=/var/backup
cd $source ; find . -mtime -1 -type f -print | cpio -ocB | ssh -l username host-b "cd $target ; cpio -icBduml"

daily.

Another suggestion to copy the entire directory tree at /some/path to other.host via SSH is to do:

find /some/path -print | sort | cpio -o -Hnewc | ssh -C other.host "cpio -idvum"

Finally, there’s more to chew with this thorough example on how to mirror a site with rsync http://www.askapache.com/security/mirror-using-rsync-ssh.html

Two essential copy/paste  I sometimes need while interacting with unix vim in windows

  • to paste on Vim from a selection done in the clipboard: Ctrl + mouse right click (in insertion mode)
  • to copy from Vim:  select text (by highlighting it with the mouse), press the middle mouse button to paste.

Hand editing web stuff (outside of wysiwyg editors, that is) a lot of times requires dealing with messy html markup. Even though tags are meant to be parsed by browsers, and there are even performance benefits for serving ugly obfuscated code without white spaces, the human readability of the markup needs some tidiness in the formatting of web pages for which the indentation of tags makes us able to understand what goes on inside it.

Emacs has a large set of commands to internally handle code indentation, but never occurred to me until recently that they could be helpful to simply re-align the clutter of html tags that you can see from the output of a source view.

I went on defining something basic like this little elisp function to quickly help with the general re-alignment of code.

(defun my-tidy ()
  "Automatically re-indents code"
  (interactive)
  (execute-kbd-macro
   (read-kbd-macro "C-u -999 M-x indent-region RET C-x C-x M-x indent-region")))

(global-set-key (kbd "C-M-*") 'my-tidy)

Now that was fine but still insufficient. Say, what about the embedded css or javascript that normally goes along inside a web page?
I didn’t like the way emacs (in its default mode, of course) gets css code re-aligned, plus I actually do have specific requirements which demand the ability to reformat the css style sheets declaration and rules when editing a web document. As I use firefox with its web-developer plug-in, in order to save screen real state I leave the narrowest possible window at my left, therefore it is inconvenient to have css stuff deeply indented to the right (wanted just one space from left margin), additionally, rules needed to be broken up nicely as well (avoiding long chains like #div a.rule1, #div b.rule2, #div c.rule 3 for example).

This screen-shot might show better why the formatting of css code matters so much in my work setup.

my css editing style

So playing a bit more with the idea, I went on crafting some good old sed and awk one-liners for reformatting all what could be found embedded inside <style> tags. The formidable shell-command-on-region in emacs allows such things. You will note that the regexp ain’t look pretty,  it’s sort of long (I might make another post explaining how it breaks up), and also has the dreaded leaning toothpick syndrome! cause emacs lisp needs characters to be double escaped.

In short, all what I wanted is wrapped up below exactly as it now goes inside my emacs init :

(defun select-css-code ()
  "Select region contained by <style></style> tags.
   Simply highliths what is between those tags for embedded css content"
  (interactive)
  (save-excursion)
  (let(p1 p2)
    (goto-char (point-min))
    (search-forward "<style ")
    (backward-char 7)
    (setq p1 (point))
    (search-forward "</style>")
    (setq p2(point))
    (goto-char p1)
    (push-mark p2)
    (setq mark-active t)))

(defun select-javascript-code ()
  "Select region contained by <script></script> tags.
   Simply highliths what is between those tags for embedded javascript content"
  (interactive)
  (save-excursion)
  (let(p1 p2)
    (goto-char (point-min))
    (search-forward "<script ")
    (backward-char 8)
    (setq p1 (point))
    (search-forward "</script>")
    (setq p2(point))
    (goto-char p1)
    (push-mark p2)
    (setq mark-active t)))

(defun re-indent-web-page-code ()
  "Re-indents html code including its embedded javascript and css.
The css code gets indented diferently (through some awk and sed one-liners)
to ease the editing of styles with Firefox using a window of its Web-Developer plug-in."
  (interactive)
  (progn
    (mark-whole-buffer)
    (indent-rigidly (region-beginning)(region-end) -999)
    (indent-region (region-beginning) (region-end))
    (select-javascript-code)
    (javascript-mode)
    (indent-rigidly (region-beginning)(region-end) -999)
    (indent-region (region-beginning) (region-end))
    (html-mode)
    (select-css-code)
       (setq command  "awk  '/{/ {gsub(/,/,\",\\n\")} {print }' | sed -ne '1h;1!H;${;g;s#{\\([^\\n]\\)#{\\n\\1#g;p}' | sed -ne '1h;1!H;${;g;s#;}#;\\n}#g;p}' | sed -ne '1h;1!H;${;g;s#;\\([^\\n]\\)#;\\n\\1#g;p}' |  sed -e 's#^[ \\t]*\\(.*\\)$#\\1#g' |  awk  '!/{|}|^ *#/&&!/^\\// {$0 = \" \"$0} {print }'  | awk NF |  sed -e 's#\}$#}\\n#g' | sed -ne '1h;1!H;${;g;s#,\\n#,#g;p}' | awk  '/{/ {gsub(/,/,\",\\n\")} {print }' | sed -e 's#^[ \\t]*\\(.*\\),$#\\1,#g'" )
      (shell-command-on-region (mark)(point) command t t)))

UPDATE: note that instead of a macro call

    (execute-kbd-macro
     (read-kbd-macro "M-x indent-region"))

I’m using this straight forward lisp expression

    (indent-region (region-beginning) (region-end))

TODO:
The function is almost there, I still need to address a couple of things:
What if we have many [style or javascript] sections intermingled in our html?
One way to address that would be to successively grab the content, send it to other place using the acummulating-text function of emacs like ‘append-to-buffer ( http://www.gnu.org/software/emacs/manual/html_node/emacs/Accumulating-Text.html), then, we can switch to that second buffer, treat the code there and simply get it back to the original document.
Also noted that the css code doesn’t get indented if the javascript tags aren’t found, so I’ll revise the logic to allow it regardless of whether javascript code exist or not.

Not sure why the default configuration was changed in version 23 for the functions that move cursor around like forward-word, backward-word or back-to-indentation. They highlight the words now. Until I figure it out, (it must be a simply variable to set, any idea?, anyone?) a quick and dirty fix to reset to the previous way I liked, is doing:

;; correcting the way forward-word and similar functions work. 
I don't want them to highlight text while moving cursor.                                                                                                    
(global-set-key (kbd "M-F") 'forward-word)
(global-set-key (kbd "M-B") 'backward-word)
(global-set-key (kbd "M-m") 'back-to-indentation)
(global-set-key (kbd "M-M") 'back-to-indentation)

UPDATE:
Forget about the above rebinding, I just found out what variable we should change to simply return to the Emacs 22 default behavior:

(setq shift-select-mode nil) ; “t” for true, “nil” for false

(Got this at http://xahlee.org/emacs/emacs23_features.html, an impressive site full of valuable information)

At times it’s necessary to manually force a non-cache reload/refresh of a page, overriding what browsers (wrongly) interpret as when the last change of a site happened. (The cache is a temporary storage area where frequently accessed data can be stored for rapid access in our hard drive.)
To do this in FireFox, hold down SHIFT and click the RELOAD button. In Internet Explorer, hold down CTRL and click the REFRESH button. Other browsers can allow this quick bypass which I was glad to discover, very handy and much simpler than erasing the whole cache. Check these instructions containing others like Safari, Chrome, Konkeror and Flock.


“He was the director of the great library of Alexandria, where one day he read in a papyrus book that in the southern frontier outpost of Syene, near the first cataract of the Nile, at noon, on June 21 vertical sicks cast no shadows. On the summer solstice, the longest day of the year, as the hours crept toward midday, the shadows of temple columns grew shorter. At noon, they were gone. A reflection of the Sun could then be seen in the water at the bottom of a deep well. The Sun was directly overhead.
It was an observation that someone else might easily have ignored. Sticks, shadows, reflections in wells, the position of the Sun-of what possible importance could such simple everyday matters be? But Eratosthenes was a scientist, and his musings on these commonplaces changed the world; in a way, they made the world. Eratosthenes had the presence of mind to do an experiment, actually to observe whether in Alexandria vertical sicks cast shadows near noon on June 21. And, he discovered sticks do.
Eratosthenes asked himself how, at the same moment, a stick in Syene could cast no shadow an a stick in Alexandria, far to the north, could cast a pronounced shadow. Consider a map of the ancient Egypt with two vertical sticks of equal length, one stuck in Alexandria, the other in Syene. Suppose that , a a certain moment, each stick casts no shadow at all. This is perfectly easy to understand-provided the Earth is flat. The Sun would then be directly overhead. I the tow sicks cast shadows of equal length, that also would make sense on a flat Earth: the Sun’s ray would then be inclined a the same angle to the two sticks. But how could it be that at the same instant there as no shadow at Syene and a substantial shadow at Alexandria?

The only possible answer, he saw, was that the surface of the Earth is curved. Not only that: the greater the curvature, the greater the difference in the shadow lengths. The Sun is so far away that its rays are parallel when they reach the Earth. Sticks placed at different angles so the Sun’s rays cast shadows of different lengths. For the observed difference in the shadow lengths, the distance between Alexandria and Syene had to be about seven degrees along the surface of the Earth: that is, if you imagine the sticks extending down to the center of the Earth, the would there intersect at an angle of seven degrees. Seven degrees is something like one-fiftieth of three hundred and sixty degrees, the full circumference of the Earth. Eratosthenes knew that the distance between Alexandria an Syene was approximately 800 kilometers, because he hired a man to pace it out. Eight hundred kilometers times 50 is 40,000 kilometers: so that must be the circumference of the Earth.
This is the right answer. Eratosthenes’ only tools were sticks, eyes, feet and brains, plus a taste for experiment. With them he deduced the circumference of the Earth with and error of only a few percent, a remarkable achievement for 2,200 years ago. He was the first person accurately to measure the size of a a planet.

The calculation:

From the shadow lenght in Alexandria, the angle A can be measured. But from simple geometry (“if two parallel straight lines are transected by a third line, the alternate interior angles are equal”), angle B equals angle A. So by measuring the shadow lenght in Alexandria, Eratosthenes concluded that Syene was A=B =7grades away on the circumference of the Earth.

This is was for me one of the most memorable paragraphs in the Carl Sagan book which I read about 20 years ago. There is an appeal to it that is moving: the elegance of an inquisitive mind unveiling the reality, battling the unknown domains with impeccable reasoning.
What has this to do with emacs, unix and the gnu tools I blog about while making my way through them? May be something in line with the appreciation of first class outcomes, stuff which is enduring through the beauty of its rare simplicity and cleverness.