Search code examples
word-wrapscite

Reformatting text (or, better, LaTeX) in 80 colums in SciTE


I recently dived into LaTeX, starting with the help of a WYSIWYM editor like Lix. Now I'm staring writing tex files in Sci-TE, It already has syntax higlighting and I adapted the tex.properties file to work in Windows showing a preview on Go [F5]

One pretty thing Lyx does, and it's hard to acheive with a common text editor, is to format text in 80 columns: I can write a paragraph and hit Return each time I reach near the edge column but if, after the first draft, I want to add or cut some words here and there I end up breaking the layout and having to rearrange newlines.

It would be useful to have a tool in Sci-TE so I can select a paragraph of text I added or deleted some words in and have it rearranged in 80 columns. Probably not something working on the whole document since it could probably break some intended anticipated line break.

Probably I could easily write a Python plugin for geany, I saw vim has something similar, but I'd like to know if its' possible in Sci-TE too.


Solution

  • I was a bit disappointed when I found no answer as I was searching for same. No helpers by Google either, so I searched for Lua examples and syntax in a hope to craft it myself. I don't know Lua so this can perhaps be made differently or efficiently but its better then nothing I hope - here is Lua function which needs to be put in SciTE start-up Lua script:

    function wrap_text()
    
        local border = 80
        local t = {}
    
        local pos = editor.SelectionStart
        local sel = editor:GetSelText()
        if #sel == 0 then return end
    
        local para = {}
        local function helper(line) table.insert(para, line) return "" end
        helper((sel:gsub("(.-)\r?\n", helper)))
    
        for k, v in pairs(para) do
            line = ""
            for token in string.gmatch(v, "[^%s]+") do
                if string.len(token .. line) >= border then
                    t[#t + 1] = line
                    line = token .. " "
                else
                    line = line .. token .. " "
                end
            end
            t[#t + 1] = line:gsub("%s$", "")
        end
    
        editor:ReplaceSel(table.concat(t, "\n"))
        editor:GotoPos(pos)
    
    end
    

    Usage is like any other function from start-up script, but for completness I'll paste my tool definition from SciTE properties file:

    command.name.8.*=Wrap Text
    command.mode.8.*=subsystem:lua,savebefore:no,groupundo
    command.8.*=wrap_text
    command.replace.selection.8.*=2
    

    It does respect paragraphs, so it can be used on broader selection, not just one paragraph.