Include code snippet in org file - org-mode

I'm wanting to use org mode to write a technical book. I'm looking for a way to insert existing code from external file into a babel code block that would give nice formatting when exporting to pdf.
For example
#+BEGIN_SRC python "./code/foo.py"
# insert_line (45,50)
#+END_SRC
would then give me the equivalent of the following from line 45 to 50 in foo.py
#+BEGIN_SRC python
def times_two(x):
y = x*2
return y
print times_two(5)
#+END_SRC
Is there anyway of doing this?

I think something like this could work:
#+include: "./code/foo.py" :lines "45-50"
Link to manual: http://orgmode.org/manual/Include-files.html

You can use a shell script to print the lines out with a :wrap header. For example, here I print lines 9-18 of the wos.py script. The shell script won't export if you set :exports too.
#+BEGIN_SRC sh :wrap src python :exports results
sed -n 9,18p wos.py
#+END_SRC
#+RESULTS:
#+BEGIN_src python
class HTTPSudsPreprocessor(urllib2.BaseHandler):
def __init__(self, SID):
self.SID = SID
def http_request(self, req):
req.add_header('cookie', 'SID="'+self.SID+'"')
return req
https_request = http_request
#+END_src
If you don't have sed, you can write a little python script that does the same thing. Just remember to shift the line numbers by one, and to set results to code.
#+BEGIN_SRC python :results code :exports results
with open("wos.py") as f:
print("".join(f.readlines()[8:17]))
#+END_SRC
#+RESULTS:
#+BEGIN_SRC python
class HTTPSudsPreprocessor(urllib2.BaseHandler):
def __init__(self, SID):
self.SID = SID
def http_request(self, req):
req.add_header('cookie', 'SID="'+self.SID+'"')
return req
https_request = http_request
#+END_SRC

Related

Julia macros: #__FILE__ #__LINE__ in macro

