上篇文章介绍了单行注释(“//”)宏的实现,这里介绍多行注释(“/**/”)宏的实现。
由于/* ... */ 的注释出现的情况较复杂,大家可以根据自己需要进行修改,这里只将第一非空行,且以“/*”开头的文本(忽略空格)视为要取消注释。
脚本中:
// while(line_index <= lnSelLast) // 对选中的内容进行操作
while(line_index < GetBufLineCount(hbuf)) //or 从当前行开始,查找到第一个“*/”为止或到结尾
决定了取消注释时是对选中内容进行操作,还是直到匹配到第一个“*/”为止进行的操作。
// 插入/* ... */ 形式的注释
// 多行注释,只对第一行非空行,且以“/*” 或是空格开头的取消注释,
//“/*”处于语句中间的,视为将对其进行注释
macro Comments_UnComments_With_Multiple()
{
hwnd = GetCurrentWnd()
hbuf = GetCurrentBuf()
if(hbuf ==0)
stop
// debugBuf只是为了调试
// debugBuf = NewBuf("debugBuf")
// ClearBuf(debugBuf)
lnSelFirst = GetWndSelLnFirst(hwnd) // 获得选中内容的第一行
lnSelLast = GetWndSelLnLast(hwnd) // 获得选中内容的最后一行
const_space = " " // 空格
const_comments_begin = "/*" // 多行注释符号-开始
const_comments_end = "*/" // 多行注释符号-结束
isCancelComments = 0
// 跳过开始的空行,否则下面报错
line_index = lnSelFirst
orig_text = GetBufLine(hbuf, line_index) // 获得第一行的text
while(strlen(orig_text) == 0)
{
line_index = line_index + 1
orig_text = GetBufLine(hbuf, line_index) // 获得下一行的text
}
// 根据第一行选中文本,确定是“注释”,还是“取消注释”
// 判断是否以“//”开始,如果是则认为是“取消注释”,首先需要去掉空格
subIndex = 0
while(strmid(orig_text, subIndex, subIndex+1) == const_space)
subIndex = subIndex + 1
if (strmid(orig_text, subIndex, subIndex+2) == const_comments_begin) // 以“/*”开头,取消注释
{
isCancelComments = 1
dest_text = strmid(orig_text, subIndex+2, strlen(orig_text))
if(strlen(dest_text) == 0)
{
DelBufLine(hbuf, line_index) // 本行只有“/*”时,删除
}
else
{
PutBufLine (hbuf, line_index, dest_text) // 替换以前的text
}
line_index = line_index + 1
}
else // 进行注释
{
InsBufLine(hbuf, lnSelFirst, "/*")
InsBufLine(hbuf, lnSelLast+2, "*/")
stop
}
// 遍历所有选中的行
// line_index = lnSelFirst // 前面已经跳过开头的空行
// while(line_index <= lnSelLast) // 对选中的内容进行操作
while(line_index < GetBufLineCount(hbuf)) //or 从当前行开始,查找到第一个“*/”为止或到结尾
{
orig_text = GetBufLine(hbuf, line_index) // 获得以前的text
if (strlen(orig_text) > 1) // 如果是空行或只有一个字符,则跳过
{
dest_text = ""
if(isCancelComments == 1) // 取消注释
{
// 查找注释符“*/”
subIndex = 0
while(subIndex < strlen(orig_text)-2 && strmid(orig_text, subIndex, subIndex+2) != const_comments_end)
subIndex = subIndex + 1
if (strmid(orig_text, subIndex, subIndex+2) == const_comments_end) // 找到“*/”,进行处理
{
prefixText = strmid(orig_text, 0, subIndex) // 前面的text
lastText = strmid(orig_text, subIndex+2, strlen(orig_text)) // 后面的text
dest_text = cat(prefixText, lastText)
if(strlen(dest_text) == 0)
{
DelBufLine(hbuf, line_index) // 本行只有“*/”时,删除
}
else
{
PutBufLine (hbuf, line_index, dest_text) // 替换以前的text
}
break // 退出
}
}
}
line_index = line_index + 1
}
}