简体   繁体   English

Notepad ++自动检测Python选项卡或空格

[英]Notepad++ Automatic Detection of Python Tabs or Spaces

I normally write code with tabs but many python libraries use spaces. 我通常使用制表符编写代码,但许多python库使用空格。 Is there any way for Notepad++ to automatically detect how the file is formatted and have it automatically switch to using spaces when the file is already formatted that way? Notepad ++是否有任何方法可以自动检测文件的格式,并在文件已经格式化时自动切换到使用空格?

BTW, I know there was already an SO question on how to change Notepad++'s tab format. 顺便说一句,我知道如何改变Notepad ++的标签格式已经有了一个问题 But it would be better if it automatically changed based on the current file's formatting. 但如果它根据当前文件的格式自动更改会更好。

If you install the "Python Script" plugin for Notepad++, you can write code to automatically switch between tabs and spaces. 如果为Notepad ++安装“Python Script”插件,则可以编写代码以自动在选项卡和空格之间切换。

Here's how: 这是如何做:

  1. In the menu: Plugins -> Python Script -> Configuration, and set Initialization to ATSTARTUP. 在菜单中:插件 - > Python脚本 - >配置,并将初始化设置为ATSTARTUP。 When Notepad++ starts, the startup.py script will run. 当Notepad ++启动时,将运行startup.py脚本。

  2. Find startup.py and edit it. 找到startup.py并进行编辑。 On my PC its path is c:\\Program Files\\Notepad++\\plugins\\PythonScript\\scripts\\startup.py , add the following code to startup.py . 在我的PC上它的路径是c:\\Program Files\\Notepad++\\plugins\\PythonScript\\scripts\\startup.py ,将以下代码添加到startup.py

The function buffer_active() is called every time when you switch tab, and guess_tab() checks whether the text is using tab indent or not. 每次切换选项卡时都会调用函数buffer_active()guess_tab()检查文本是否正在使用制表符缩进。 You can show the Python console to debug the code. 您可以显示Python控制台以调试代码。

def guess_tab(text):
    count = 0
    for line in text.split("\n"):
        indents = line[:len(line)-len(line.lstrip())]
        if "\t" in indents:
            count += 1
    if count > 5: 
        return True
    else:
        return False

def buffer_active(arg):
    editor.setBackSpaceUnIndents(True)
    use_tab = guess_tab(editor.getText())
    editor.setUseTabs(use_tab)
    sys.stderr.write( "setUseTabs %s\n" % use_tab )

notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED])    
notepad.callback(buffer_active, [NOTIFICATION.BUFFERACTIVATED])

This is only an example, feel free to make guess_tab() better yourself, maybe use a global dict to cache the result and speedup the callback function. 这只是一个例子,随意使guess_tab()更好,也许使用全局dict来缓存结果并加速回调函数。

Here is an improved version based on HYRY's answer : 这是基于HYRY答案的改进版本:

  • Works on the startup tab (when you launch notepad++ to open a file) 在启动选项卡上工作(当您启动notepad ++以打开文件时)
  • Doesn't need a minimal amount of rows to trigger indentation detection. 不需要最少量的行来触发缩进检测。 Indentation guess is based on the first encountered indented line. 缩进猜测是基于第一个遇到的缩进行。
  • Keeps indentation defaults when indentation cannot be detected 当无法检测到缩进时,保留缩进默认值
  • Very efficient, doesn't slow down Notepad++ when opening big files (tested on a 220 MB file, indentation detection takes only < 300 ms) 非常高效,打开大文件时不会减慢Notepad ++的速度(在220 MB文件上测试,缩进检测只需<300 ms)

Available for download here : https://gist.github.com/vincepare/8a204172d959defb2122 可从此处下载: https//gist.github.com/vincepare/8a204172d959defb2122

import re
import time

def indent_guess_tab(text):
    for line in text.split("\n"):
        pattern = re.compile("^( {4,}|\t)")
        match = pattern.match(line)
        if (match):
            return True if ("\t" in match.group(1)) else False

def indent_auto_detect(arg):
    start = time.clock()

    # Get text sample
    maxLen = 500000
    len = editor.getTextLength()
    len = len if len < maxLen else maxLen
    sample = editor.getTextRange(0, len)

    # Indent set
    current_use_tab = editor.getUseTabs()
    use_tab = indent_guess_tab(sample)

    if (use_tab != None and use_tab != current_use_tab):
        console.write("Indent use tab switch (%s => %s)\n" % (current_use_tab, use_tab))
        editor.setUseTabs(use_tab)

    end = time.clock()
    console.write("Indentation detection took %s ms\n" % (round((end-start)*1000, 3)))

notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED, NOTIFICATION.READY])    
notepad.callback(indent_auto_detect, [NOTIFICATION.BUFFERACTIVATED])
notepad.callback(indent_auto_detect, [NOTIFICATION.READY])
console.write("Automatic indentation detection started\n")
indent_auto_detect(None)

Nope! 不!

You can always just change them (to tabs , of course) to suit your needs with Replace All ( 您可以随时更改它们(当然是更改标签 )以满足您的需求(全部替换)      , \\t ) in extended mode. \\t )在扩展模式下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM