作为一个开放源代码的操作系统,Linux附带的源代码库使得广大爱好者有了一个广泛学习、深入钻研的机会,特别是Linux内核的组织极为复杂,同时,又不能像windows平台的程序一样,可以使用集成开发环境通过察看变量和函数,甚至设置断点、单步运行、调试等手段来弄清楚整个程序的组织结构,使得Linux内核源代码的阅读变得尤为困难。
当然Linux下的vim和emacs编辑程序并不是没有提供变量、函数搜索,彩色显示程序语句等功能。它们的功能是非常强大的。比如,vim和emacs就各自内嵌了一个标记程序,分别叫做ctag和etag,通过配置这两个程序,也可以实现功能强大的函数变量搜索功能,但是由于其配置复杂,linux附带的有关资料也不是很详细,而且,即使建立好标记库,要实现代码彩色显示功能,仍然需要进一步的配置(在另一片文章,我将会讲述如何配置这些功能),同时,对于大多数爱好者来说,可能还不能熟练使用vim和emacs那些功能比较强大的命令和快捷键。
为了方便的学习Linux源程序,我们不妨回到我们熟悉的window环境下,也算是“师以长夷以制夷”吧。但是在Window平台上,使用一些常见的集成开发环境,效果也不是很理想,比如难以将所有的文件加进去,查找速度缓慢,对于非Windows平台的函数不能彩色显示。于是笔者通过在互联网上搜索,终于找到了一个强大的源代码编辑器,它的卓越性能使得学习Linux内核源代码的难度大大降低,这便是Source Insight3.0,它是一个Windows平台下的共享软件,可以从 上边下载30天试用版本。由于Source Insight是一个Windows平台的应用软件,所以首先要通过相应手段把Linux系统上的程序源代码弄到Windows平台下,这一点可以通过在linux平台上将/usr/src目录下的文件拷贝到Windows平台的分区上,或者从网上光盘直接拷贝文件到Windows平台的分区来实现。
下面主要讲解如何使用Source Insight,考虑到阅读源程序的爱好者都有相当的软件使用水平,本文对于一些琐碎、人所共知的细节略过不提,仅介绍一些主要内容,以便大家能够很快熟练使用本软件,减少摸索的过程。
安装Source Insight并启动程序,可以进入图1界面。在工具条上有几个值得注意的地方,如图所示,图中内凹左边的是工程按钮,用于显示工程窗口的情况;右边的那个按钮按下去将会显示一个窗口,里边提供光标所在的函数体内对其他函数的调用图,通过点击该窗体里那些函数就可以进入该函数所在的地方。
![图1 Source Insight界面图](http://www-128.ibm.com/developerworks/cn/linux/l-tip-prompt/tip17/1.jpg)
由于Source Insight实质上是一个支持多种开发语言(java,c ,c++等等)的编辑器,只不过由于其查找、定位、彩色显示等功能的强大,而被我们当成源代码阅读工具使用。所以,为了有效的阅读源程序,首先必须选择功能菜单上的 “Project”选项的子菜单“New Project”新建一个项目,项目名称可以自由选定,当然也可以选择删除(Remove)一个项目。当删除一个项目的时候,并不删除原有的源代码文件,只是将该软件生成的那些工程辅助文件删除。设定之后,将会弹出一个对话框如图2,接受默认选择,如果,硬盘空间足够,可以将第一个复选框选上,该选项将会需要与源代码大致同等的空间来建立一个本地数据库以加快查找的速度。
![图2 工程设置](http://www-128.ibm.com/developerworks/cn/linux/l-tip-prompt/tip17/2.jpg)
点击“OK”按钮,接受选择后,将会有一个新的对话框弹出,在这个对话框里,可以选择将要阅读的文件加入工程,一种方式是通过在File Name中输入要阅读源代码文件的名称,点击“Add”按钮将其加入,也可以通过其中“Add All”和“Add Tree”两个按钮可以将选中目录的所有文件加入到工程中,其中“Add All”选项会提示加入顶层文件和递归加入所有文件两种方式,而“Add Tree”相当于“Add All”选项的递归加入所有文件,可以根据需要使用,就我来说,更喜欢“Add Tree”一些。由于该程序采用了部分打开文件的方式,没有用到的文件不会打开,所以,加入数千个文件也不用担心加入的文件超出程序的所能容忍的最大值,我就是采用“Add Tree”的方式将Linux2.4内核的四千五百九十一个文件加入的。
![图3 添加文件](http://www-128.ibm.com/developerworks/cn/linux/l-tip-prompt/tip17/3.jpg)
加入文件后,点击一个文件,可以出现使用界面,如图4所示,其中,右边的那个窗口(Linux Project,即工程窗口)缺省按照字母顺序列出当前工程中所有的文件。
![图4 工作窗口](http://www-128.ibm.com/developerworks/cn/linux/l-tip-prompt/tip17/4.jpg)
点击一个文件就可以打开该文件,显示如图5所示,进入到右边的那个窗口分别可以以文件列表的方式,列出所有的文件,每个窗体下边有一排按钮,左边的窗口(21142.c)从左至右分别为:按字母顺序排列所有标记、按照文件中行数顺序排列标记、按照类型排列标记、浏览本地文件标记、标记窗口属性。右边的窗口(Linux Project)从左至右分别为:按字母顺序文件列表、显示文件夹、按照文件类型归类文件、全部文件的所有标记列表、按照标记类型归类标记、跳转到定义处、显示标记信息、浏览工程标记、查找函数调用、工程属性,其中全部文件的所有标记列表选项可能要一段时间抽取标记,同步到数据库去,如果开始选择了建立标记数据库,将会在今后节省同步时间,最有用的莫过于浏览标记信息和查找函数调用,前者可以通过“Jump”按钮在不同的地方查找同样的标志,还可以通过“Reference”按钮结合后者进行全局的标记查找。
![图五](http://www-128.ibm.com/developerworks/cn/linux/l-tip-prompt/tip17/5.jpg)
Reference功能是Source Insight的特色之一,它可以在速度极快的在整个工程中找到所有的标记,并且在该行程序的前边加上红色箭头的小按钮链接上。图6是一个Reference搜索后的结果,它可以有两种模式,一种集中显示结果,图6显示的就是这种模式,在这种模式下,可以通过前边的红色箭头小按钮进入另外一种模式,该标记的具体的所在处,也可以通过标记的具体所在处点击红色箭头小按钮进入警种模式,还可以通过工具条上的两个红色小箭头直接在第二种模式下前后移动,察看相应信息。它的这个强大的功能使得阅读Linux源程序有如神助。但是要注意的是,当进行了第二次“Reference”时,它会提示你将结果集附加在第一个结果集的后边还是取代第一个结果集。如果选择前者,不能对结果集根据前后两次搜索结果进行分类,然后在其子类里进行移动,只能在整个结果集里移动;如果,选择后者,结果集将会被替换为第二次搜索的结果,略微有些不方便。
![图6 Reference的搜索结果](http://www-128.ibm.com/developerworks/cn/linux/l-tip-prompt/tip17/6.jpg)
当然,Source Insight 还提供了一些其他常见的便利。比如:右键菜单几乎包含了程序的所有功能,可以在编辑窗口为程序加上行号,还可以统计整个工程的程序行数,当然还有功能强大却用不上自动完成功能,似乎连它的30天试用期也是别有用心――可以迫使你尽可能快速的阅读源程序,其他一些技巧大家可以在使用过程中慢慢摸索。怎么样?爱好读源代码的朋友,不妨马上去下载一个,去开始我们的Linux内核探险之旅吧
如果一个软件的文件数达到1000以上,那么对代码的管理和阅读将是一件比较困难的事情。在VC下,不得不安装Visual Assist软件,以提升阅读和编写代码的效率。
Source Insight是一款非常优秀的商业代码阅读和编写软件。在管理大型源码方面具有非常独到的优势。其最新版本,应该是3.5。因为是商业软件,一些正规的 大公司如果没有购买,是禁止使用的。以前在华为有人私自使用Source Insight,还被处罚。最后公司买了正版。
但Source Insight的缺省样式有时候觉得过于凌乱。看代码久了就累。而VC在装有Visual Assist的情况下,界面上面则好很多,舒服很多,但功能上还是赶不上Source Insight。以前传言微软要收购Source Insight。如果真是这样,那Visual studio将是史上最牛的集成开发环境。可惜比尔一直没有行动。虽然挖了Delphi的创始人,使VS2003以后,编程序轻松了不少。
既然比尔不行动,那我自己动手好了,把Source Insight配的和VC差不多,除了不能编译之外。 Source Insight的显示效果的确不太好。对中文支持也不好,所以经过我多次试验,才找到这比较好的方法。
1. 配置缺省字体。菜单Options->Document Options, 配置Screen Fonts为Arial 10 Bold。点Auto Indent按钮,Auto Indent Type选为Smart,将Indent Open Brace 和 Indent Close Brace复选框去掉,确认。这个时候字体具有了VC里面缺省的System字体的黑体效果。而且这种字体在Source Insight里面最美化,别的字体则比较难看。包括其缺省字体。Arial 10 Bold还能正常支持中文,这也是必须的。
2.配置关 键字颜色。点选菜单Options->Style Properties,设置样式。在Default Text样式,Foreground color选Pick,RGB填为0,0,128。这种藏青色比黑色舒服一点。同样,将Ref to local, Ref to parameter,Ref to member,Standard Object,Standard Property设为128,128,128的灰色。将Null value,Keyword,Ref to Class,Ref to struct,Ref to typedef,string都设为0,0,255。将Ref to macro,Ref to Const,Ref to Enum,Ref to EnumConst设为160,0,160;将Ref to Method, Ref to Method Proto,Ref to Proto,Ref to Func,Standard Function的颜色设为136,0,0的深红色,将Comment设为33,133,33的绿色。
3.微调颜色。如果看到关键字颜色不符合自己要求,在该关键字上点右键,在弹出菜单上有一个Style Properties,进去后就是对应的条目,可以设置其样式,通常是颜色。
4.保存。自己满意后,进入Style Properties后点Save 按钮,将其保存起来,甚至可以存到网上,以便下次使用和与朋友共享。1 sourceinsight screen font 的默认字体是Verdana的,它是一直变宽字体。在Document style中可以将字体改为定宽的Courier
2 勾掉indent Open Brace和Indent Close Brace的效果: 继上一段,在相对缩进行里, 如果输入"{"或"}", 则自动和上一行列对齐
3 今天把一个用sourceinsight排版整齐的C文件,偶然用VC打开一看,全乱了。研究了半天,发现SI对每个字符的宽度不太一致。
说明:
该宏文件实现一些编码程中能会到的功能, 如添加文件头、函数说明和宏定义等, 使用时能自动添加文件名、函数名和当前日期.
使用说明:
1. Project->Open Project... 打开Base工程(该工程一般在"我的文档\Source Insight\Projects\Base"中);
2. Project->Add and Remove Project Files... 加入宏文件(即mymacro.em);
3. Options->Menu Assignments 打开Menu Assignments窗口, 在Command中输入Macro, 选中要使用的宏, 添加到合适的菜单中.
在可以找到很多宏定义文件,但大多数没什么用。
/*附上宏定义文件(一下是我精心挑选的十分好用的宏定义,不试不知道,一试真有用)*/
/* mymacro.em - a small collection of useful editing macros */
/******************************************************************************
* InsFunHeader -- insert function's information
*
* modification history
* --------------------
* 01a, 23mar2003, added DESCRIPTION by t357
* 01a, 05mar2003, t357 written
* --------------------
******************************************************************************/
macro InsFunHeader()
{
// Get the owner's name from the environment variable: szMyName.
// If the variable doesn't exist, then the owner field is skipped.
/*#########################################################
#########################################################
####### Set szMyName variable to your name ########
####### for example szMyName = "t357" ########
#########################################################
#########################################################*/
szMyName = "LW"
// Get a handle to the current file buffer and the name
// and location of the current symbol where the cursor is.
hbuf = GetCurrentBuf()
szFunc = GetCurSymbol()
ln = GetSymbolLine(szFunc)
// Get current time
szTime = GetSysTime(1)
Day = szTime.Day
Month = szTime.Month
Year = szTime.Year
if (Day < 10)
szDay = "@"
else
szDay = Day
szMonth = NumToName(Month)
szInf = Ask("Enter the information of function:")
szDescription = Ask("Enter the description of function:")
// begin assembling the title string
sz = "/******************************************************************************"
InsBufLine(hbuf, ln, sz)
InsBufLine(hbuf, ln + 1, " * @szFunc@ - @szInf@")
InsBufLine(hbuf, ln + 2, " * DESCRIPTION: - ")
InsBufLine(hbuf, ln + 3, " * @szDescription@ ")
// remove by t357. CutWord(szDescription)
InsBufLine(hbuf, ln + 4, " * Input: ")
InsBufLine(hbuf, ln + 5, " * Output: ")
InsBufLine(hbuf, ln + 6, " * Returns: ")
InsBufLine(hbuf, ln + 7, " * ")
InsBufLine(hbuf, ln + 8, " * modification history")
InsBufLine(hbuf, ln + 9, " * --------------------")
InsBufLine(hbuf, ln + 10, " * 01a, @szDay@@szMonth@@Year@, @szMyName@ written")
InsBufLine(hbuf, ln + 11, " * --------------------")
InsBufLine(hbuf, ln + 12, " ******************************************************************************/")
// put the insertion point inside the header comment
SetBufIns(hbuf, ln + 1, strlen(szFunc) + strlen(szInf) + 8)
}
/******************************************************************************
* NumToName -- change the month number to name
*
* modification history
* --------------------
* 01a, 05mar2003, t357 written
* --------------------
******************************************************************************/
macro NumToName(Month)
{
if (Month == 1)
return "jan"
if (Month == 2)
return "feb"
if (Month == 3)
return "mar"
if (Month == 4)
return "apr"
if (Month == 5)
return "may"
if (Month == 6)
return "jun"
if (Month == 7)
return "jul"
if (Month == 8)
return "aug"
if (Month == 9)
return "sep"
if (Month == 10)
return "oct"
if (Month == 11)
return "nov"
if (Month == 12)
return "dec"
}
/******************************************************************************
* CutWord -- auto newline
*
* modification history
* --------------------
* 01a, 24mar2003, t357 fix some bug
* 01a, 05mar2003, t357 written
* --------------------
******************************************************************************/
macro CutWord(ncurLine, szInf)
{
LENGTH = 63
nlength = StrLen(szInf)
i = 0 /* loop control */
begin = 0 /* first character's index of current line */
pre = 0 /* preceding word's index */
hbuf = GetCurrentBuf()
// nline = GetBufLnCur()
while (i < nlength)
{
/* remove by t357
nrow = 0
sz = ""
while (nrow < 80)
{
if (nlength < 0)
break
sz = Cat(sz, szInf[nrow])
nrow = nrow + 1
nlength = nlength - 1
}
InsBufLine(hbuf, nline, sz)
szInf = szInf[nrow]
}
*/
c = szInf[i]
if (" " == @c@ && (i - b < LENGTH))
{
pre = i
}
else if (" " == @c@)
{
szOutput = ""
k = begin /* loop control */
while (k < pre)
{
szOutput = Cat(szOutput, szInf[k])
k = k + 1
}
InsBufLine(hbuf, ncurLine, sz)
ncurLine = ncurLine + 1
begin = pre
}
i = i + 1
}
if (h != i - 1)
{
szOutput = ""
k = begin /* loop control */
while (k < pre)
{
szOutput = Cat(szOutput, szInf[k])
k = k + 1
}
InsBufLine(hbuf, ncurLine, sz)
ncurLine = ncurLine + 1
}
}
// Wrap ifdeinef
macro IfdefineSz(sz)
{
hwnd = GetCurrentWnd()
lnFirst = GetWndSelLnFirst(hwnd)
lnLast = GetWndSelLnLast(hwnd)
hbuf = GetCurrentBuf()
InsBufLine(hbuf, lnFirst, "#ifndef @sz@")
InsBufLine(hbuf, lnFirst + 1, "#define @sz@")
InsBufLine(hbuf, lnLast + 3, "#endif /* @sz@ */")
SetBufIns(hbuf, lnFirst + 2, 0)
}
/* A U T O E X P A N D */
/*-------------------------------------------------------------------------
Automatically expands C statements like if, for, while, switch, etc..
To use this macro,
1. Add this file to your project or your Base project.
2. Run the Options->Key Assignments command and assign a
convenient keystroke to the "AutoExpand" command.
3. After typing a keyword, press the AutoExpand keystroke to have the
statement expanded. The expanded statement will contain a ### string
which represents a field where you are supposed to type more.
The ### string is also loaded in to the search pattern so you can
use "Search Forward" to select the next ### field.
For example:
1. you type "for" + AutoExpand key
2. this is inserted:
for (###; ###; ###)
{
###
}
3. and the first ### field is selected.
-------------------------------------------------------------------------*/
/******************************************************************************
* AutoExpand - Automatically expands C statements
*
* DESCRIPTION: - Automatically expands C statements like if, for, while,
* switch, etc..
*
* Input:
* Output:
* Returns:
*
* modification history
* --------------------
* 01a, 27mar2003, t357 modified
* --------------------
******************************************************************************/
macro AutoExpand()
{
// get window, sel, and buffer handles
hwnd = GetCurrentWnd()
if (hwnd == 0)
stop
sel = GetWndSel(hwnd)
if (sel.ichFirst == 0)
stop
hbuf = GetWndBuf(hwnd)
// get line the selection (insertion point) is on
szLine = GetBufLine(hbuf, sel.lnFirst);
// parse word just to the left of the insertion point
wordinfo = GetWordLeftOfIch(sel.ichFirst, szLine)
ln = sel.lnFirst;
chTab = CharFromAscii(9)
// prepare a new indented blank line to be inserted.
// keep white space on left and add a tab to indent.
// this preserves the indentation level.
ich = 0
while (szLine[ich] == ' ' || szLine[ich] == chTab)
{
ich = ich + 1
}
szLine = strmid(szLine, 0, ich)
sel.lnFirst = sel.lnLast
sel.ichFirst = wordinfo.ich
sel.ichLim = wordinfo.ich
// expand szWord keyword...
if (wordinfo.szWord == "if" ||
wordinfo.szWord == "while" ||
wordinfo.szWord == "elseif")
{
SetBufSelText(hbuf, " (###)")
InsBufLine(hbuf, ln + 1, "@szLine@" # "{");
InsBufLine(hbuf, ln + 2, "@szLine@" # chTab);
InsBufLine(hbuf, ln + 3, "@szLine@" # "}");
}
else if (wordinfo.szWord == "for")
{
SetBufSelText(hbuf, " (###; ###; ###)")
InsBufLine(hbuf, ln + 1, "@szLine@" # "{");
InsBufLine(hbuf, ln + 2, "@szLine@" # chTab);
InsBufLine(hbuf, ln + 3, "@szLine@" # "}");
}
else if (wordinfo.szWord == "switch")
{
SetBufSelText(hbuf, " (###)")
InsBufLine(hbuf, ln + 1, "@szLine@" # "{")
InsBufLine(hbuf, ln + 2, "@szLine@" # "case ")
InsBufLine(hbuf, ln + 3, "@szLine@" # chTab)
InsBufLine(hbuf, ln + 4, "@szLine@" # chTab # "break;")
InsBufLine(hbuf, ln + 5, "@szLine@" # "default:")
InsBufLine(hbuf, ln + 6, "@szLine@" # chTab)
InsBufLine(hbuf, ln + 7, "@szLine@" # "}")
}
else if (wordinfo.szWord == "do")
{
InsBufLine(hbuf, ln + 1, "@szLine@" # "{")
InsBufLine(hbuf, ln + 2, "@szLine@" # chTab);
InsBufLine(hbuf, ln + 3, "@szLine@" # "} while ();")
}
else if (wordinfo.szWord == "case")
{
SetBufSelText(hbuf, " ###")
InsBufLine(hbuf, ln + 1, "@szLine@" # chTab)
InsBufLine(hbuf, ln + 2, "@szLine@" # chTab # "break;")
}
else
stop
SetWndSel(hwnd, sel)
LoadSearchPattern("###", true, false, false);
Search_Forward
}
/* G E T W O R D L E F T O F I C H */
/*-------------------------------------------------------------------------
Given an index to a character (ich) and a string (sz),
return a "wordinfo" record variable that describes the
text word just to the left of the ich.
Output:
wordinfo.szWord = the word string
wordinfo.ich = the first ich of the word
wordinfo.ichLim = the limit ich of the word
-------------------------------------------------------------------------*/
macro GetWordLeftOfIch(ich, sz)
{
wordinfo = "" // create a "wordinfo" structure
chTab = CharFromAscii(9)
// scan backwords over white space, if any
ich = ich - 1;
if (ich >= 0)
while (sz[ich] == " " || sz[ich] == chTab)
{
ich = ich - 1;
if (ich < 0)
break;
}
// scan backwords to start of word
ichLim = ich + 1;
asciiA = AsciiFromChar("A")
asciiZ = AsciiFromChar("Z")
while (ich >= 0)
{
ch = toupper(sz[ich])
asciiCh = AsciiFromChar(ch)
if ((asciiCh < asciiA || asciiCh > asciiZ) && !IsNumber(ch))
break // stop at first non-identifier character
ich = ich - 1;
}
ich = ich + 1
wordinfo.szWord = strmid(sz, ich, ichLim)
wordinfo.ich = ich
wordinfo.ichLim = ichLim;
return wordinfo
}
//
// Comment the selected block of text using single line comments and indent it
//
macro CommentBlock()
{
hbuf = GetCurrentBuf();
hwnd = GetCurrentWnd();
sel = GetWndSel(hwnd);
iLine = sel.lnFirst;
while (iLine <= sel.lnLast)
{
szLine = GetBufLine(hbuf, iLine);
szLine = cat("// ", szLine);
PutBufLine(hbuf, iLine, szLine);
iLine = iLine + 1;
}
if (sel.lnFirst == sel.lnLast)
{
tabSize = _tsGetTabSize() - 1;
sel.ichFirst = sel.ichFirst + tabSize;
sel.ichLim = sel.ichLim + tabSize;
}
SetWndSel(hwnd, sel);
}
//
// Undo the CommentBlock for the selected text.
//
macro UnCommentBlock()
{
hbuf = GetCurrentBuf();
hwnd = GetCurrentWnd();
sel = GetWndSel(hwnd);
iLine = sel.lnFirst;
tabSize = 0;
while (iLine <= sel.lnLast)
{
szLine = GetBufLine(hbuf, iLine);
len = strlen(szLine);
szNewLine = "";
if (len > 1)
{
if (szLine[0] == "/" && szLine[1] == "/")
{
if (len > 2)
{
if (AsciiFromChar(szLine[2]) == 9)
{
tabSize = _tsGetTabSize() - 1;
szNewLine = strmid(szLine, 3, strlen(szLine));
}
}
if (szNewLine == "")
{
szNewLine = strmid(szLine, 2, strlen(szLine));
tabSize = 2;
}
PutBufLine(hbuf, iLine, szNewLine);
}
}
iLine = iLine + 1;
}
if (sel.lnFirst == sel.lnLast)
{
sel.ichFirst = sel.ichFirst - tabSize;
sel.ichLim = sel.ichLim - tabSize;
}
SetWndSel(hwnd, sel);
}
macro _tsGetTabSize()
{
szTabSize = GetReg("TabSize");
if (szTabSize != "")
{
tabSize = AsciiFromChar(szTabSize[0]) - AsciiFromChar("0");
}
else
{
tabSize = 4;
}
return tabSize;
}
//
// Reformat a selected comment block to wrap text at 80 columns.
// The start of the selection (upper left most character of the selection) is
// handled specially, in that it specifies the left most column at which all
// lines will begin. For example, if the following block was selected starting
// at the @ symbol, through the last line of the block...
//------------------------------------------------------------------------------
// preamble: @ This is a line that will be wrapped keeping the "at" symbol in its current column.
// All lines following it that are selected will use that as their starting column. See below to see how the wrapping
// works for this block of text.
//------------------------------------------------------------------------------
// preamble: @ This is a line that will be wrapped keeping the "at" symbol in
// its current column. All lines following it that are selected
// will use that as their starting column. See below to see how
// the wrapping works for this block of text.
//
macro tsReformatCommentBlock()
{
hbuf = GetCurrentBuf();
hwnd = GetCurrentWnd();
sel = GetWndSel(hwnd);
tabSize = _tsGetTabSize();
leftTextCol = 0 - 1;
colWrap = 80;
// Find the starting column, and create a Margin string
ichFirst = sel.ichFirst;
// Single line comment reformat?
if (sel.ichFirst == sel.ichLim && sel.lnFirst == sel.lnLast)
{
ichFirst = 0;
}
rec = _tsGetStartColumn(hbuf, ichFirst, sel.lnFirst);
if (rec == "")
stop;
colLeftMargin = rec.colMargin;
szMargin = "";
colComment = 0;
if (rec.colComment >= 0)
{
colComment = rec.colComment + 2
szMargin = _tsAddWhiteToColumn(szMargin, 0, rec.colComment, tabSize);
szMargin = cat(szMargin, "//");
}
szMargin = _tsAddWhiteToColumn(szMargin, colComment, rec.colMargin, tabSize);
rec = "";
szCurMargin = "";
if (ichFirst != 0)
{
szLine = GetBufLine(hbuf, sel.lnFirst);
szCurMargin = strmid(szLine, 0, ichFirst);
}
else
{
szCurMargin = szMargin;
szMargin = "";
}
insertLine = sel.lnFirst;
iLine = sel.lnFirst;
szRemainder = "";
while (1)
{
// msg("$0-" # iLine # ":" # szRemainder);
rec = _tsGetNextCommentString(hbuf, ichFirst, szRemainder, iLine, sel.lnLast, colWrap);
ichFirst = 0;
if (rec == "")
break;
// msg("$1-" # rec.ln # ":" # rec.szComment);
szLine = rec.szComment;
ich = 0;
col = colLeftMargin;
len = strlen(szLine);
ichPrevCharToWhite = 0-1;
ichPrevWhiteToChar = 0-1;
// msg("Leftovers @szRemainder@");
while (ich < len)
{
if (AsciiFromChar(szLine[ich]) == 9)
{
col = (((col + tabSize) / tabSize) * tabSize);
}
else
{
col = col + 1;
}
if (col > colWrap)
break;
fIsWhitespace = _tsIsWhitespaceChar(szLine[ich]);
fIsWhitespace1 = 1;
if (ich + 1 < len)
{
fIsWhitespace1 = _tsIsWhitespaceChar(szLine[ich + 1]);
}
if (!fIsWhitespace && fIsWhitespace1)
ichPrevCharToWhite = ich;
ich = ich + 1;
}
if (ichPrevCharToWhite > 0)
{
// msg("$2:" # strmid(szLine, 0, ichPrevCharToWhite + 1));
ich = ichPrevCharToWhite + 1;
while (ich < len)
{
if (!_tsIsWhitespaceChar(szLine[ich]))
{
ichPrevWhiteToChar = ich - 1;
// msg("$3:" # strmid(szLine, ichPrevWhiteToChar + 1, len));
break;
}
ich = ich + 1;
}
}
if (ichPrevCharToWhite > 0 && col > colWrap)
{
szNewLine = cat(szCurMargin, strmid(szLine, 0, ichPrevCharToWhite + 1));
szRemainder = "";
if (ichPrevWhiteToChar > 0)
szRemainder = strmid(szLine, ichPrevWhiteToChar + 1, len);
if (ichPrevCharToWhite > ichPrevWhiteToChar)
msg("!!!Wrap, duplicating word " # ichPrevWhiteToChar # " " # ichPrevCharToWhite # " " # szNewLine # " >>> " # szRemainder);
// msg(szLine);
// msg(col # " " # ichPrevWhiteToChar # " " # ichPrevCharToWhite # " " # szNewLine # " >>> " # szRemainder);
}
else if (szLine != "")
{
szNewLine = cat(szCurMargin, szLine );
szRemainder = "";
// sel.lnLast = sel.lnLast + 1;
}
iLine = rec.ln;
if (insertLine == iLine)
{
iLine = iLine + 1;
sel.lnLast = sel.lnLast + 1;
// msg("$5-" # insertLine # ":" # szNewLine);
InsBufLine(hbuf, insertLine, szNewLine);
}
else
{
szLine = GetBufLine(hbuf, insertLine);
if (szLine != szNewLine)
{
// msg("$6-" # insertLine # ":" # szNewLine);
PutBufLine(hbuf, insertLine, szNewLine);
}
}
insertLine = insertLine + 1;
if (szMargin != "")
{
szCurMargin = szMargin;
szMargin = "";
}
}
while (insertLine <= sel.lnLast)
{
DelBufLine(hbuf, insertLine);
sel.lnLast = sel.lnLast - 1;
}
len = GetBufLineLength(hbuf, insertLine-1);
sel.ichFirst = len;
sel.ichLim = len;
sel.lnFirst = sel.lnLast;
SetWndSel(hwnd, sel);
}
macro _tsAddWhiteToColumn(sz, col0, col, tabSize)
{
szTabs = " ";
szSpaces = " ";
tabs0 = col0 / tabSize;
tabs = (col / tabSize) - tabs0;
if (tabs == 0)
foo = col0;
else
foo = (tabs + tabs0) * tabSize;
spaces = col - foo;
// msg(col0 # " " # col # " " # tabs # " " # spaces # " " # tabs0);
if (tabs)
sz = cat(sz, strmid(szTabs, 0, tabs));
if (spaces)
sz = cat(sz, strmid(szSpaces, 0, spaces));
return sz;
}
macro _tsGetStartColumn(hbuf, ichBegin, ln)
{
szLine = GetBufLine(hbuf, ln);
len = strlen(szLine);
tabSize = _tsGetTabSize();
ich = 0;
colMargin = 0;
colComment = 0-1;
rec = "";
rec.colMargin = colMargin;
rec.colComment = colComment;
while (ich < len)
{
if (AsciiFromChar(szLine[ich]) == 9)
{
colMargin = (((colMargin + tabSize) / tabSize) * tabSize);
}
else
{
colMargin = colMargin + 1;
}
if (colComment < 0)
{
if (ich + 1 < len)
{
if (szLine[ich] == "/" && szLine[ich+1] == "/")
{
colComment = colMargin - 1;
ich = ich + 2;
colMargin = colMargin + 1;
continue;
}
}
}
if (ich >= ichBegin)
{
if (!_tsIsWhitespaceChar(szLine[ich]))
{
rec.colMargin = colMargin - 1;
rec.colComment = colComment;
// msg(szLine[ich]);
return rec;
}
}
ich = ich + 1;
}
return rec;
}
macro _tsGetNextCommentString(hbuf, ichSkip, szRemainder, ln, lnLast, colWrap)
{
rec = "";
// Go until we get a string that is at least long enough to fill a line
// or, we run out of lines.
if (szRemainder == "" && ln > lnLast)
return "";
ichFirst = ichSkip;
// msg(ichSkip);
while (1)
{
if (ln > lnLast)
{
rec.szComment = szRemainder;
rec.ln = ln;
return rec;
}
cchRemainder = strlen(szRemainder);
if (cchRemainder > colWrap)
{
rec.szComment = szRemainder;
rec.ln = ln;
return rec;
}
szLine = GetBufLine(hbuf, ln);
len = strlen(szLine);
if (ichSkip == 0)
ichFirst = _tsSkipPastCommentAndWhitespace(szLine, len);
ichSkip = 0;
ichLast = len - 1;
// Now, strip out all whitespace at the end of the line
while (ichLast >= ichFirst)
{
if (!_tsIsWhitespaceChar(szLine[ichLast]))
{
break;
}
ichLast = ichLast - 1;
}
// Entire line is whitespace?
if (ichLast < ichFirst)
{
if (szRemainder == "")
ln = ln + 1;
rec.szComment = szRemainder;
rec.ln = ln;
return rec;
}
// length of the non whitespaced comment + 1 space + cchRemainder
if ((ichLast + 1) - ichFirst + cchRemainder + 1 > 255)
{
// It may not format the current line quite right, but
// but at least we won't throw away some of the comment.
rec.szComment = szRemainder;
rec.ln = ln;
return rec;
}
if (szRemainder != "")
szRemainder = cat(szRemainder, " ");
szRemainder = cat(szRemainder, strmid(szLine, ichFirst, ichLast + 1));
ln = ln + 1;
}
}
macro _tsSkipPastCommentAndWhitespace(szLine, len)
{
ichFirst = 0;
// Skip past the comment initiator "//" if there is one.
while (ichFirst < len)
{
if (ichFirst + 1 < len)
{
if (szLine[ichFirst] == "/" && szLine[ichFirst+1] == "/")
{
ichFirst = ichFirst + 2;
break;
}
}
ichFirst = ichFirst + 1;
}
// If no comment found in line, then start from the beginning
if (ichFirst >= len)
ichFirst = 0;
ichFirst = ichFirst;
// Now, strip out all whitespace after the comment start.
while (ichFirst < len)
{
if (!_tsIsWhitespaceChar(szLine[ichFirst]))
{
break;
}
ichFirst = ichFirst + 1;
}
return ichFirst;
}