This code:
macro FL(message)
return #sprintf("%s:%d | %s", #__FILE__, #__LINE__, message) # line 2
end
println(#FL("m")) # line 4
prints fl.jl:2 | m. How can I make it print fl.jl:4 | m?
The following will work in the current Julia nightly:
macro FL(message)
return :(#sprintf("%s:%d | %s", $(string(__source__.file)), $(__source__.line), $(esc(message)))) # line 2
end
println(#FL("m")) # line 4
This was made possible by the following implementation pull request. It is not possible in any officially released version, unfortunately.
Though there may be more elegant ways to do this, if you don't want this to block your progress on other fronts, why not just pass the line number to the macro...
macro FL(message, line)
return #sprintf("%s:%d | %s", #__FILE__, line, message)
end
println(#FL("m", #__LINE__))

SML in org-mode block returns it = "stdIn" : string

When I start an SML REPL and put in
print("floor is : " ^ (Int.toString (floor 3.1823)) ^ "\n");
I get
floor is : 3
val it = () : unit
i.e., expected behavior. But when I do the same thing in an Emacs org-mode source block:
#+name: sml_test
#+begin_src sml :exports both
print("floor is : " ^ (Int.toString (floor 3.1823)) ^ "\n");
#+end_src
I get the cryptic (for me)
#+RESULTS: sml_test
: val it = "stdIn" : string
Does anyone from the ML world know what this could mean?
This is probably a bug in ob-sml. If you visit the *sml* buffer, and do C-c C-c on the source block, the sml REPL gets this input:
print("floor is : " ^ (Int.toString (floor 3.1823)) ^ "\n");
; "stdIn";
Note the extra "stdIn" there. Also if you set :results output on the block, you should get the standard output of the block, but I get the same thing as with the default :results value setting (and the same thing you get: the cryptic thing which I guess is the result of that spurious "stdIn" - I should say that I know nothing about ML, so take all this with the appropriately sized grain of salt). I would open an issue on the ob-sml github project.

How to add some text between source code and results exports to PDF?

Whenver I want to export a source code block with it's results, I want to add some text in-between, e.g. "Output:", because otherwise is very hard for the reader to understand where the program ends and the output begins - how do I achieve adding "Output:" in-between?
Example:
* Test
#+BEGIN_SRC python :results output :exports both
i = 5
print i
i = i + 1
print i
s = '''This is a multi-line string.
This is the second line.'''
print s
#+END_SRC
#+RESULTS:
: 5
: 6
: This is a multi-line string.
: This is the second line.
You need to name your source code block. Then, and only then, you can put your results part wherever you want, even before the source code block.
EDITED (add ECM):
#+name: my-block
#+begin_src emacs-lisp
(message "hello")
#+end_src
I can put paragraphs here...
#+results: my-block
: hello

Having a table as result of an org-babel code block in Perl

I have a very simple example to illustrate the problem. Consider the following code block in Perl, in an org-mode file:
#+begin_src perl :results table
return qw(1 2 3);
#+end_src
It produces the following result:
#+results:
| 1\n2\n3\n |
which is not totally satisfactory since I was expecting a full org-table.
For instance, in Python the following code:
#+begin_src python :results table
return (1, 2, 3)
#+end_src
produces this result:
#+results:
| 1 | 2 | 3 |
So that's apparently working in Python but not in Perl. Am I doing something wrong? Is this a known bug?
Since I felt a little masochistic this morning I decided to take a shot at hacking a little lisp again. I cooked up a small fix which works for your example but I can't promise it will work more complex ones. So here it comes:
org-babel defines a wrapper for each language. The perl one did not produce something babel detects as a list so I modified it. In order to not make everything formated as a table I had to check if the result was printable as a table:
(setq org-babel-perl-wrapper-method
"
sub main {
%s
}
#r = main;
open(o, \">%s\");
if ($#r > 0) {
print o \"(\",join(\", \",#r), \")\",\"\\n\"
} else {
print o join(\"\\n\", #r), \"\\n\"
}")
You can modify this further to fit your needs if you want to.
The next thing is that the perl-evaluate method in babel does not run the output through further formating so I modified the evaluate method taking the new parts from the python-evaluate code:
(defun org-babel-perl-table-or-string (results)
"Convert RESULTS into an appropriate elisp value.
If the results look like a list or tuple, then convert them into an
Emacs-lisp table, otherwise return the results as a string."
(org-babel-script-escape results))
(defun org-babel-perl-evaluate (session body &optional result-type)
"Pass BODY to the Perl process in SESSION.
If RESULT-TYPE equals 'output then return a list of the outputs
of the statements in BODY, if RESULT-TYPE equals 'value then
return the value of the last statement in BODY, as elisp."
(when session (error "Sessions are not supported for Perl."))
((lambda (raw)
(if (or (member "code" result-params)
(member "pp" result-params)
(and (member "output" result-params)
(not (member "table" result-params))))
raw
(org-babel-perl-table-or-string (org-babel-trim raw))))
(case result-type
(output (org-babel-eval org-babel-perl-command body))
(value (let ((tmp-file (org-babel-temp-file "perl-")))
(org-babel-eval
org-babel-perl-command
(format org-babel-perl-wrapper-method body
(org-babel-process-file-name tmp-file 'noquote)))
(org-babel-eval-read-file tmp-file))))))
The new parts are org-babel-perl-table-or-string and the part in org-babel-perl-evaluate between the empty lines (plus 1 closing parenthesis at the end).
So what this now does is let perl print lists similar to the way python prints them and put the printed results through org-babel's formating procedures.
Now to the result:
A List:
#+begin_src perl :results value
return qw(1 2 3);
#+end_src
#+results:
| 1 | 2 | 3 |
A scalar:
#+begin_src perl :results value
return "Hello test 123";
#+end_src
#+results:
: Hello test 123
Ways you can use this code:
Place it in scratch and M-x eval-buffer for testing
Place it in a elsip src block at the beginning of your org-document
Place it in your .emacs after babel is loaded
Modify ob-perl.el in your lisp/org folder (might need to recompile org-mode afertwards)
I didn't not tested this much further than the output examples I gave you so if it misbehaves for other examples feel free to complain.

Printing UTF-8 text in slime REPL

I'm a beginning user of both Emacs and Clojure, testing my working environment with some simple text processing. I'm having problems getting the Slime REPL to properly print UTF-8 text stored in a vector.
I start by reading the contents of a file (a dictionary of Tocharian B) into a vector:
user> (def toch
(with-open [rdr (java.io.BufferedReader.
(java.io.FileReader. "/directory/toch.txt"))]
(vec (line-seq rdr))))
=> #'user/toch
I then try to get a line from the vector, and I get garbage:
user> (toch 44)
=> " Examples : /// kektseñe akappi ste ‘the body is an impurity’ (121b5), akappī = BHS aśuciṃ (529a3). "
I can enter the string into the Slime REPL and get it back as it should be:
user> " Examples : /// kektseñe akappi ste ‘the body is an impurity’ (121b5), akappī = BHS aśuciṃ (529a3). "
=> " Examples : /// kektseñe akappi ste ‘the body is an impurity’ (121b5), akappī = BHS aśuciṃ (529a3). "
And I can print to disk without any problem:
user> (binding [*out* (java.io.FileWriter. "test.txt")]
(prn (toch 44)))
=> nil
[Contents of test.txt: " Examples : /// kektseñe akappi ste ‘the body is an impurity’ (121b5), akappī = BHS aśuciṃ (529a3). "]
And getting lines from the vector from other REPLs (e.g. clj, lein repl) also works fine. It's only when I try to look at the contents of the vector within the Slime REPL that there's any problem.
What's going on here? Is there some miscommunication between Emacs and Swank? How can I fix this?
Try putting
(setq slime-net-coding-system 'utf-8-unix)
into your .emacs file (or setting and saving the variable via M-x customize-variable).
In addition, make sure that you are running Clojure from within a UTF-8-enabled locale (if you're on Un*x and using Leiningen, try something like env LC_ALL=en_US.UTF-8 lein swank).