Sublime Forum

Offset region by line_height (request for improving code)

#1

I want to offset a single region up or down by a mutiple of line_height (called region and offset, respectively, in the code below).

The only way I’ve managed to do so is to go from region > point > layout, offset the layout, and then go back again. It works just fine but it’s not very elegant. Here’s what it looks like:

region_a    = list(view.text_to_layout(region.a))
region_b    = list(view.text_to_layout(region.b))
region_a[1] = region_a[1] + offset
region_b[1] = region_b[1] + offset
region      = sublime.Region(view.layout_to_text(region_a), view.layout_to_text(region_b))

I’m looking for gentle (or not so gentle) suggestions for improvement in either my python or use of the API :blush:.

Thanks,
Alex

0 Likes

#2

I had a chance to improve my crummy code slightly:

github.com/alehandrof/Typewrite … py#L28-L35

But there’s still a lot of repetition, and I can’t figure out how to do it better.

0 Likes

#3

Repetition isn’t always a bad thing, and sometimes your algorithm just requires it; that is why you functionalize repetitious code so you can just call the the function instead of copying and pasting the code over and over.

You can’t always help repetitious code. Your script is so small anyways, and it seems you have functionlized the repetitious code. Someone will always be able to tell you how they “feel” your code could be changed to be better, sometimes it is actually true, some times it is just opinion.

The big thing I would say, is take your “offset” variable which is global and define it at the top of your script. That way it is clear it is global, and someone coming in behind you doesn’t have to search functions looking for the global term to find out it is in fact a global function and you didn’t just forget to define it.

Some people even go further and do things like g_offset or gOffset to denote globals; again it is all personal preference, but globals are always a pain to identify, so at least list them at the beginning of the script to make it easier to tell they are global. In a small script like this, it isn’t a big deal, but as scripts get larger, it is nice to be able to look at the top of the script and tell what variables are global.

0 Likes

#4

Thanks for taking the time to comment. It’s much appreciated.

I was indeed a little confused at to how to handle the global variable. I will follow your suggestion.

I’ve read a bit of a python manual/tutorial, but I get impatient. Consequently, good etiquette is sometimes lacking in my work.

I am currently refactoring a gigantic LESS codebase I wrote in a two-week frenzy to learn the syntax, which (alas!) has made it to production. I give myself headaches :unamused:

0 Likes