-- Notecase Pro sample script (requires Notecase Pro >= 3.1.6)
--
-- Description:
-- Wrap selected note text to have maximal line length of 60 letters, center the text too
-- 
-- This script's author, Miroslav Rajcic, hereby waives all copyright 
-- and related or neighboring rights to this script, pursuant to the
-- Creative Commons CC0 Universal relinquishment of rights found at
-- http://creativecommons.org/publicdomain/zero/1.0/ 

-- make sure app version supports necessary scriptable program commands
nMaj, nMin, nRev = Nc_Config_GetAppVersion()
if (nMaj < 3 or (nMaj == 3 and nMin < 1) or (nMaj == 3 and nMin == 1 and nRev < 6)) then
	Nc_GUI_MessageBox("ERROR: Script requires NcPro version >= 3.1.6")
	return
end

-- maximal line length (change this to get lines of different length)
nWrappingSize = 60

-- get info on the currently active document/note
nDocID = Nc_Doc_ID_GetCur()
strCurNoteID = Nc_Note_ID_GetCur(nDocID)

if strCurNoteID == "" then
 	Nc_GUI_MessageBox("No note selected, aborting")
	return 
end

nFrom, nTo = Nc_Note_SelectionRange_Get(nDocID, strCurNoteID)
strText = Nc_Note_Content_Get(nDocID, strCurNoteID, 0, nFrom, nTo)

-- start offset is lower out of the two offsets
nStart = nFrom
if nStart > nTo then
 nStart = nTo
end

-- remove existing line break characters
strText = string.gsub(strText, "\n", " ") 

-- now insert breaks every ZZZ characters
nPos = nWrappingSize
nLen = string.len(strText)
nStartPos = 0
nLine = 1

while nPos < nLen do

	-- find good place to make a line break (between the words)
	while nPos > nStartPos do
	  strChar = string.sub(strText, nPos, nPos)
		if strChar ~= " " then
			nPos = nPos - 1
		else
		  -- break line at the position of the space character being found
			break			
		end
	end
	if nPos == nStartPos then
		-- no place to make a break found, do brute force break at the max line size
		nPos = nStartPos + nWrappingSize
	end

	-- insert new line character into the proper position
	strText = string.sub(strText, 1, nPos) .. "\n" .. string.sub(strText, nPos+1)
	nLen = nLen + 1
	nStartPos = nPos
	nPos = nPos + nWrappingSize + 1
	nLine = nLine + 1
end

-- write text back (overwriting the old text)
Nc_Note_Content_Set(nDocID, strCurNoteID, strText, 0, nFrom, nTo)

-- center and select the new text
nLen = string.len(strText)
Nc_Note_Format_Align_Center_Apply(nDocID, strCurNoteID, nStart, nStart + nLen)
Nc_Note_SelectionRange_Set(nDocID, strCurNoteID, nStart, nStart + nLen)