Sublime Forum

ScrollOff: set minimum number of lines above/below cursor

#1

I had some free time today so finally got around to writing a plugin I requested awhile back. This plugin artificially narrows the viewport such that scrolling up or down near the boundaries causes the visible region to change. This emulates the behavior of the vim scrolloff setting.

Add to your Key Bindings – User:

/* Scrolloff keybinds */ { "keys": "up"], "command": "scroll_off", "args": { "forward": false } }, { "keys": "down"], "command": "scroll_off", "args": { "forward": true } },

Add to your Settings – User: (Optional, defaults to 5)

"scrolloff": <positive integer>

Save as Packages/User/ScrollOffCommand.py:

[code]import sublime, sublime_plugin

class ScrollOffCommand(sublime_plugin.TextCommand):
def run(self, edit, forward):
self.view.run_command(“move”, {“by”: “lines”, “forward”: forward})

    limit = abs(int(self.view.settings().get("scrolloff"))) or 5

    cursor = self.view.rowcol(self.view.sel()[0].begin())[0]
    view_top = self.view.rowcol(self.view.visible_region().begin())[0]
    view_bottom = self.view.rowcol(self.view.visible_region().end())[0]

    absolute_bottom = self.view.rowcol(self.view.size())[0]

    if cursor < view_top + limit:
        self.view.set_viewport_position((0, (view_top - 1) * self.view.line_height()))
    elif cursor <= absolute_bottom - limit and cursor >= view_bottom - limit:
        self.view.set_viewport_position((0, (view_top + 1) * self.view.line_height()))

[/code]

Note that I opted to override the default up/down keybindings to avoid headaches with mouse selection and cursor jumping via CTRL+Home, CTRL+End, etc.

There is some strange behavior I don’t know how to sort out. For instance, the cursor moves faster than the viewport for long scrolls, so the scrolloff limit isn’t maintained. I’ve also had a few files where the cursor reaches the viewport bottom boundary when there is still content in the file (ie, not the absolute_bottom) . If anyone is willing to look into these issues I’d appreciate it. :smile:

0 Likes

#2

I wish I’d seen your previous post! I wrote a similar plugin a while back.
github.com/SublimeText/ScrollOffset
Clever to override the arrows to fix mouse-selections, though. I tried capturing the mouse events instead but had trouble getting something workable.

0 Likes

#3

Simple and effective. I love it.
This is worthy of a package.

0 Likes

#4

I just wanted to say I’m using this and it’s working well for me, thanks!

If you’re interested, some suggestions I have are:

  • take the setting “scroll_past_end” into account and if it’s true then scroll past the end of the file
  • if the caret is moving away from the edge of the view (e.g. the caret is near the bottom of the view and is moved upwards) and the caret is less than the scrolloff setting then don’t do any scrolling (maybe this is just my personal preference)
  • add it to package control

Thanks!

0 Likes