Sublime Forum

Is it possible to manipulate text this way?

#1

HI,

I usually manipulate text-files and for that I have a python-script in place.

But that requires reading and writing interim files – and I would like to do that within the Sublime Text editor:

The flow:

def read_file(ifn):
  ifp = open(ifn, 'r')
  sleep(0.5)
  #-- reset the buffer
  ilines=[]
  for each_line in ifp:
    lcnt += 1
    #-- strip endof line 
    my_line = (each_line.rstrip('\n'))
    ilines.append(my_line)
  #-- pass back to main
  return ilines


def do_my_stuff(inlines):
  outlines=[]
  #--
  return outlines
def write_file(ofn, wlines):
  ofp = open(ofn, 'w')
  sleep(0.5)
  for wline in wlines:
    ofp.write(wline + "\n")
  ofp.close()
  sleep(0.5)
  return 1

##
##-- MAIN
##
readlines=read_file('my_input_file.txt')
processedlines=do_my_stuff(readlines)
dummy=write_file('my_output_file', processedlines)

In Sublime Text I want to:

Select all contents of the active document
Make the buffer into a list
Pass that list to ‘do_my_stuff()’
Overwrite the complete content of the active document with the output.

0 Likes

#2

Here’s a plugin template for you.

from __future__ import annotations

import sublime
import sublime_plugin


def do_my_stuff(content: str) -> str:
    # ...
    return content


class MyViewContentReplaceCommand(sublime_plugin.TextCommand):
    def run(self, edit: sublime.Edit) -> None:
        buffer_region = sublime.Region(0, self.view.size())

        content = self.view.substr(buffer_region)
        content = do_my_stuff(content)

        self.view.replace(edit, buffer_region, content)

The run method in MyViewContentReplaceCommand can be called with my_view_content_replace command.

1 Like

#3

Hi jfcheng, thank you very much!

0 Likes