Emacs: print with line numbers - emacs

Does anyone know how to print with the line numbers of the code in the margin? I can display the line number, cannot have that in the printout. Thanks!

You can add the line numbers with temporary overlays and convert the buffer to HTML using the htmlize package, after which you can save the HTML and print using lpr or a browser.
(defun htmlize-with-line-numbers ()
(interactive)
(goto-char (point-min))
(let ((n 1))
(while (not (eobp))
(htmlize-make-tmp-overlay (point) (point) `(before-string ,(format "%4d " n)))
(setq n (1+ n))
(forward-line 1)))
(switch-to-buffer (htmlize-buffer)))
This will require a recent version of htmlize.

Sorry for the solution on such an old post. I used ps-print-buffer rather than print-buffer, since the results are much nicer looking. Anyway, for some reason it is not documented in the manual, but if you look at the source for ps-print.el, you find the ps-line-number variable that you can set to non-nil in order include line numbers.
M-x set-variable RET ps-line-number RET t
That should set it temporarily so that you can print. You may want to set it permanently in your init.el.
You can also print using the M-x pr-interface command, which brings up a buffer of all sorts of printing options.

An easy yet hackish way would of course be to temporarily insert line numbers directly into the buffer
C-<
C-M-% ^ RET \,(1+ \#) SPC RET
then print it
M-x print-buffer
and then undo the line numbers again:
C-/
C-u C-SPC
The result is not very beautiful, but usable. There are three main problems:
you're making changes to the buffer. In particular, that means the buffer must not be read-only.
the line numbers are left justified which means you get different indentation depending on the number of digits in the line number.
your major mode will trip over the line numbers and you'll lose the syntax highlighting. If you're printing on a black-and-white printer that's not a problem though.
You could fix the second point by using a more complicated replacement string:
\,(format "%4d " (1+ \#))
but then you have to know what is the maximum line number so you can give the right number of digits between % and d. You could of course just jump to the end of the buffer quickly to check the maximum line number. But more importantly, it's becoming a pain to type all that every time you want to print line numbers.

Related

Emacs: line numbers that respect line-wrapping

Modes: I'm using linum for line numbers, the package linum-relative for relative line numbers. If it matters, I am also using visual-line-mode. These are flexible.
Currently, a single line (i.e. text without a newline) is numbered as only one line, regardless of how many times it is wrapped. I am wondering if there is a way to change the numbering to respect these wraps. So, for example,
263 This is all in
a single line
without newlines
might become:
263 This is all in
264 a single line
265 without newlines
and, in relative mode:
0 This is all in
a single line
without newlines
might become:
-1 This is all in
0 a single line
1 without newlines
I really only want the change in relative mode, but would not mind if it spills over into absolute mode.
A toggled change that works on both would be most useful - that way, the user can specifically select when, or with which modes, to turn it off or on.
If the goal is navigation, I suggest a similar solution via the popular ace-jump-mode.
If the goal is just persistent line numbering, you might consider longlines-mode instead of visual-line-mode (but I would avoid this, personally).
ace-jump # GitHub
https://github.com/winterTTr/ace-jump-mode
Demo:
http://dl.dropboxusercontent.com/u/3254819/AceJumpModeDemo/AceJumpDemo.htm
With it, you can jump to any line with as little as two keypresses.
In addition to lines, you can jump to the start of any word; there's also individual character-level jump precision. If desired, it can be configured to restrict jumps to the current window/buffer, or across all windows in the current frame, and even multi-frames.
It doesn't, however, recognize wrapped lines as jump-able locations. Again, you might consider longlines-mode as a fix for this if it is really important to you, but as I understand, it's considered hack'ish and deprecated in favor of visual-line-mode. Though, with longlines-mode, the lines are renumbered exactly as you want in your first example.
I'm assuming the goal is navigation, and as such, I think you'll find with just a little practice that word-based jumping or even jumping via incremental search to be a superior solution.
Update
Here's a simple solution to trick ace-jump to scan within N lines using emacs narrowing features; perhaps others can improve upon it. You could also do something similar for word and line modes.
(defun brian-ace-jump-to-char-within-N-lines (&optional n)
(interactive "p")
(let* ((N (or n 0))
(query-char (read-char "Query Char:"))
(start (save-excursion
(forward-line (- N))
(point)))
(stop (save-excursion
(forward-line (1+ N))
(point))))
(unwind-protect
(condition-case err
(progn
(narrow-to-region start stop)
(ace-jump-char-mode query-char))
(error
(message (error-message-string err))))
(widen))))

fix an auto-complete-mode and linum-mode annoyance

I'm using auto-complete-mode which I think is totally fantastic. I'm also a big fan of linum-mode but I've got a very irritating issue when the two are used together, especially when I'm working in a new buffer (or a buffer with very few lines).
Basically the buffer is 'x' lines long but when auto-complete kicks in it "adds" lines to the buffer, so linum-mode keeps switching, for example, between displaying line numbers on one column or two columns, depending on whether auto-complete is suggesting a completion or not.
So you type a sentence and you see your buffer's content frantically shifting from left to right at every keypress. It is really annoying.
I take it the solution involves configuring the linum-format variable but I don't know how.
Ideally it would be great if my linum-format was:
dynamic
right-aligned
considering there are 'y' more lines to the buffer than what the buffer actually has
My rationale being that auto-complete shall not suggest more than 'y' suggestion and that, hence, the two shall start playing nicely together.
For example, if 'y' is set to 20 and my buffer has 75 lines, then linum should use two columns: because no matter where I am auto-complete shall not make the buffer 'bigger' than 99 lines.
On the contrary, if 'y' is still set to 20 and my buffer has 95 lines, then linum should use three columns because otherwise if I'm near the end of the buffer and auto-complete kicks in my buffer shall start "wobbling" left and right when I type.
I'd rather not hardcode "3 columns wide" for linum.
I guess using "dynamic but always at least two columns" would somehow fix most annoyances but still something as I described would be great.
P.S: I realize that my 'fix' would imply that linum would always display on at least two columns, and I'm fine with that... As long as it stays right-aligned and use 2, 3 or 4 columns depending on the need.
Simply put the following line in .emacs which resolves this issue. It is in auto-complete.el.
(ac-linum-workaround)
I've written a couple of previous answers on modifying the linum-mode output, which you could probably adapt to your purposes.
Relative Line Numbers In Emacs
Colorize current line number
Edit: Here's the most basic version of that code (also on EmacsWiki, albeit somewhat buried), which doesn't modify the default output at all, but uses the techniques from those other answers to be more efficient than the default code. That's probably a more useful starting point for you.
(defvar my-linum-format-string "%4d")
(add-hook 'linum-before-numbering-hook 'my-linum-get-format-string)
(defun my-linum-get-format-string ()
(let* ((width (length (number-to-string
(count-lines (point-min) (point-max)))))
(format (concat "%" (number-to-string width) "d")))
(setq my-linum-format-string format)))
(setq linum-format 'my-linum-format)
(defun my-linum-format (line-number)
(propertize (format my-linum-format-string line-number) 'face 'linum))
Just have the same problem, after seeing 'patching the source' I believe it could be done with advice. Here is what I come up with
(defadvice linum-update
(around tung/suppress-linum-update-when-popup activate)
(unless (ac-menu-live-p)
ad-do-it))
I would like to use popup-live-p as mentioned but unfortunately it requires the variable for the popup, which we couldn't know in advance.
Update:
I ended up patching the source for linum.el. I added an extra hook that runs before updates.
Here's the patched file: linum.el (github)
Here's the code I have in my init.el:
;; Load custom linum.
(load-file "~/.emacs.d/linum.el")
;; Suppress line number updates while auto-complete window
;; is displayed.
(add-hook 'linum-before-update-hook
'(lambda ()
(when auto-complete-mode
(if (ac-menu-live-p)
(setq linum-suppress-updates t)
(setq linum-suppress-updates nil)))))
Hope it helps!

emacs macro to convert a vector to a matrix in .csv notation

I have a single line text file of csv values
I would like to able to 'pretty-print' the file to span multiple lines to make it more readable
The 1st no. represents the no. of csv values in the next section and so on
e.g.
3,1,2,3,3,4,5,6
would be converted to:
3,1,2,3
3,4,5,6
I know a little about making macros, e.g.
C-x (
C-s RET ,
C-x )
using this I can do:
C-u 3 C-x e to move 3 csv values along
My sticking point is how to use the value from file to paste into the arg to C-u
maybe I should be using an e-lisp function instead as its a function I would like to 'save' for continual use across emacs sessions. Is it possible to save macros as such?
any ideas gratefully received
I find elisp easier to think about than keyboard macros. How about this:
(defun csv-line-breaks ()
(interactive)
(while (search-forward "," nil t
(1+ (string-to-number (thing-at-point 'word))))
(delete-char -1)
(insert "\n")))
(global-set-key (kbd "C-c b") 'csv-line-breaks)
With this in your .emacs (or just evaluate the code in your scratch buffer), you put point at the beginning of the line, then hit C-c b to break the line up into the chunks you want.
What this does:
Looping over the buffer until it runs out of values, and for each loop:
Read the first value. (thing-at-point 'word) grabs anything it finds between whitespace of punctuation (more or less).
Convert the value, which is actually a string, into a number
Add one to that number, and move forward that many commas
Delete the previous comma
Insert a new line
You might want to take a look at csv-mode for Emacs: http://emacswiki.org/emacs/CsvMode
Although it might not do exactly what you're looking for, it has a feature for formatting for readability, as well as other features for munging csv files in a variety of ways.

Stack overflow while generating tags completion table in emacs

I'm using GNU Emacs 23.3 on Windows. I work in a very large codebase for which I generate a TAGS file (using the etags binary supplied with Emacs). The TAGS file is quite large (usually hovers around 100MB). I rarely need to use any functionality beyond find-tag, but there are times when I wish I could do completion out of the TAGS table.
Calling complete-tag causes Emacs to make a completion table automatically. The process takes quite a bit of time, but my problem isn't in the amount of time it takes, but rather the fact that right at the end (around 100% completion), I get a stack overflow (sorry about the unprintable chars):
Debugger entered--Lisp error: (error "Stack overflow in regexp matcher")
re-search-forward("^\\(\\([^]+[^-a-zA-Z0-9_+*$:]+\\)?\\([-a-zA-Z0-9_+*$?:]+\\)[^-a-zA-Z0-9_+*$?:]*\\)\\(\\([^\n]+\\)\\)?\\([0-9]+\\)?,\\([0-9]+\\)?\n" nil t)
etags-tags-completion-table()
byte-code(...)
tags-completion-table()
Has anyone else run into this? Know of a way to work around it?
EDIT: Stack output after turning on debug-on-error
EDIT: Removed stack, since I now know what the failing entries look like:
^L
c:\path\to\some\header.h,0
^L
c:\path\to\some\otherheader.h,0
My tags file contains quite a few entries in this format. Looking at the headers involved, it's clear that they couldn't be correctly parsed by etags. This is fine, but I'm surprised that tags-completion-table doesn't account for this format in its regex. For reference, here's what a real entry looks like:
^L
c:\path\to\some\validheader.h,115
class CSomeClass ^?12,345
bool SomeMethod(^?CSomeClass::SomeMethod^A67,890
The regexp in question is used to match a tag entry inside the TAGS file. I guess that the error can occur if the file is incorrectly formatted (e.g. using non-native line-endings), or if an entry simply is really, really large. (An entry is typically a line or two, which should not be a problem for the regexp matcher.)
One way of tracking down the problem is go to the TAGS buffer and see where the point (cursor) is, after the error has occurred. Once you know which function it is, and you could live without tags for it, you could simply avoid generating TAGS entries for it.
If the problem is due to too complex entry, I would suggest that you should send bug report to the Emacs team.
If you load the tags table (open the TAGS table with Emacs, then bury-buffer), try M-x dabbrev-expand (bound to M-/). If the present prefix is very common, you might end up running through many possible completions before reaching the desired one.
I don't use Windows, but on the Mac and Linux machines I use, I have not faced this issue.
This looks like a bug in Emacs, see:
https://groups.google.com/d/msg/gnu.emacs.help/Ew0sTxk0C-g/YsTPVEKTBAAJ
https://debbugs.gnu.org/db/20/20703.html
I have applied the suggested patch to etags-tags-completion-table (copied below in completeness for your convenience) and trapped an error case.
I'm triggering the error in an extremely long line of code (46,000 characters!). I presume somebody programmatically generated the line and pasted it into the source. A workaround could be to simply filter such lines at the ctag building or loading stage, just something that deletes "long" lines, whatever that may mean. Probably 500 characters is long enough!
I could also look at adding maximum sizes to my regexes in ctags, but that really isn't a general solution because many ctags patterns do not have such limits.
(defun etags-tags-completion-table () ; Doc string?
(let ((table (make-vector 511 0))
(progress-reporter
(make-progress-reporter
(format "Making tags completion table for %s..." buffer-file-name)
(point-min) (point-max))))
(save-excursion
(goto-char (point-min))
;; This monster regexp matches an etags tag line.
;; \1 is the string to match;
;; \2 is not interesting;
;; \3 is the guessed tag name; XXX guess should be better eg DEFUN
;; \4 is not interesting;
;; \5 is the explicitly-specified tag name.
;; \6 is the line to start searching at;
;; \7 is the char to start searching at.
(condition-case err
(while (re-search-forward
"^\\(\\([^\177]+[^-a-zA-Z0-9_+*$:\177]+\\)?\
\\([-a-zA-Z0-9_+*$?:]+\\)[^-a-zA-Z0-9_+*$?:\177]*\\)\177\
\\(\\([^\n\001]+\\)\001\\)?\\([0-9]+\\)?,\\([0-9]+\\)?\n"
nil t)
(intern (prog1 (if (match-beginning 5)
;; There is an explicit tag name.
(buffer-substring (match-beginning 5) (match-end 5))
;; No explicit tag name. Best guess.
(buffer-substring (match-beginning 3) (match-end 3)))
(progress-reporter-update progress-reporter (point)))
table))
(error
(message "error happened near %d" (point))
(error (error-message-string err)))))
table))

How to get Emacs to unwrap a block of code?

Say I have a line in an emacs buffer that looks like this:
foo -option1 value1 -option2 value2 -option3 value3 \
-option4 value4 ...
I want it to look like this:
foo -option1 value1 \
-option2 value2 \
-option3 value3 \
-option4 value4 \
...
I want each option/value pair on a separate line. I also want those subsequent lines indented appropriately according to mode rather than to add a fixed amount of whitespace. I would prefer that the code work on the current block, stopping at the first non-blank line or line that does not contain an option/value pair though I could settle for it working on a selected region.
Anybody know of an elisp function to do this?
Nobody had what I was looking for so I decided to dust off my elisp manual and do it myself. This seems to work well enough, though the output isn't precisely what I asked for. In this version the first option goes on a line by itself instead of staying on the first line like in my original question.
(defun tcl-multiline-options ()
"spread option/value pairs across multiple lines with continuation characters"
(interactive)
(save-excursion
(tcl-join-continuations)
(beginning-of-line)
(while (re-search-forward " -[^ ]+ +" (line-end-position) t)
(goto-char (match-beginning 0))
(insert " \\\n")
(goto-char (+(match-end 0) 3))
(indent-according-to-mode)
(forward-sexp))))
(defun tcl-join-continuations ()
"join multiple continuation lines into a single physical line"
(interactive)
(while (progn (end-of-line) (char-equal (char-before) ?\\))
(forward-line 1))
(while (save-excursion (end-of-line 0) (char-equal (char-before) ?\\))
(end-of-line 0)
(delete-char -1)
(delete-char 1)
(fixup-whitespace)))
In this case I would use a macro. You can start recording a macro with C-x (, and stop recording it with C-x ). When you want to replay the macro type C-x e.
In this case, I would type, C-a C-x ( C-s v a l u e C-f C-f \ RET SPC SPC SPC SPC C-x )
That would record a macro that searches for "value", moves forward 2, inserts a slash and newline, and finally spaces the new line over to line up. Then you could repeat this macro a few times.
EDIT: I just realized, your literal text may not be as easy to search as "value1". You could also search for spaces and cycle through the hits. For example, hitting, C-s a few times after the first match to skip over some of the matches.
Note: Since your example is "ad-hoc" this solution will be too. Often you use macros when you need an ad-hoc solution. One way to make the macro apply more consistently is to put the original statement all on one line (can also be done by a macro or manually).
EDIT: Thanks for the comment about ( versus C-(, you were right my mistake!
Personally, I do stuff like this all the time.
But I don't write a function to do it unless I'll be doing it
every day for a year.
You can easily do it with query-replace, like this:
m-x (query-replace " -option" "^Q^J -option")
I say ^Q^J as that is what you'll type to quote a newline and put it in
the string.
Then just press 'y' for the strings to replace, and 'n' to skip the wierd
corner cases you'd find.
Another workhorse function is query-replace-regexp that can do
replacements of regular expressions.
and also grep-query-replace, which will perform query-replace by parsing
the output of a grep command. This is useful because you can search
for "foo" in 100 files, then do the query-replace on each occurrence
skipping from file to file.
Your mode may support this already. In C mode and Makefile mode, at least, M-q (fill-paragraph) will insert line continuations in the fill-column and wrap your lines.
What mode are you editing this in?