Notepad++ 脚本:如何移除换行符?

2 投票
1 回答
1473 浏览
提问于 2025-04-16 20:05

我现在正在用PythonScript写一个非常简单的脚本,目的是在文本文件中支持基本的ASCII复选框。

我的计划是,当我按下Alt+F2时,编辑器会把[ ]变成[x],把[x]变回[ ],前提是这一行是以复选框开头的。如果不是的话,就在当前位置插入一个[ ]。

我写了一个脚本,它几乎可以正常工作……

from Npp import *
import string

# If the line starts with [ ] or [x] the script toggles the value between the two possibilites
# if the line doesn't contains [ ] the script adds the empty box at the current position
curLine = editor.getCurLine()
curPos = editor.getCurrentPos()
curLineNr = editor.lineFromPosition(curPos)
strippedLine = curLine.lstrip()

if (strippedLine.startswith('[ ]')):
    curLine = curLine.replace('[ ]', '[x]', 1).rstrip('\n')
    editor.replaceWholeLine(curLineNr, curLine)
    editor.gotoPos(curPos)
elif (strippedLine.startswith('[x]')):
    curLine = curLine.replace('[x]', '[ ]', 1).rstrip('\n')
    editor.replaceWholeLine(curLineNr, curLine)
    editor.gotoPos(curPos)
else:
    editor.addText('[ ] ')

但是这个脚本在替换编辑器中的行后,会多插入一个换行符。一个很笨的方法是删除新插入的那一行,但我其实不想一开始就插入它。

编辑:/搞定了。只需使用editor.replaceWholeLine方法,它就能完美运行。

1 个回答

2

使用 editor.replaceWholeLine 方法配合 editor.replaceLine 方法。

上面的脚本现在可以正常工作了。

撰写回答