Copyright ©2010 by John Cawley III. This document may be freely copied,
distributed and archived provided it is copied entire and unmodified and the
copyright statement remains intact.
Last modified: 2010-03-12. The current version of this document is available at
http://www.Thistlehaven.net/J3.
Email comments and questions about this document to j3@pobox.com.
This short note addresses a fix I had to make to some LUA code commonly found on the web to work correctly with my SciTE configuration.
The SciTE editor (see http://www.scintilla.org/SciTE.html) is an excellent text editor based on the Scintilla control (see http://www.scintilla.org/) by Neil Hodgson and others. The macro/extension language that it normally uses is LUA.
If you search for sample LUA code to use with SciTE on the web, you will find snippets that will recenter a given line in the editor window – for instance the code below from http://lua-users.org/wiki/UsingLuaWithScite:
-- this centers the cursor positionfunction center_pos(line)if not line then
-- this is the current lineline = editor:LineFromPosition(editor.CurrentPos)
end local top = editor.FirstVisibleLine local middle = top + editor.LinesOnScreen/2editor:LineScroll(0,line - middle)
end
This code, however, frequently (but not always) centered the wrong line in my documents, sometimes being off by multiple pages of text.
It finally became annoying enough that I hunted down the cause of the misbehavior, and share it now in case it helps anyone else.
The trouble presumably came from the fact that I have SciTE configured to wrap lines (wrap=1 and wrap.indent.mode=2 in SciTEGlobal.properties), since I tracked the trouble down to points in the file after which lines are wrapped – each “virtual wrapped line” threw the vertical centering off by one line. It looks like the editor.FirstVisibleLine function returns a number from “visible line space” of the document, while editor:LineScroll requires a number from “document line space”.
The solution is to make use of the function editor:DocLineFromVisible, which takes a value from “visible line space” and maps it to a value from “document line space”. This fix is shown in the code below and does indeed make the vertical recentering function work correctly now for my SciTE configuration:
function Recenter( line )
if not line then
line = editor:LineFromPosition( editor.CurrentPos )
end
local top = editor:DocLineFromVisible( editor.FirstVisibleLine )
local middle = top + editor.LinesOnScreen/2
editor:LineScroll( 0, line-middle )
end
Keywords: SciTE, Scintilla, editor.FirstVisibleLine, editor:LineScroll, editor:DocLineFromVisible, recenter, center_pos