Sublime Forum

Replacing \n with actual newline

#1

Hello,

I was looking at the plugin API, because I need to make a simple plugin that uses a regex to search for \n and replace it with an actual new line, only for .json files. Can anyone help me on this? It would also be nice to have this happen automatically when opening a .json file

0 Likes

#2

This will replace \n with an actual newline:

import sublime, sublime_plugin

class TestCommand ( sublime_plugin.TextCommand ):

	def run ( self, edit ):

		view    = self.view
		query   = "\\n" # backslash is escaped to send a literal backslash
		newLine = "\n"

		queryRegions = view.find_all ( query, sublime.LITERAL ) # literal flag is used to disable regex

		for region in reversed ( queryRegions ): # use reverse region order to avoid displacing regions with previous replacements
			view.replace ( edit, region, newLine )

As far as having it happen automatically when opening a .json file, you’d probably have to:

  • set up an Event Listener
  • use: window.extract_variables () ["file_extension"]
0 Likes

#3

Thanks for your help! It was much appreciated :slight_smile:

1 Like