I would like to create some tools for the text editor, for example, I would like to create at this moment a small operator that taking the selected text, transforms it into all lowercase or all uppercase text, in short, a simple thing like

txt = txt.upper()
txt = txt.lower()

I would have many tools to create for convenience, but I am not familiar with how to interact with this workspace


Here is an example of a script that makes the currently selected piece of text uppercase. So the main thing here is the Text object of the space data which also has some other attributes you can use. The SpaceTextEditor might also have some usefull functions.

import bpy
text = bpy.context.space_data.text
fschar = text.current_character
fsline = text.current_line_index
fechar = text.select_end_character
feline = text.select_end_line_index

# The end and start lines and characters can be switched
# depending on the direction in which the text was selected
schar = min(fschar,fechar)
echar = max(fschar,fechar)
sline = min(fsline,feline)
eline = max(fsline,feline)

original_text = text.as_string()
lines = original_text.split("\n")

for line in range(sline, eline + 1):
    cur_line = lines[line]
    start_char = 0
    end_char = len(cur_line)
    if line == sline:
        start_char = schar
    if line == eline:
        end_char = echar
    # Uppercase the selected part of this line
    new_line = "".join((cur_line[:start_char], cur_line[start_char:end_char].upper(), cur_line[end_char:]))
    lines[line] = new_line
new_text = "\n".join(lines)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.