backwardsScanInBufferRange not working


#1

Hi,

I am trying to find a number string by scanning the text buffer backwards. My first code was this and it was working:

getSubtitleId(editor, range)
{
	let subtitleId;

	// Start the range 4 rows earlier
	if (range.start.row - 4 > 0)
		range.start.row = range.start.row - 4;
	else
		range.start.row = 0;

	editor.backwardsScanInBufferRange(new RegExp('^\\d+$'), range, (iterator) =>
	{
		iterator.stop();
		subtitleId = iterator.match;
	});

	return subtitleId;
},

However when I was going over it once again, I noticed that I was changing permanently the start row of the range variable: range.start.row = range.start.row - 4;

To stop this, I changed my code so that I began working with a copy of the original range object, by using: let rangeCopy = range.copy();

getSubtitleId(editor, range)
{
	let subtitleId;
	let rangeCopy = range.copy();

	// Start the range 4 rows earlier
	if (rangeCopy.start.row - 4 > 0)
		rangeCopy.start.row = rangeCopy.start.row - 4;
	else
		rangeCopy.start.row = 0;

	editor.backwardsScanInBufferRange(new RegExp('^\\d+$'), range, (iterator) =>
	{
		iterator.stop();
		subtitleId = iterator.match;
	});

	return subtitleId;
},

Since I made the change, my function is no longer working and I can’t tell why. Could you help me?


#2

What type is range? Atom passes around “range-compatible arrays” for lots of things and when using [[0, 0], [Infinity, Infinity]].copy(), I get an exception.


#3

Hi,

range is of the type Range, the standard Range object that Atom passes around. This particular one came from a TextBuffer.Scan method.

I just used the standard copy method that is mentioned on the documentation.

I’ve also ran the code with a debugger and the start and end points of both the original range and the rangeCopy objects are the same.

Thanks,
Felipe


#4

Hi,

I got it! It turns out it was a silly mistake: I forgot to import the Range object from Atom. So once I added import { Range } from 'atom'; to the begnning of the file, everything worked.

Below is the final code:

getSubtitleId(editor, range)
{
	let subtitleId;
	let rangeCopy = range.copy();

	// Start the range 4 rows earlier
	if (rangeCopy.start.row - 4 > 0)
		rangeCopy.start.row = rangeCopy.start.row - 4;
	else
		rangeCopy.start.row = 0;

	editor.backwardsScanInBufferRange(new RegExp('^\\d+$'), rangeCopy, (iterator) =>
	{
		iterator.stop();
		subtitleId = iterator.match;
	});

	return subtitleId;
},