#include Once "window9.bi"

Function Linelengtheditor(Byval gadget As Long, Byval index As Integer=-1) As Integer
	
	Dim As GtkTextBuffer Ptr  buffer
	
	Dim As GtkTextIter iterindex  , iter1 , iter2 , itersel1 ,_
	itersel2 , iterstarttext , iterendtext
	
	Dim As gint char_offset1 , char_offset2 , iLineCount , _
	iLenStr , iLenSelect , iLenAllText

	buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW( Gadgetid(gadget) )) 
	
	iLineCount = gtk_text_buffer_get_line_count (buffer) 
	
	gtk_text_buffer_get_selection_bounds(buffer,@itersel1,@itersel2) 
	
	Dim As String szText = *gtk_text_iter_get_text(  @itersel1, @itersel2 )
	
	If Len(szText) Then
		
		szText = Replacestring(szText , Chr(10) , "" , ,1)
		
		szText = Replacestring(szText , Chr(13) , "" , ,1)		
		
	Endif

	iLenSelect = Len(szText) 
	
	If index <> -1 Then
		
		gtk_text_buffer_get_iter_at_offset(buffer, @iterindex, index) 
		
		gtk_text_buffer_get_iter_at_offset(buffer, @iterstarttext, 0) 
		
		char_offset1 = gtk_text_iter_get_line(@iterindex) 
		
		char_offset2  = char_offset1 + 1 
		
	Else
	
		char_offset1 = gtk_text_iter_get_line(@itersel1) 
		
		char_offset2 = gtk_text_iter_get_line(@itersel2) + 1 
		
	Endif
	
	If (iLineCount - char_offset1) < 1 Then Return 0 

	gtk_text_buffer_get_iter_at_line(buffer , @iter1, char_offset1) 

	If (iLineCount - char_offset1)  = 1 Then 
		
		gtk_text_buffer_get_end_iter(buffer , @iter2) 
		
		iterendtext = iter2 
	
	Elseif index  = -1 Andalso (iLineCount - char_offset2)  = 0 Then 
	
		gtk_text_buffer_get_end_iter(buffer , @iter2) 
		
		iterendtext = iter2 
		
	Elseif (iLineCount - char_offset1)  > 1 Then
		
		gtk_text_buffer_get_iter_at_line(buffer , @iter2, char_offset2) 
		
		gtk_text_buffer_get_end_iter(buffer , @iterendtext) 

	Endif

	If index <> -1 Then
		
		iLenStr = Len(Trim(*gtk_text_iter_get_text( @iter1, @iter2 ), Any Chr(13) & Chr(10)))
		
		iLenAllText = Len(Trim(*gtk_text_iter_get_text( @iterstarttext, @iterendtext ), Any Chr(13) & Chr(10)))
		
		If iLenAllText < index Then
			
			Return 0
			
		Else
		
			Return iLenStr
			
		Endif

	Else

		szText = *gtk_text_iter_get_text( @iter1, @iter2 )
		
		If Len(szText) Then
			
			szText = Replacestring(szText , Chr(10) , "" , ,1)
			
			szText = Replacestring(szText , Chr(13) , "" , ,1)		
			
		Endif		

		iLenStr = Len(szText)

		Return iLenStr - iLenSelect
		
	Endif

End Function