Sublime 3; How to accurately count characters when both CR and LF are present in line termination

5.8k Views Asked by At

When editing a text file, the default character-counting function in Sublime 3 counts a newline as one character, irrespective of whether the line ends in LF or CR,LF. I cannot find a setting to give me the correct count for a text file with CR,LF line endings.

I've tried installing the WordCount package, but it has the same issue. Setting the preference

char_ignore_whitespace : true

does not change the behaviour.

One could argue that Sublime's behaviour is incorrect since (for the files I am working with) the newline constitutes two characters, not one.

The reason I would like the count to include the CR in the character count (i.e. a newline is 2 characters) is so that I can use Sublime to help debug some code that is using ftell/fseek. As it stands, I have to keep adding the line count to the character count to get the correct byte position in the file (when selecting all text from the beginning of the file to the point of interest).

Is there a setting I am missing? Is there a different package that can be used?

EDIT: I noticed that Notepad++ correctly reports the character count for such files, but I prefer to use Sublime :)

EDIT2: I found some code here (Is it possible to show the exact position in Sublime Text 2?) that works in Sublime 3, but also counts two-character newlines incorrectly.

1

There are 1 best solutions below

0
On

I modified the code in the link above to crudely compensate the the missing end-of-line counts. The code below simply adds the number of lines (zero-based) to the character position and displays this as an alternative position (in case a unix-style file is open, in which case the compensation is not required).

This is admittedly crude, and not intelligent enough to determine what type of line ending the file has. Maybe someone else has a better idea?

import sublime, sublime_plugin

class PositionListener(sublime_plugin.EventListener):
  def on_selection_modified(self,view):
    text = "Position: "
    sels = view.sel()
    for s in sels:
        if s.empty():
            row, col = view.rowcol(s.begin())
            text += str(s.begin())
            text += " [" + str(s.begin() + row) + "]"
        else:
            text += str(s.begin()) + "-" + str(s.end())
            row, col = view.rowcol(s.begin())
            text += " [" + str(s.begin() + row) + "-"
            row, col = view.rowcol(s.end())
            text += str(s.end() + row) + "]"
    view.set_status('exact_pos', text)