Welcome, guest | Sign In | My Account | Store | Cart

This recipe is based off of http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061

I found and used the recipe above, however, I took issue with the results. See, I wanted to use it on a big Java file that had lots of long lines. With extra long package names, and extra long lines containing multiple semicolons without spaces after them, I found it necessary to modify this algorithm to suit my specific purposes.

If you have a line like this:

import com.jobsintheus.vaccinium.controller.ejb.stateful.VacciniumStatefulSessionRemoteHome;

you're going to have problems using the above algorithm, but the one herein does something useful with that - splitting the line on the periods too. It works for semicolons too.

Inserted line breaks will become the visible backslash charater plus the line break.

Otherwise, line breaks that existed before stay as is (with no visible backslash character).

The point is to have the Java code be a readable addition as an input file to (la)tex verbatim.

Python, 40 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import string
def wrap(text, width):
    """
    A word-wrap function that preserves existing line breaks
    and most spaces in the text. Expects that existing line
    breaks are posix newlines (\n).

    Inserted newlines will appear with a backslash instead.
    """
    return string.replace(string.replace(string.replace(string.replace(
            string.replace(
             reduce(
                lambda line,
                word,
                width=width: '%s%s%s' %
                  (line,
                   ' \n'[(len(line)-line.rfind('\n')-1 +
                     len(word.split('\n',1)[0]) >= width)],
                   word),
                  string.replace(string.replace(
                                string.replace(text,
                                         ".",
                                         ".___MARK "),
                                 ";",
                                 ";___MARK "),
                        "\n",
                        "___EOL ").split(' ')
                 ),
            "___MARK ", ""),
           "___MARK", ""),
        "\n", "\\\n"),
        "___EOL\\\n", "\n"),
       "___EOL ", "\n")

f=open('MyClass.java', 'r') #REPLACE MyClass.java with filename
msg = ""
for line in f:
        msg = msg+line

print(wrap(msg,70))

I understand that this is pretty inefficient, and know there is probably a more elegant solution, but it does what I wanted.

Created by Christopher Morley on Fri, 30 Sep 2005 (PSF)
Python recipes (4591)
Christopher Morley's recipes (1)

Required Modules

Other Information and Tasks