如何获取Gedit插件中当前行的长度(或行尾的偏移量)

时间:2011-11-18 02:13:56

标签: python gtk pygtk gedit

在用Python编写的Gedit插件中,我可以用

获取当前行开头的偏移量
document = window.get_active_document()
offset = document.get_iter_at_mark(document.get_insert())

我怎样才能获得同一行结尾的偏移量?目前我正在使用一种解决方法:我得到下一行的偏移量并从中减去所需行的偏移量,然后减去1(对于最后一行处理特殊情况)。有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

有点晚了,我知道,但迟到总比没有好。我正在运行gedit 3.2.3,我不知道这些东西从一个版本到另一个版本有多大变化,但这对我有用:

line_types = {"cr-lf": '\r\n',
              "lf": '\n',
              "cr": '\r'}
document = window.get_active_document()
newline = line_types[document.get_newline_type().value_nick]
insert_mark = document.get_insert()
offset = document.get_iter_at_mark(insert_mark)
line = offset.get_line()
# we subtract 1 because get_chars_in_line() counts the newline character
# there is a special case with the last line if it doesn't have a newline at the end
# we deal with that later
line_length = offset.get_chars_in_line() - len(newline)
end_of_line = document.get_iter_at_line_offset(line, line_length)
if end_of_line.get_char() != newline[0]:
    end_of_line = document.get_iter_at_offset(end_of_line.get_offset()+len(newline))
# if the above code is correct this should select from the current insert point
# to the end of line
document.move_mark(insert_mark, end_of_line)

编辑1:未考虑文件未被换行符

终止的情况

编辑2:考虑行尾的不同定义

PS:无论这个或你当前的解决方案是“更干净”还是“更好”,我不知道,我猜这是主观的。

相关问题