通用工具用于去除各种语言源代码中的所有注释?
我在找一个命令行工具,可以从输入文件中删除所有注释,然后返回去掉注释后的内容。最好这个工具能支持一些常见的编程语言,比如C、C++、Python、PHP、JavaScript、HTML、CSS等等。这个工具需要能够理解语法,而不是仅仅用正则表达式,因为后者会把源代码字符串中的模式也抓到。
我知道注释是有用的信息,通常保留它们是个好主意。不过我现在关注的是不同的使用场景。
6 个回答
3
你想要的功能可以通过emacs脚本来实现。
我为你写了这个脚本,它正好满足你的需求,而且可以很容易地扩展到其他编程语言。
文件名:kill-comments
#!/usr/bin/python
import subprocess
import sys
import os
target_file = sys.argv[1]
command = "emacs -batch -l ~/.emacs-batch " + \
target_file + \
" --eval '(kill-comment (count-lines (point-min) (point-max)))'" + \
" -f save-buffer"
#to load a custom .emacs script (for more syntax support),
#use -l <file> in the above command
#print command
fnull = open(os.devnull, 'w')
subprocess.call(command, shell = True, stdout = fnull, stderr = fnull)
fnull.close()
使用这个脚本只需要调用:
kill-comments <file-name>
如果想要添加其他语言,只需编辑你的~/.emacs-batch文件,加入该语言的主要模式。你可以在http://www.emacswiki.org找到几乎所有你想要的语法高亮模式。
作为示例,这里是我的~/.emacs-batch文件。它扩展了上面的脚本,用于从javascript文件中移除注释。(我在我的~/.el目录中有javascript.el)
(setq load-path (append (list (concat (getenv "HOME") "/.el")) load-path))
(load "javascript")
(setq auto-mode-alist (cons '("\\.js$" . javascript-mode) auto-mode-alist))
加上javascript的功能后,这个脚本会从你提到的所有文件类型中移除注释,还有很多其他类型的文件。
祝你好运,编码愉快!
0
目前还没有这样的工具。