Sublime Forum

[Proof Of Concept] Highlight Lines Longer Than A Certain Length

#1

Written in response to this StackOverflow Question
 

 



 
Useful Implementations:

  • verifies indentation character & adjusts region with proper indentation length if tab character is used

( regions lengths do not account for tabs, so they are not accurate to character count if tabs are used )
 



 

import sublime, sublime_plugin

class highlight_long_lines( sublime_plugin.EventListener ):
	def on_modified_async( self, view ):


		#▒▒▒▒▒▒▒▒  Settings  ▒▒▒▒▒▒▒▒#
		maxLength           = 80
		scope               = "Invalid"
		firstCharacter_Only = False



		view.erase_regions( "LongLines" )

		indentationSize     = view.settings().get( "tab_size" )
		indentation_IsSpace = view.settings().get( "translate_tabs_to_spaces" )

		document    = sublime.Region( 0, view.size() )
		lineRegions = view.lines( document )

		invalidRegions = []

		for region in lineRegions:

			text             = view.substr( region )
			text_WithoutTabs = text.expandtabs( indentationSize )

			if text_WithoutTabs.isspace():
				tabOffset = 0
			else:
				tabCount      = text.count( "	" )
				tabDifference = len( text_WithoutTabs ) - len( text )
				tabOffset     = tabDifference

			lineLength = ( region.end() - region.begin() ) - tabOffset
			if lineLength > maxLength:

				highlightStart = region.begin() + ( maxLength - tabOffset )

				if firstCharacter_Only == True:
					highlightEnd = highlightStart + 1
				else:
					highlightEnd = region.end()

				invalidRegion = sublime.Region( highlightStart, highlightEnd )
				invalidRegions.append( invalidRegion )

		if len( invalidRegions ) > 0:
			view.add_regions( "LongLines", invalidRegions, scope )
1 Like

#2

Or just set a ruler and see if text exceeds it.

(That’s also the wrong link.)

2 Likes

#3

 
True, dude said he found rulers distracting though.  Just burning some time on SO :grin:

 

 
Fixed, thanks :+1:

0 Likes

#4

Btw, he could also search for this regex: (?<=.{80}).+.

0 Likes

#5

 
Not lazy enough :stuck_out_tongue_winking_eye:

2 Likes

#6

A lot of people don’t realize you can do this in RegReplace without another plugin. Though it would be on save and not on modified.

                "long_lines":
		{
			"find": "(?m)(?<=^.{80}).+(?=$)",
			"name": "long_lines"
		},
    // on_save replacements
    "on_save_sequences": [
        // Highlight long lines
        {
            "file_pattern": ["*"],
            "sequence": ["long_lines"],
            "action": "mark"
        },
1 Like