package require Tcl 9
# This script parses an nroff formatted Tcl/Tk manual page,
# converts it into some AST (Abstract Syntax Tree)
# and then writes it out again as a markdown file.
#
#
# When this script is called from another Tcl script (i.e. using the [source] command),
# you can call the procedure `::ndoc::man2markdown` with a the content of a man file
# to be converted as an argument
# (the whole script and its procedures live in the '::ndoc::' namespace).
# If you just have the man file, you can use: `::ndoc::man2markdown [::ndoc::readFile /path/to/my/file.n]`
#
#
# This procedure will return the resulting markdown.
#
# When this script is called directly from the command line using tclsh,
# specifying an nroff file as an argument will call the [::ndoc::man2markdown] procedure
# on the file content and return the markdown on stdout.
#
# When not specifying an argument,
# it runs in test mode, converting a specific manual page from within the
# repository structure which this script is a part of. The result is written to stdout.
#
# When run with two directory names, it will convert all nroff files in the (existing) first directory
# and put the result as markdown files into the second directory (which will be created if it does not exist).
# This should be used to produce the current status of afairs into doc/markdown/:
#
# ```
# # (from the tools directory)
# tclsh man2markdown.tcl ../doc ../doc/markdown
# ```
#
# The last invocation can be used to check what changed with respect to the last `fossil commit`.
# Any change reported by fossil (before committing) is a change that might have issues
# compared to the previous version, so it should be checked before the commit
# and amended before the commit!
#
# This script is part of the implementation of TIP 700 <https://core.tcl-lang.org/tips/doc/trunk/tip/700.md>
#
namespace eval ::ndoc {
# internal documentation of the used AST
set markdownText {
A typical Tcl/Tk nroff manual document consists of block elements and inline elements
and conforms to the following structure (only loosely used BNF notation here ...):
``` {.BNF}
Block = Paragraph | Code | Header | List | Dlist | Div | Syntax
Inline = Space | Text | Emphasis | Strong | Quoted | Link | Span
Document = Block +
Paragraph = Inline +
Header = Text
List = ListItem +
ListItem = Block + [but without 'Header']
Dlist = DlistItem +
DlistItem = Block + [but without 'Header']
Emphasis = Inline +
Strong = Inline +
Quoted = Inline +
Link = Inline +
Syntax = Span + | Space +
Div = Div + | Span + | Inline +
Span = Span | Text | Space + [currently a Span can not hold any other inline elements except itself (but only once) or Text/Space]
Text = <a string of visible characters including spaces>
Code = <a string of visible characters including spaces and newlines>
Space = <a space character>
```
We don't mind (for now) to be lazy, so the spaces are not separate all the time. They can be
present stand-alone or as part of a 'Text' element. For each newline between two input lines
we add a space.
The AST corresponding to a document is internally represented as a nested Tcl list.
The list has three elements where the last element may contain further lists of the same structure.
The first element of that list is always the "Document" item. Within that item the other
structural items are nested according to the above BNF structure.
Each item of the AST consists of three elements:
<keyword> <options> <content>
1. the <keyword> (e.g. "Document" or "Text")
2. a set of <options> with values (e.g. -level foo -class bar)
3. the <content> of the item which is itself either another structural item or a terminal element
All structural items with a '+' above have one or more nested AST items as their <content> elements.
This means, the content is itself a list with AST elements, each of these elements being a 3-element list as described above.
The others (the terminals: Text, Code, Space) only have a simple string of characters in the <content> element.
They do not have nested elements. Note, that the content element of Space is an empty string.
For most items, the options are currently empty (i.e. the empty list). These are the
possible structural items of the AST in the Tcl representation:
| item keyword | options | description |
|--------------|---------------|-----------------------------------------------------|
| Document | |
| Paragraph | -vs | the value is the value of the .VS macro showing information on when this content was added
| Header | -level | a section heading of a specific level (-level 1|2|3)
| | -class | defines that the header belongs to a specific class (can be used for CSS)
| List | -type | a bullet (-type bullet) or numbered (-type numbered) list
| ListItem | |
| Dlist | | a definition list
| DlistItem | -definition | the definition text making up the 'label' of the item (this is an Inline AST element!)
| | -vs | value of a .VS macro for that DlistItem > not possible to use in markdown
| Emphasis | |
| Strong | | text with strong emphasis, typically rendered as bold |
| Quoted | -type | text enclosed in quotes of a specific type (-type single|double)
| Link | -target | an internal link, within the document (-target #<anchor>) or to another manual page (-target <page>)
| Span | <class> -vs | a span element with a custom class attribute such as '.cmd', '.sub' etc. used for Tcl command syntax elements
| Div | <class> | a div element with a custom class attribute (currently only '.synopsis') used for grouping lines of Tcl command syntax
Here is example 1 of a complete AST:
``` {.nroff}
this is \fIitalic "and quoted" text\fR, right?
```
Example 1 AST as nested Tcl list:
``` {.tcl}
Document {} {
{Paragraph {} {
{Text {} "this is "}
{Emphasis {} {
{Text {} "italic "}
{Quoted {} {
{Text {} "and quoted"}
}}
{Text {} "text"}
}}
{Text {} ", right?"}
}}
}
```
Here's another example 2 where the nesting is slightly different:
``` {.nroff}
this is "*italic and quoted*"
```
Example 2 AST as nested Tcl list:
``` {.tcl}
Document {} {
{Paragraph {} {
{Text {} "this is "}
{Quoted {} {
{Emphasis {} {
{Text {} "italic and quoted"}
}}
}}
}}
}
```
Example 3 contains some more block elements:
```{.nroff}
.SH My header
.PP
Some text here with code:
.CS
set myVar theValue
.CE
.TP 13
A definition label
.
Some definition text
.RS
.PP
.CS
some code
.CE
.RE
somemore text
.TP 13
Another definition
.
Text for second item
.SH Next header
```
This is the corresponding Tcl list representation:
```{.tcl}
Document {} {
{Header {-level 1} {
{Text {} "My header"}
}}
{Paragraph {} {
{Text {} {Some text here with code:}}
}}
{Code {} {set myVar theValue}}
{Dlist {} {
{DlistItem {-definition "A definition label"} {
{Paragraph {} {
{Text {} {Some definition text}}
}}
{Code {} {puts "some code"}}
{Paragraph {} {
{Text {} {some more text}}
}}
}}
{DlistItem {-definition "Another definition"} {
{Text {} "Text for second item"}
}}
}}
{Header {-level 1} {Next header}}
...
}
```
}
# give diagnostic output:
set verbose 0
# the dictionary into which the manual page is put
set manual [dict create]
# list of section/aubsection titles which can act as reference targets
# (will be reset for ever man page read):
set sectionTitles [list]
# list of Tcl commands to recognize for links between manual pages:
set tclCmdList [lsort [info commands]]
lappend tclCmdList my next bgerror Tcl mathop mathfunc tclvars tm msgcat tclsh wish
# dictionary mapping every documented Tcl C API function (Tcl_...) to the
# manual page (file root) that documents it:
set tclCApiFileMap [dict create {*}{
Tcl_Obj Object
Tcl_Access Access Tcl_AddErrorInfo AddErrInfo Tcl_AddObjErrorInfo AddErrInfo Tcl_AlertNotifier Notifier
Tcl_Alloc Alloc Tcl_AllocStatBuf FileSystem Tcl_AllowExceptions AllowExc Tcl_AppInit AppInit
Tcl_AppendAllObjTypes ObjectType Tcl_AppendElement SetResult Tcl_AppendExportList Namespace3 Tcl_AppendFormatToObj StringObj
Tcl_AppendLimitedToObj StringObj Tcl_AppendObjToErrorInfo AddErrInfo Tcl_AppendObjToObj StringObj Tcl_AppendPrintfToObj StringObj
Tcl_AppendResult SetResult Tcl_AppendStringsToObj StringObj Tcl_AppendToObj StringObj Tcl_AppendUnicodeToObj StringObj
Tcl_AsyncCreate Async Tcl_AsyncDelete Async Tcl_AsyncInvoke Async Tcl_AsyncMark Async
Tcl_AsyncMarkFromSignal Async Tcl_AsyncReady Async Tcl_AttemptAlloc Alloc Tcl_AttemptCreateHashEntry Hash
Tcl_AttemptRealloc Alloc Tcl_AttemptSetObjLength StringObj Tcl_BackgroundError BackgdErr Tcl_BackgroundException BackgdErr
Tcl_BadChannelOption CrtChannel Tcl_BounceRefCount Object3 Tcl_CallWhenDeleted CallDel Tcl_CancelEval Cancel
Tcl_CancelIdleCall DoWhenIdle Tcl_Canceled Cancel Tcl_ChannelBlockModeProc CrtChannel Tcl_ChannelBuffered CrtChannel
Tcl_ChannelClose2Proc CrtChannel Tcl_ChannelFlushProc CrtChannel Tcl_ChannelGetHandleProc CrtChannel Tcl_ChannelGetOptionProc CrtChannel
Tcl_ChannelHandlerProc CrtChannel Tcl_ChannelInputProc CrtChannel Tcl_ChannelName CrtChannel Tcl_ChannelOutputProc CrtChannel
Tcl_ChannelSetOptionProc CrtChannel Tcl_ChannelThreadActionProc CrtChannel Tcl_ChannelTruncateProc CrtChannel Tcl_ChannelVersion CrtChannel
Tcl_ChannelWatchProc CrtChannel Tcl_ChannelWideSeekProc CrtChannel Tcl_Char16Len Utf Tcl_Char16ToUtfDString Utf
Tcl_Chdir GetCwd Tcl_ClassGetMetadata Class3 Tcl_ClassSetConstructor Method Tcl_ClassSetDestructor Method
Tcl_ClassSetMetadata Class3 Tcl_ClearChannelHandlers CrtChannel Tcl_Close OpenFileChnl Tcl_CloseEx OpenFileChnl
Tcl_CommandComplete CmdCmplt Tcl_CommandTraceInfo TraceCmd Tcl_Concat Concat3 Tcl_ConcatObj StringObj
Tcl_ConditionFinalize Thread Tcl_ConditionNotify Thread Tcl_ConditionWait Thread Tcl_ConsolePanic Panic
Tcl_ConvertCountedElement SplitList Tcl_ConvertElement SplitList Tcl_ConvertToType ObjectType Tcl_CopyObjectInstance Class3
Tcl_CreateAlias CrtAlias Tcl_CreateAliasObj CrtAlias Tcl_CreateChannel CrtChannel Tcl_CreateChannelHandler CrtChnlHdlr
Tcl_CreateChild CrtAlias Tcl_CreateCloseHandler CrtCloseHdlr Tcl_CreateCommand CrtCommand Tcl_CreateEncoding Encoding3
Tcl_CreateEnsemble Ensemble Tcl_CreateEventSource Notifier Tcl_CreateExitHandler Exit3 Tcl_CreateFileHandler CrtFileHdlr
Tcl_CreateHashEntry Hash Tcl_CreateInterp CrtInterp Tcl_CreateNamespace Namespace3 Tcl_CreateObjCommand CrtObjCmd
Tcl_CreateObjCommand2 CrtObjCmd Tcl_CreateObjTrace CrtTrace Tcl_CreateObjTrace2 CrtTrace Tcl_CreateThread Thread
Tcl_CreateThreadExitHandler Exit3 Tcl_CreateTimerHandler CrtTimerHdlr Tcl_CreateTrace CrtTrace Tcl_CutChannel CrtChannel
Tcl_DStringAppend DString Tcl_DStringAppendElement DString Tcl_DStringEndSublist DString Tcl_DStringFree DString
Tcl_DStringGetResult DString Tcl_DStringInit DString Tcl_DStringLength DString Tcl_DStringResult DString
Tcl_DStringSetLength DString Tcl_DStringStartSublist DString Tcl_DStringToObj DString Tcl_DStringValue DString
Tcl_DecrRefCount Object3 Tcl_DeleteAssocData AssocData Tcl_DeleteChannelHandler CrtChnlHdlr Tcl_DeleteCloseHandler CrtCloseHdlr
Tcl_DeleteCommand CrtObjCmd Tcl_DeleteCommandFromToken CrtObjCmd Tcl_DeleteEventSource Notifier Tcl_DeleteEvents Notifier
Tcl_DeleteExitHandler Exit3 Tcl_DeleteFileHandler CrtFileHdlr Tcl_DeleteHashEntry Hash Tcl_DeleteHashTable Hash
Tcl_DeleteInterp CrtInterp Tcl_DeleteNamespace Namespace3 Tcl_DeleteThreadExitHandler Exit3 Tcl_DeleteTimerHandler CrtTimerHdlr
Tcl_DeleteTrace CrtTrace Tcl_DetachChannel OpenFileChnl Tcl_DetachPids DetachPids Tcl_DictObjDone DictObj
Tcl_DictObjFirst DictObj Tcl_DictObjGet DictObj Tcl_DictObjNext DictObj Tcl_DictObjPut DictObj
Tcl_DictObjPutKeyList DictObj Tcl_DictObjRemove DictObj Tcl_DictObjRemoveKeyList DictObj Tcl_DictObjSize DictObj
Tcl_DiscardInterpState SaveInterpState Tcl_DoOneEvent DoOneEvent Tcl_DoWhenIdle DoWhenIdle Tcl_DontCallWhenDeleted CallDel
Tcl_DumpActiveMemory DumpActiveMemory Tcl_DuplicateObj Object3 Tcl_Eof OpenFileChnl Tcl_ErrnoId SetErrno
Tcl_ErrnoMsg SetErrno Tcl_Eval Eval3 Tcl_EvalEx Eval3 Tcl_EvalFile Eval3
Tcl_EvalObjEx Eval3 Tcl_EvalObjv Eval3 Tcl_EvalTokensStandard ParseCmd Tcl_EventuallyFree Preserve
Tcl_Exit Exit3 Tcl_ExitThread Exit3 Tcl_Export Namespace3 Tcl_ExposeCommand CrtAlias
Tcl_ExprBoolean ExprLong Tcl_ExprBooleanObj ExprLongObj Tcl_ExprDouble ExprLong Tcl_ExprDoubleObj ExprLongObj
Tcl_ExprLong ExprLong Tcl_ExprLongObj ExprLongObj Tcl_ExprObj ExprLongObj Tcl_ExprString ExprLong
Tcl_ExternalToUtf Encoding3 Tcl_ExternalToUtfDString Encoding3 Tcl_ExternalToUtfDStringEx Encoding3 Tcl_FSAccess FileSystem
Tcl_FSChdir FileSystem Tcl_FSConvertToPathType FileSystem Tcl_FSCopyDirectory FileSystem Tcl_FSCopyFile FileSystem
Tcl_FSCreateDirectory FileSystem Tcl_FSData FileSystem Tcl_FSDeleteFile FileSystem Tcl_FSEqualPaths FileSystem
Tcl_FSEvalFile FileSystem Tcl_FSEvalFileEx FileSystem Tcl_FSFileAttrStrings FileSystem Tcl_FSFileAttrsGet FileSystem
Tcl_FSFileAttrsSet FileSystem Tcl_FSFileSystemInfo FileSystem Tcl_FSGetCwd FileSystem Tcl_FSGetFileSystemForPath FileSystem
Tcl_FSGetInternalRep FileSystem Tcl_FSGetNativePath FileSystem Tcl_FSGetNormalizedPath FileSystem Tcl_FSGetPathType FileSystem
Tcl_FSGetTranslatedPath FileSystem Tcl_FSGetTranslatedStringPath FileSystem Tcl_FSJoinPath FileSystem Tcl_FSJoinToPath FileSystem
Tcl_FSLink FileSystem Tcl_FSListVolumes FileSystem Tcl_FSLoadFile FileSystem Tcl_FSLstat FileSystem
Tcl_FSMatchInDirectory FileSystem Tcl_FSMountsChanged FileSystem Tcl_FSNewNativePath FileSystem Tcl_FSOpenFileChannel FileSystem
Tcl_FSPathSeparator FileSystem Tcl_FSRegister FileSystem Tcl_FSRemoveDirectory FileSystem Tcl_FSRenameFile FileSystem
Tcl_FSSplitPath FileSystem Tcl_FSStat FileSystem Tcl_FSTildeExpand FileSystem Tcl_FSUnloadFile FileSystem
Tcl_FSUnregister FileSystem Tcl_FSUtime FileSystem Tcl_FetchInternalRep ObjectType Tcl_Finalize Exit3
Tcl_FinalizeNotifier Notifier Tcl_FinalizeThread Exit3 Tcl_FindCommand Namespace3 Tcl_FindEnsemble Ensemble
Tcl_FindExecutable FindExec Tcl_FindHashEntry Hash Tcl_FindNamespace Namespace3 Tcl_FindSymbol Load3
Tcl_FirstHashEntry Hash Tcl_Flush OpenFileChnl Tcl_ForgetImport Namespace3 Tcl_Format StringObj
Tcl_Free Alloc Tcl_FreeEncoding Encoding3 Tcl_FreeInternalRep ObjectType Tcl_FreeParse ParseCmd
Tcl_GetAccessTimeFromStat FileSystem Tcl_GetAliasObj CrtAlias Tcl_GetAssocData AssocData Tcl_GetBignumFromObj IntObj
Tcl_GetBlockSizeFromStat FileSystem Tcl_GetBlocksFromStat FileSystem Tcl_GetBoolFromObj BoolObj Tcl_GetBoolean GetInt
Tcl_GetBooleanFromObj BoolObj Tcl_GetByteArrayFromObj ByteArrObj Tcl_GetBytesFromObj ByteArrObj Tcl_GetChangeTimeFromStat FileSystem
Tcl_GetChannel OpenFileChnl Tcl_GetChannelBufferSize CrtChannel Tcl_GetChannelError SetChanErr Tcl_GetChannelErrorInterp SetChanErr
Tcl_GetChannelHandle CrtChannel Tcl_GetChannelInstanceData CrtChannel Tcl_GetChannelMode CrtChannel Tcl_GetChannelName CrtChannel
Tcl_GetChannelNames OpenFileChnl Tcl_GetChannelNamesEx OpenFileChnl Tcl_GetChannelOption OpenFileChnl Tcl_GetChannelThread CrtChannel
Tcl_GetChannelType CrtChannel Tcl_GetCharLength StringObj Tcl_GetChild CrtAlias Tcl_GetClassAsObject Class3
Tcl_GetCommandFromObj CrtObjCmd Tcl_GetCommandFullName CrtObjCmd Tcl_GetCommandInfo CrtObjCmd Tcl_GetCommandInfoFromToken CrtObjCmd
Tcl_GetCommandName CrtObjCmd Tcl_GetCurrentNamespace Namespace3 Tcl_GetCurrentThread Notifier Tcl_GetCwd GetCwd
Tcl_GetDeviceTypeFromStat FileSystem Tcl_GetDouble GetInt Tcl_GetDoubleFromObj DoubleObj Tcl_GetEncoding Encoding3
Tcl_GetEncodingFromObj Encoding3 Tcl_GetEncodingName Encoding3 Tcl_GetEncodingNameForUser Encoding3 Tcl_GetEncodingNameFromEnvironment Encoding3
Tcl_GetEncodingNames Encoding3 Tcl_GetEncodingSearchPath Encoding3 Tcl_GetEnsembleFlags Ensemble Tcl_GetEnsembleMappingDict Ensemble
Tcl_GetEnsembleNamespace Ensemble Tcl_GetEnsembleParameterList Ensemble Tcl_GetEnsembleSubcommandList Ensemble Tcl_GetEnsembleUnknownHandler Ensemble
Tcl_GetErrno SetErrno Tcl_GetErrorLine AddErrInfo Tcl_GetFSDeviceFromStat FileSystem Tcl_GetFSInodeFromStat FileSystem
Tcl_GetGlobalNamespace Namespace3 Tcl_GetGroupIdFromStat FileSystem Tcl_GetHashKey Hash Tcl_GetHashValue Hash
Tcl_GetHostName GetHostName Tcl_GetIndexFromObj GetIndex Tcl_GetIndexFromObjStruct GetIndex Tcl_GetInt GetInt
Tcl_GetIntForIndex IntObj Tcl_GetIntFromObj IntObj Tcl_GetInterpPath CrtAlias Tcl_GetLinkCountFromStat FileSystem
Tcl_GetLongFromObj IntObj Tcl_GetMemoryInfo Alloc Tcl_GetModeFromStat FileSystem Tcl_GetModificationTimeFromStat FileSystem
Tcl_GetNameOfExecutable FindExec Tcl_GetNamespaceUnknownHandler Namespace3 Tcl_GetNumber Number Tcl_GetNumberFromObj Number
Tcl_GetObjResult SetResult Tcl_GetObjType ObjectType Tcl_GetObjectAsClass Class3 Tcl_GetObjectCommand Class3
Tcl_GetObjectFromObj Class3 Tcl_GetObjectName Class3 Tcl_GetObjectNamespace Class3 Tcl_GetOpenFile GetOpnFl
Tcl_GetParent CrtAlias Tcl_GetPathType SplitPath Tcl_GetRange StringObj Tcl_GetRegExpFromObj RegExp3
Tcl_GetReturnOptions AddErrInfo Tcl_GetServiceMode Notifier Tcl_GetSizeFromStat FileSystem Tcl_GetSizeIntFromObj IntObj
Tcl_GetStackedChannel ChnlStack Tcl_GetStartupScript Tcl_Main Tcl_GetStdChannel GetStdChan Tcl_GetString StringObj
Tcl_GetStringFromObj StringObj Tcl_GetStringResult SetResult Tcl_GetThreadData Thread Tcl_GetTime GetTime
Tcl_GetTopChannel ChnlStack Tcl_GetUniChar StringObj Tcl_GetUnicode StringObj Tcl_GetUnicodeFromObj StringObj
Tcl_GetUserIdFromStat FileSystem Tcl_GetVar SetVar Tcl_GetVar2 SetVar Tcl_GetVar2Ex SetVar
Tcl_GetVersion GetVersion Tcl_GetWideIntFromObj IntObj Tcl_GetWideUIntFromObj IntObj Tcl_Gets OpenFileChnl
Tcl_GetsObj OpenFileChnl Tcl_GlobalEval Eval3 Tcl_GlobalEvalObj Eval3 Tcl_HasStringRep ObjectType
Tcl_HashStats Hash Tcl_HideCommand CrtAlias Tcl_Import Namespace3 Tcl_IncrRefCount Object3
Tcl_Init Init Tcl_InitCustomHashTable Hash Tcl_InitHashTable Hash Tcl_InitMemory DumpActiveMemory
Tcl_InitNotifier Notifier Tcl_InitObjHashTable Hash Tcl_InitStringRep ObjectType Tcl_InitStubs InitStubs
Tcl_InitSubsystems InitSubSyst Tcl_InputBlocked OpenFileChnl Tcl_InputBuffered OpenFileChnl Tcl_InterpActive CrtInterp
Tcl_InterpDeleted CrtInterp Tcl_InvalidateStringRep Object3 Tcl_IsChannelExisting CrtChannel Tcl_IsChannelRegistered CrtChannel
Tcl_IsChannelShared CrtChannel Tcl_IsEmpty StringObj Tcl_IsEnsemble Ensemble Tcl_IsSafe CrtAlias
Tcl_IsShared Object3 Tcl_IsStandardChannel OpenFileChnl Tcl_JoinPath SplitPath Tcl_JoinThread Thread
Tcl_LimitAddHandler Limit Tcl_LimitCheck Limit Tcl_LimitExceeded Limit Tcl_LimitGetCommands Limit
Tcl_LimitGetGranularity Limit Tcl_LimitGetTime Limit Tcl_LimitReady Limit Tcl_LimitRemoveHandler Limit
Tcl_LimitSetCommands Limit Tcl_LimitSetGranularity Limit Tcl_LimitSetTime Limit Tcl_LimitTypeEnabled Limit
Tcl_LimitTypeExceeded Limit Tcl_LimitTypeReset Limit Tcl_LimitTypeSet Limit Tcl_LinkArray LinkVar
Tcl_LinkVar LinkVar Tcl_ListObjAppendElement ListObj Tcl_ListObjAppendList ListObj Tcl_ListObjGetElements ListObj
Tcl_ListObjIndex ListObj Tcl_ListObjLength ListObj Tcl_ListObjRange ListObj Tcl_ListObjRepeat ListObj
Tcl_ListObjReplace ListObj Tcl_ListObjReverse ListObj Tcl_LoadFile Load3 Tcl_LogCommandInfo AddErrInfo
Tcl_Main Tcl_Main Tcl_MainEx Tcl_Main Tcl_MainExW Tcl_Main Tcl_MakeFileChannel OpenFileChnl
Tcl_MakeTcpClientChannel OpenTcp Tcl_Merge SplitList Tcl_MethodDeclarerClass Method Tcl_MethodDeclarerObject Method
Tcl_MethodIsPrivate Method Tcl_MethodIsPublic Method Tcl_MethodIsType Method Tcl_MethodIsType2 Method
Tcl_MethodName Method Tcl_MutexFinalize Thread Tcl_MutexLock Thread Tcl_MutexUnlock Thread
Tcl_NRAddCallback NRE Tcl_NRCallObjProc NRE Tcl_NRCallObjProc2 NRE Tcl_NRCmdSwap NRE
Tcl_NRCreateCommand NRE Tcl_NRCreateCommand2 NRE Tcl_NREvalObj NRE Tcl_NREvalObjv NRE
Tcl_NRExprObj NRE Tcl_NewBignumObj IntObj Tcl_NewBooleanObj BoolObj Tcl_NewByteArrayObj ByteArrObj
Tcl_NewDictObj DictObj Tcl_NewDoubleObj DoubleObj Tcl_NewInstanceMethod Method Tcl_NewInstanceMethod2 Method
Tcl_NewIntObj IntObj Tcl_NewListObj ListObj Tcl_NewLongObj IntObj Tcl_NewMethod Method
Tcl_NewMethod2 Method Tcl_NewObj Object3 Tcl_NewObjectInstance Class3 Tcl_NewStringObj StringObj
Tcl_NewUnicodeObj StringObj Tcl_NewWideIntObj IntObj Tcl_NewWideUIntObj IntObj Tcl_NextHashEntry Hash
Tcl_NotifyChannel CrtChannel Tcl_NumUtfChars Utf Tcl_OOInitStubs OOInitStubs Tcl_ObjGetVar2 SetVar
Tcl_ObjPrintf StringObj Tcl_ObjSetVar2 SetVar Tcl_ObjectContextInvokeNext Method Tcl_ObjectContextIsFiltering Method
Tcl_ObjectContextMethod Method Tcl_ObjectContextObject Method Tcl_ObjectContextSkippedArgs Method Tcl_ObjectDeleted Class3
Tcl_ObjectGetMetadata Class3 Tcl_ObjectGetMethodNameMapper Class3 Tcl_ObjectSetMetadata Class3 Tcl_ObjectSetMethodNameMapper Class3
Tcl_OpenCommandChannel OpenFileChnl Tcl_OpenFileChannel OpenFileChnl Tcl_OpenTcpClient OpenTcp Tcl_OpenTcpServer OpenTcp
Tcl_OpenTcpServerEx OpenTcp Tcl_OutputBuffered OpenFileChnl Tcl_Panic Panic Tcl_ParseArgsObjv ParseArgs
Tcl_ParseBraces ParseCmd Tcl_ParseCommand ParseCmd Tcl_ParseExpr ParseCmd Tcl_ParseQuotedString ParseCmd
Tcl_ParseVar ParseCmd Tcl_ParseVarName ParseCmd Tcl_PkgPresent PkgRequire Tcl_PkgPresentEx PkgRequire
Tcl_PkgProvide PkgRequire Tcl_PkgProvideEx PkgRequire Tcl_PkgRequire PkgRequire Tcl_PkgRequireEx PkgRequire
Tcl_PkgRequireProc PkgRequire Tcl_PosixError AddErrInfo Tcl_Preserve Preserve Tcl_PrintDouble PrintDbl
Tcl_PutEnv Environment Tcl_QueryTimeProc GetTime Tcl_QueueEvent Notifier Tcl_Read OpenFileChnl
Tcl_ReadChars OpenFileChnl Tcl_ReadRaw OpenFileChnl Tcl_Realloc Alloc Tcl_ReapDetachedProcs DetachPids
Tcl_RecordAndEval RecordEval Tcl_RecordAndEvalObj RecEvalObj Tcl_RegExpCompile RegExp3 Tcl_RegExpExec RegExp3
Tcl_RegExpExecObj RegExp3 Tcl_RegExpGetInfo RegExp3 Tcl_RegExpMatch RegExp3 Tcl_RegExpMatchObj RegExp3
Tcl_RegExpRange RegExp3 Tcl_RegisterChannel OpenFileChnl Tcl_RegisterConfig RegConfig Tcl_RegisterObjType ObjectType
Tcl_Release Preserve Tcl_ResetResult SetResult Tcl_RestoreInterpState SaveInterpState Tcl_SaveInterpState SaveInterpState
Tcl_ScanCountedElement SplitList Tcl_ScanElement SplitList Tcl_Seek OpenFileChnl Tcl_ServiceAll Notifier
Tcl_ServiceEvent Notifier Tcl_ServiceModeHook Notifier Tcl_SetAssocData AssocData Tcl_SetBignumObj IntObj
Tcl_SetBooleanObj BoolObj Tcl_SetByteArrayLength ByteArrObj Tcl_SetByteArrayObj ByteArrObj Tcl_SetChannelBufferSize CrtChannel
Tcl_SetChannelError SetChanErr Tcl_SetChannelErrorInterp SetChanErr Tcl_SetChannelOption OpenFileChnl Tcl_SetCommandInfo CrtObjCmd
Tcl_SetCommandInfoFromToken CrtObjCmd Tcl_SetDoubleObj DoubleObj Tcl_SetEncodingSearchPath Encoding3 Tcl_SetEnsembleFlags Ensemble
Tcl_SetEnsembleMappingDict Ensemble Tcl_SetEnsembleParameterList Ensemble Tcl_SetEnsembleSubcommandList Ensemble Tcl_SetEnsembleUnknownHandler Ensemble
Tcl_SetErrno SetErrno Tcl_SetErrorCode AddErrInfo Tcl_SetErrorLine AddErrInfo Tcl_SetExitProc Exit3
Tcl_SetHashValue Hash Tcl_SetIntObj IntObj Tcl_SetListObj ListObj Tcl_SetLongObj IntObj
Tcl_SetMainLoop Tcl_Main Tcl_SetMaxBlockTime Notifier Tcl_SetNamespaceUnknownHandler Namespace3 Tcl_SetNotifier Notifier
Tcl_SetObjErrorCode AddErrInfo Tcl_SetObjLength StringObj Tcl_SetObjResult SetResult Tcl_SetPanicProc Panic
Tcl_SetRecursionLimit SetRecLmt Tcl_SetResult SetResult Tcl_SetReturnOptions AddErrInfo Tcl_SetServiceMode Notifier
Tcl_SetStartupScript Tcl_Main Tcl_SetStdChannel GetStdChan Tcl_SetStringObj StringObj Tcl_SetSystemEncoding Encoding3
Tcl_SetTimeProc GetTime Tcl_SetTimer Notifier Tcl_SetUnicodeObj StringObj Tcl_SetVar SetVar
Tcl_SetVar2 SetVar Tcl_SetVar2Ex SetVar Tcl_SetWideIntObj IntObj Tcl_SetWideUIntObj IntObj
Tcl_SignalId Signal Tcl_SignalMsg Signal Tcl_Sleep Sleep Tcl_SourceRCFile SourceRCFile
Tcl_SpliceChannel CrtChannel Tcl_SplitList SplitList Tcl_SplitPath SplitPath Tcl_StackChannel ChnlStack
Tcl_StandardChannels StdChannels Tcl_Stat Access Tcl_StaticLibrary StaticLibrary Tcl_StaticPackage StaticLibrary
Tcl_StoreInternalRep ObjectType Tcl_StringCaseMatch StrMatch Tcl_StringMatch StrMatch Tcl_SubstObj SubstObj
Tcl_TakeBignumFromObj IntObj Tcl_Tell OpenFileChnl Tcl_ThreadAlert Notifier Tcl_ThreadQueueEvent Notifier
Tcl_TraceCommand TraceCmd Tcl_TraceVar TraceVar Tcl_TraceVar2 TraceVar Tcl_TransferResult SetResult
Tcl_TranslateFileName Translate Tcl_TruncateChannel OpenFileChnl Tcl_Ungets OpenFileChnl Tcl_UniChar Utf
Tcl_UniCharAtIndex Utf Tcl_UniCharCaseMatch Utf Tcl_UniCharIsAlnum UniCharIsAlpha Tcl_UniCharIsAlpha UniCharIsAlpha
Tcl_UniCharIsControl UniCharIsAlpha Tcl_UniCharIsDigit UniCharIsAlpha Tcl_UniCharIsGraph UniCharIsAlpha Tcl_UniCharIsLower UniCharIsAlpha
Tcl_UniCharIsPrint UniCharIsAlpha Tcl_UniCharIsPunct UniCharIsAlpha Tcl_UniCharIsSpace UniCharIsAlpha Tcl_UniCharIsUpper UniCharIsAlpha
Tcl_UniCharIsWordChar UniCharIsAlpha Tcl_UniCharLen Utf Tcl_UniCharNcasecmp Utf Tcl_UniCharNcmp Utf
Tcl_UniCharToLower ToUpper Tcl_UniCharToTitle ToUpper Tcl_UniCharToUpper ToUpper Tcl_UniCharToUtf Utf
Tcl_UniCharToUtfDString Utf Tcl_UnlinkVar LinkVar Tcl_UnregisterChannel OpenFileChnl Tcl_UnsetVar SetVar
Tcl_UnsetVar2 SetVar Tcl_UnstackChannel ChnlStack Tcl_UntraceCommand TraceCmd Tcl_UntraceVar TraceVar
Tcl_UntraceVar2 TraceVar Tcl_UpVar UpVar3 Tcl_UpVar2 UpVar3 Tcl_UpdateLinkedVar LinkVar
Tcl_UtfAtIndex Utf Tcl_UtfBackslash Utf Tcl_UtfCharComplete Utf Tcl_UtfFindFirst Utf
Tcl_UtfFindLast Utf Tcl_UtfNcasecmp Utf Tcl_UtfNcmp Utf Tcl_UtfNext Utf
Tcl_UtfPrev Utf Tcl_UtfToChar16 Utf Tcl_UtfToChar16DString Utf Tcl_UtfToExternal Encoding3
Tcl_UtfToExternalDString Encoding3 Tcl_UtfToExternalDStringEx Encoding3 Tcl_UtfToLower ToUpper Tcl_UtfToNormalized UnicodeNormalize
Tcl_UtfToNormalizedDString UnicodeNormalize Tcl_UtfToTitle ToUpper Tcl_UtfToUniChar Utf Tcl_UtfToUniCharDString Utf
Tcl_UtfToUpper ToUpper Tcl_UtfToWChar Utf Tcl_UtfToWCharDString Utf Tcl_ValidateAllMemory DumpActiveMemory
Tcl_VarEval Eval3 Tcl_VarTraceInfo TraceVar Tcl_VarTraceInfo2 TraceVar Tcl_WCharLen Utf
Tcl_WCharToUtfDString Utf Tcl_WaitForEvent Notifier Tcl_WaitPid DetachPids Tcl_WinConvertError SetErrno
Tcl_Write OpenFileChnl Tcl_WriteChars OpenFileChnl Tcl_WriteObj OpenFileChnl Tcl_WriteRaw OpenFileChnl
Tcl_WrongNumArgs WrongNumArgs Tcl_ZlibAdler32 TclZlib Tcl_ZlibCRC32 TclZlib Tcl_ZlibDeflate TclZlib
Tcl_ZlibInflate TclZlib Tcl_ZlibStreamChecksum TclZlib Tcl_ZlibStreamClose TclZlib Tcl_ZlibStreamEof TclZlib
Tcl_ZlibStreamGet TclZlib Tcl_ZlibStreamGetCommandName TclZlib Tcl_ZlibStreamInit TclZlib Tcl_ZlibStreamPut TclZlib
}]
# dictionary mapping every documented Tk C API function (Tk_...) to the
# manual page (file root) that documents it:
set tkCApiFileMap [dict create {*}{
Tk_3DBorderColor 3DBorder Tk_3DBorderGC 3DBorder Tk_3DHorizontalBevel 3DBorder Tk_3DVerticalBevel 3DBorder
Tk_AddOption AddOption Tk_Alloc3DBorderFromObj 3DBorder Tk_AllocBitmapFromObj GetBitmap Tk_AllocColorFromObj GetColor
Tk_AllocCursorFromObj GetCursor Tk_AllocFontFromObj GetFont Tk_AlwaysShowSelection WindowId Tk_AttachHWND GetHWND
Tk_Attributes WindowId Tk_BindEvent BindTable Tk_CanvasDrawableCoords CanvTkwin Tk_CanvasEventuallyRedraw CanvTkwin
Tk_CanvasGetCoord CanvTkwin Tk_CanvasPsBitmap CanvPsY Tk_CanvasPsColor CanvPsY Tk_CanvasPsFont CanvPsY
Tk_CanvasPsPath CanvPsY Tk_CanvasPsStipple CanvPsY Tk_CanvasPsY CanvPsY Tk_CanvasSetStippleOrigin CanvTkwin
Tk_CanvasTagsOption CanvTkwin Tk_CanvasTextInfo CanvTxtInfo Tk_CanvasTkwin CanvTkwin Tk_CanvasWindowCoords CanvTkwin
Tk_ChangeWindowAttributes ConfigWind Tk_Changes WindowId Tk_CharBbox TextLayout Tk_Class SetClass
Tk_ClearSelection ClrSelect Tk_ClipDrawableToRect 3DBorder Tk_ClipboardAppend Clipboard3 Tk_ClipboardClear Clipboard3
Tk_CollapseMotionEvents QWinEvent Tk_Colormap WindowId Tk_ComputeTextLayout TextLayout Tk_ConfigureInfo ConfigWidg
Tk_ConfigureValue ConfigWidg Tk_ConfigureWidget ConfigWidg Tk_ConfigureWindow ConfigWind Tk_CoordsToWindow CoordToWin
Tk_CreateBinding BindTable Tk_CreateBindingTable BindTable Tk_CreateClientMessageHandler CrtCmHdlr Tk_CreateErrorHandler CrtErrHdlr
Tk_CreateEventHandler EventHndlr Tk_CreateGenericHandler CrtGenHdlr Tk_CreateImageType CrtImgType Tk_CreateItemType CrtItemType
Tk_CreateOptionTable SetOptions Tk_CreatePhotoImageFormat CrtPhImgFmt Tk_CreateSelHandler CrtSelHdlr Tk_CreateWindow CrtWindow
Tk_CreateWindowFromPath CrtWindow Tk_DefineBitmap GetBitmap Tk_DefineCursor ConfigWind Tk_DeleteAllBindings BindTable
Tk_DeleteBinding BindTable Tk_DeleteBindingTable BindTable Tk_DeleteClientMessageHandler CrtCmHdlr Tk_DeleteErrorHandler CrtErrHdlr
Tk_DeleteEventHandler EventHndlr Tk_DeleteGenericHandler CrtGenHdlr Tk_DeleteImage DeleteImg Tk_DeleteOptionTable SetOptions
Tk_DeleteSelHandler CrtSelHdlr Tk_Depth WindowId Tk_DestroyWindow CrtWindow Tk_Display WindowId
Tk_DisplayName WindowId Tk_DistanceToTextLayout TextLayout Tk_Draw3DPolygon 3DBorder Tk_Draw3DRectangle 3DBorder
Tk_DrawChars MeasureChar Tk_DrawCharsInContext MeasureChar Tk_DrawFocusHighlight DrawFocHlt Tk_DrawHighlightBorder 3DBorder
Tk_DrawTextLayout TextLayout Tk_Fill3DPolygon 3DBorder Tk_Fill3DRectangle 3DBorder Tk_FindPhoto FindPhoto
Tk_FontGetDescription GetFont Tk_FontId FontId Tk_Free3DBorder 3DBorder Tk_Free3DBorderFromObj 3DBorder
Tk_FreeBitmap GetBitmap Tk_FreeBitmapFromObj GetBitmap Tk_FreeColor GetColor Tk_FreeColorFromObj GetColor
Tk_FreeColormap GetClrmap Tk_FreeConfigOptions SetOptions Tk_FreeCursor GetCursor Tk_FreeCursorFromObj GetCursor
Tk_FreeFont GetFont Tk_FreeFontFromObj GetFont Tk_FreeGC GetGC Tk_FreeImage GetImage
Tk_FreeOptions ConfigWidg Tk_FreePixmap GetPixmap Tk_FreeSavedOptions SetOptions Tk_FreeTextLayout TextLayout
Tk_GeometryRequest GeomReq Tk_Get3DBorder 3DBorder Tk_Get3DBorderColors 3DBorder Tk_Get3DBorderFromObj 3DBorder
Tk_GetAllBindings BindTable Tk_GetAnchor GetAnchor Tk_GetAnchorFromObj GetAnchor Tk_GetAtomName InternAtom
Tk_GetBinding BindTable Tk_GetBitmap GetBitmap Tk_GetBitmapFromObj GetBitmap Tk_GetButtonMask EventHndlr
Tk_GetCapStyle GetCapStyl Tk_GetColor GetColor Tk_GetColorByValue GetColor Tk_GetColorFromObj GetColor
Tk_GetColormap GetClrmap Tk_GetCursor GetCursor Tk_GetCursorFromData GetCursor Tk_GetCursorFromObj GetCursor
Tk_GetDash GetDash Tk_GetDoublePixelsFromObj GetPixels Tk_GetFont GetFont Tk_GetFontFromObj GetFont
Tk_GetFontMetrics FontId Tk_GetGC GetGC Tk_GetHINSTANCE GetHINSTANCE Tk_GetHWND GetHWND
Tk_GetImage GetImage Tk_GetImageModelData CrtImgType Tk_GetItemTypes CrtItemType Tk_GetJoinStyle GetJoinStl
Tk_GetJustify GetJustify Tk_GetJustifyFromObj GetJustify Tk_GetMMFromObj GetPixels Tk_GetNumMainWindows MainWin
Tk_GetOption GetOption Tk_GetOptionInfo SetOptions Tk_GetOptionValue SetOptions Tk_GetOtherWindow WinUtil
Tk_GetPixels GetPixels Tk_GetPixelsFromObj GetPixels Tk_GetPixmap GetPixmap Tk_GetRelief GetRelief
Tk_GetReliefFromObj GetRelief Tk_GetRootCoords GetRootCrd Tk_GetScreenMM GetPixels Tk_GetScrollInfo GetScroll
Tk_GetScrollInfoObj GetScroll Tk_GetSelection GetSelect Tk_GetUid GetUid Tk_GetUserInactiveTime Inactive
Tk_GetVRootGeometry GetVRoot Tk_GetVisual GetVisual Tk_Grab Grab3 Tk_HWNDToWindow HWNDToWindow
Tk_HandleEvent HandleEvent Tk_Height WindowId Tk_IdToWindow IdToWindow Tk_ImageChanged ImgChanged
Tk_Init Tk_Init Tk_InitConsoleChannels CrtConsoleChan Tk_InitOptions SetOptions Tk_InitStubs TkInitStubs
Tk_InternAtom InternAtom Tk_InternalBorderBottom WindowId Tk_InternalBorderLeft WindowId Tk_InternalBorderRight WindowId
Tk_InternalBorderTop WindowId Tk_Interp WindowId Tk_IntersectTextLayout TextLayout Tk_IsContainer WindowId
Tk_IsEmbedded WindowId Tk_IsMapped WindowId Tk_IsTopLevel WindowId Tk_Main Tk_Main
Tk_MainLoop MainLoop Tk_MainWindow MainWin Tk_MaintainGeometry MaintGeom Tk_MakeContainer WinUtil
Tk_MakeWindow WinUtil Tk_MakeWindowExist CrtWindow Tk_ManageGeometry ManageGeom Tk_MapWindow MapWindow
Tk_MeasureChars MeasureChar Tk_MeasureCharsInContext MeasureChar Tk_MinReqHeight WindowId Tk_MinReqWidth WindowId
Tk_MoveResizeWindow ConfigWind Tk_MoveToplevelWindow MoveToplev Tk_MoveWindow ConfigWind Tk_Name Name
Tk_NameOf3DBorder 3DBorder Tk_NameOfAnchor GetAnchor Tk_NameOfBitmap GetBitmap Tk_NameOfCapStyle GetCapStyl
Tk_NameOfColor GetColor Tk_NameOfCursor GetCursor Tk_NameOfFont GetFont Tk_NameOfImage NameOfImg
Tk_NameOfJoinStyle GetJoinStl Tk_NameOfJustify GetJustify Tk_NameOfRelief GetRelief Tk_NameToWindow Name
Tk_NewWindowObj WindowId Tk_OwnSelection OwnSelect Tk_Parent WindowId Tk_ParseArgv ParseArgv
Tk_PathName Name Tk_PhotoBlank FindPhoto Tk_PhotoExpand FindPhoto Tk_PhotoGetImage FindPhoto
Tk_PhotoGetSize FindPhoto Tk_PhotoPutBlock FindPhoto Tk_PhotoPutZoomedBlock FindPhoto Tk_PhotoSetSize FindPhoto
Tk_PointToChar TextLayout Tk_PostscriptFontName FontId Tk_PreserveColormap GetClrmap Tk_QueueWindowEvent QWinEvent
Tk_RedrawImage GetImage Tk_ReqHeight WindowId Tk_ReqWidth WindowId Tk_ResetUserInactiveTime Inactive
Tk_ResizeWindow ConfigWind Tk_RestackWindow Restack Tk_RestoreSavedOptions SetOptions Tk_RestrictEvents RestrictEv
Tk_SafeInit Tk_Init Tk_Screen WindowId Tk_ScreenNumber WindowId Tk_SendVirtualEvent EventHndlr
Tk_SetAppName SetAppName Tk_SetBackgroundFromBorder 3DBorder Tk_SetCaretPos SetCaret Tk_SetClass SetClass
Tk_SetClassProcs SetClassProcs Tk_SetGrid SetGrid Tk_SetInternalBorder GeomReq Tk_SetInternalBorderEx GeomReq
Tk_SetMinimumRequestSize GeomReq Tk_SetOptions SetOptions Tk_SetWindowBackground ConfigWind Tk_SetWindowBackgroundPixmap ConfigWind
Tk_SetWindowBorder ConfigWind Tk_SetWindowBorderPixmap ConfigWind Tk_SetWindowBorderWidth ConfigWind Tk_SetWindowColormap ConfigWind
Tk_SetWindowVisual SetVisual Tk_SizeOfBitmap GetBitmap Tk_SizeOfImage GetImage Tk_StrictMotif StrictMotif
Tk_TextLayoutToPostscript TextLayout Tk_TextWidth MeasureChar Tk_Uid GetUid Tk_UndefineCursor ConfigWind
Tk_UnderlineChars MeasureChar Tk_UnderlineCharsInContext MeasureChar Tk_UnderlineTextLayout TextLayout Tk_Ungrab Grab3
Tk_UnmaintainGeometry MaintGeom Tk_UnmapWindow MapWindow Tk_UnsetGrid SetGrid Tk_UseWindow WinUtil
Tk_Visual WindowId Tk_Width WindowId Tk_WindowId WindowId Tk_X WindowId
Tk_Y WindowId
}]
# dictionary of links on pages that should link to a page
# not identical to the link text.
# The keys of this dict are filenames (nroff files),
# the value for each key is a mapping with <cmdText filename ?cmdText filename ...?>
# where 'cmdText' is the command name mentioned in the manual and 'filename' is the
# name of the manual file in which the command is described
# (the key to this dictionary refers to the nroff file name):
set tclCmdListRemap [dict create {*}{
binary {tcl_platform tclvars}
class {oo::object object oo::define define}
classvariable {oo::objdefine objdefine}
configurable {oo::define define oo::objdefine objdefine}
copy {oo::class class oo::object object}
define {oo::class class oo::objdefine objdefine oo::define define oo::object object oo::Slot Slot}
filename {auto_path tclvars platform tclvars tcl_platform tclvars}
info {Tcl_CreateObjCommand CrtObjCmd tcl_library tclvars tcl_patchLevel tclvars oo::define define oo::objdefine objdefine oo::class class}
interp {env tclvars Tcl_Eval Eval}
library {Tcl_AppInit AppInit}
load {Tcl_StaticLibrary StaticLibrary}
lsearch {re\_syntax re_syntax}
mathfunc {Tcl_CreateObjCommand CrtObjCmd tcl_platform tclvars}
memory {Tcl_InitMemory DumpActiveMemory Tcl_Alloc Alloc Tcl_Free Alloc}
msgcat {tcl_pkgPath tclvars}
my {oo::object object oo::define objdefine}
namespace {Tcl_EvalObjv Eval Tcl\_GetIndexFromObj GetIndex}
package {pkg_mkIndex pkgMkIndex}
packagens {pkg_mkIndex pkgMkIndex}
pkg_mkIndex {Tcl_PkgProvide PkgRequire Tcl_PkgRequire PkgRequire}
platform {tcl_platform tclvars tcl_platform(platform) tclvars}
platform_shell {tcl_platform(platform) tclvars}
process {Tcl_ReapDetachedProcs DetachPids Tcl_WaitPid DetachPids}
refchan {Tcl_DriverGetHandleProc SetChanErr Tcl_DriverHandlerProc SetChanErr Tcl_DriverFlushProc SetChanErr}
regexp {re\_syntax re_syntax}
regsub {re\_syntax re_syntax}
safe {auto_path tclvars tcl_library tclvars auto_index tclvars auto_reset tclvars pkg_mkIndex pkgMkIndex library library}
socket {Tcl_DoOneEvent DoOneEvent}
string {Tcl_GetBoolean GetInt Tcl_GetDoubleFromObj DoubleObj Tcl_GetBignumFromObj IntObj}
switch {re\_syntax re_syntax}
tclvars {Tcl_SetObjErrorCode AddErrInfo}
timerate {Tcl_EvalObjEx Eval}
tm {auto_path tclvars tcl_pkgPath tclvars}
unknown {auto_load library auto_execok library auto_noload library auto_noexec library}
}]
# dictionary of pages in which specific cmd words should *not* be linked
# as they represent something else in that context
# (exclude_refs_map taken from core tools/tcltk-man2html.tcl of version d2328814c619
# and supplemented as we go and find more places).
# The key to this dictionary refers to the nroff file name:
set tclCmdListExclude [dict create {*}{
bind {button destroy option}
clock {next}
canvas {bitmap text}
chan {read}
checkbutton {image}
cookiejar {destroy configure info error set}
console {eval}
clipboard {string}
define {variable}
entry {string}
event {return}
expr {variable}
file {socket}
font {menu}
getOpenFile {file open text}
grab {global}
history {exec}
http {error Tcl binary}
info {coroutine proc}
interp {time}
menu {checkbutton radiobutton}
messageBox {error info}
next {unknown destroy}
options {bitmap image set}
radiobutton {image}
regexp {binary}
safe {join split}
scale {label variable}
scrollbar {set}
selection {string}
tcltest {error Tcl}
tclvars {Tcl split}
text {bind image lower raise}
timerate {lindex}
tkvars {tk}
tkwait {variable}
tm {exec}
trace {variable rename unset read}
transchan {read}
try {error return break continue}
zlib {binary close filename text time}
ttk_checkbutton {variable}
ttk_combobox {selection}
ttk_entry {focus variable}
ttk_intro {focus text}
ttk_label {font text}
ttk_labelframe {text}
ttk_menubutton {flush}
ttk_notebook {image text}
ttk_progressbar {variable}
ttk_radiobutton {variable}
ttk_scale {variable}
ttk_scrollbar {set}
ttk_spinbox {format}
ttk_treeview {text open focus selection}
ttk_widget {image text variable}
TclZlib {binary flush filename text}
}]
}
proc ::ndoc::BIRPstrip {text} {
#
# removes any \fB, \fI, \fP and \fR nroff markup from a text
#
return [string map {{\fB} {} {\fI} {} {\fR} {} {\fP} {}} $text]
}
proc ::ndoc::BIRPclean {text} {
#
# cleanup \fB, \fI, \fP and \fR nroff markup to be more regular
#
# text - raw nroff text to clean up the BIR markup in
#
# Returns the cleaned nroff
#
# We want to clean a bit up here so that spaces do not become part of
# Emphasis or Strong (typically found in the 'Synopsis' section):
#
# "\fBappend \fIvarName \fR?\fIvalue value value ...\fR?"
# and "\fBdict merge \fR?\fIdictionaryValue ...\fR?"
#
# should be
#
# "\fBappend\fR \fIvarName\fR ?\fIvalue value value ...\fR?"
# and "\fBdict merge\fR ?\fIdictionaryValue ...\fR?"
#
#
# This hould NOT apply to: "\fBTk_CreateClientMessageHandler\fR arranges for \fIproc\fR",
# i.e. when \fR is in between ...
# so for simplicity we do not allow a backslash in between
#
# Note: the procedure does not yet catch all instances that could need cleanup
#
# Note that \fB followed by \fI will not give us bold+italic
# but rather switch from bold only to italic only
#
# Note: we here treat \fP as if it is \fR since the Tk sources do not
# seem to use \fP in other cases. Thus, any \fP is changed to \fR
#
set state N
set out {}
# some initial cleaning, changing bold and italic whitespace to normal whitespace:
set text [string map {{\fB \fI} {\fR \fI}} $text]
set text [string map {{\fI \fB} {\fR \fB}} $text]
for {set i 0} {$i < [string length $text]} {incr i} {
set char [string index $text $i]
set lookahead [string range $text [expr {$i+1}] [expr {$i+2}]]
set lookfurther [string index $text [expr {$i+3}]]
set lookback [string index $text [expr {$i-1}]]
set lookback2 [string range $text [expr {$i-2}] [expr {$i-1}]]
if {$char ne "\\"} {
append out $char
} else {
# command found with backslash as first character:
if {$lookahead ni {fB fI fR fP}} {
# no BIRP, keep backslash:
append out $char
} else {
# BIRP found (current char is the backslash in front):
switch $state {
N - R - P {
switch $lookahead {
fB {append out \\fB; set state B}
fI {append out \\fI; set state I}
fR {return -code error "fR without previous fI/fB in: $text"}
fP {return -code error "fP without previous fI/fB in: $text"}
}
}
B {
switch $lookahead {
fB {return -code error "dirty BIRP: fB following fB in: $text"}
fR - fP {
if {$lookback eq { }} {
set out [string range $out 0 end-1]
append out \\fR { }
} else {
append out \\fR
}
set state N
}
fI {
if {$lookback eq { }} {
set out [string range $out 0 end-1]
append out \\fR { }
} elseif {$lookback2 eq " ?"} {
set out [string range $out 0 end-2]
append out \\fR { ?}
} else {
append out \\fR
}
if {$lookfurther eq { }} {append out { }; incr i}
append out \\fI
set state I
}
}
}
I {
switch $lookahead {
fB {
if {$lookback eq { }} {
set out [string range $out 0 end-1]
append out \\fR { }
} else {
append out \\fR
}
if {$lookfurther eq { }} {append out { }; incr i}
append out \\fB
set state B
}
fR - fP {
if {$lookback eq { }} {
set out [string range $out 0 end-1]
append out \\fR { }
} else {
append out \\fR
}
set state N
}
fI {return -code error "dirty BIR: fI following fI in: $text"}
}
}
}
incr i 2
}
}
}
return $out
}
proc ::ndoc::BIR2markdown {text} {
#
# takes cleaned BIR nroff and translates it into markdown
#
# - this proc is currently not used anywhere -
#
set state N
set md {}
for {set i 0} {$i < [string length $text]} {incr i} {
set char [string index $text $i]
set lookahead [string range $text [expr {$i+1}] [expr {$i+2}]]
# we need to always escape asterisks as they have special meaning in markdown:
if {$char eq "*"} {append md \\}
if {$char ne "\\"} {
append md $char
} elseif {$char eq "\\" && [string index $lookahead 0] eq "e"} {
append md "\\\\"
incr i
} else {
# ignore the backslash:
incr i
if {$lookahead ni {fB fI fR}} {
append md [string index $text $i]
} else {
switch $state {
N - R {
switch $lookahead {
fB {append md **; set state B}
fI {append md *; set state I}
fR {return -code error "fR without previous fI/fB in: $text"}
}
}
B {
switch $lookahead {
fB {append md {** **}}
fR {append md **; set state N}
fI {append md {** *}; set state I}
}
}
I {
switch $lookahead {
fB {append md {* **}; set state B}
fR {append md *; set state N}
fI {append md {* *}}
}
}
}
incr i
}
}
}
return $md
}
proc ::ndoc::parseArgs {line} {
#
# Takes a line with an nroff macro call and returns a list of the arguments
#
# line - a line of nroff with a macro call and its arguments
#
set res [list]
set stopHere 0
set startIndex 4
while {! $stopHere} {
if {[string index $line $startIndex] eq "\""} {
# text in quotes
incr startIndex
set endIndex [string first \" $line $startIndex]
if {$endIndex == -1} {return -code error "no matching quote found"}
if {$endIndex == [string length $line] - 1} {
set stopHere 1
set endIndex end-1
} else {
incr endIndex -1
set nextIndex [expr {$endIndex + 3}]
}
} else {
# no quotes
set endIndex [string first { } $line $startIndex]
if {$endIndex == -1} {
set endIndex end
set stopHere 1
} else {
incr endIndex -1
set nextIndex [expr {$endIndex + 2}]
}
}
lappend res [string range $line $startIndex $endIndex]
if {! $stopHere} {set startIndex $nextIndex}
}
return $res
}
proc ::ndoc::parseQuoting {line} {
#
# parse a .QW, .PQ or .QR nroff macro
# that is formatted as a space-separated two or more element list
# with possible embedded spaces in quoted text
#
# line - a line of nroff with a .QW or .PQ or .QR tag
#
# Returns raw text with normal text quotation marks
# surrounded by an extra § character.
#
# .PQ adds parenthesis arount the quotes.
# .QR adds a dash between the first two elements
#
# The § are embedded so the nroff inline parser can transform this to a "Quoted" AST element
# instead of treating the quote as a literal character
#
# Example: '.QW "the end" .' gives us '§"the end"§.'
#
set stop 0
set type [string range $line 1 2]
if {$type eq "PQ"} {set quotedText "("}
# split text into the two or three elements:
lassign [parseArgs $line] argText(1) argText(2) argText(3)
append quotedText §\" $argText(1)
# make the broken ctags happy ...: "
if {$type eq "QR"} {
append quotedText - $argText(2) \"§
} else {
append quotedText \"§ $argText(2)
}
if {$type eq "PQ"} {append quotedText ")"}
append quotedText $argText(3)
return $quotedText
}
proc ::ndoc::parseBackslash {text} {
#
# parses an nroff text string and handles escaping of characters
# (both removing or adding backslashes)
#
# \u005ce \u005c = \e -> \
# \u005c- - = \- -> - (dash)
# \N'34' \" = \N'34' -> "
# \\(en – = \(en -> – (em-dash)
# \\(-> \u2192 = \(-> -> -> (arrow)
# \\\\ = \\ -> undo backslash escaping during parsing, it will be added by the markdown writer if needed
# \\| = {} -> zero-width narrow space (1/6 em)
# \\0 = { } -> digit-width space (a space that is exactly the same width as a digit (0–9) in the current font)
# \\& = {} -> zero-width non-printing character (often followed by a literal dot to prevent interpretations as a macro command when located at the beginning of a line)
#
# Note: this procedure does not handle the \f... sequences
# (\fB, \fI and \fR are handled by BIRPclean, BIRPstrip and parseInline)
#
# Returns the transformed text
#
set text [string map {
\u005ce \u005c
\u005c- -
\N'34' \"
\\(en –
\\(em \u2014
\\(-> \u2192
\\\\ \\
\\| {}
\\0 { }
\\& {}
\\(fm '
} $text]
return $text
}
proc ::ndoc::man2AST {manContent} {
#
# parses the data in manContent
# interpreting it as nroff format inlcuding Tcl macros,
# and converting it into an abstract syntax tree (AST)
#
# manContent - the content of a file containing an nroff formatted manual page
#
# The procedure fills the global dict 'manual' with four elements:
# - copyright = a list of copyright entries
# - meta = a list of some metadata elements and their values (see below in the .TH branch)
# - content = the AST
# - name = the name of the manual page
#
variable manual
variable verbose
dict set manual copyright [list]
dict set manual meta [list]
dict set manual content [list]
set manContent [split $manContent \n]
if {$verbose} {puts "++++ processing blocks ++++"}
set blockAST [parseBlock Document $manContent]
#foreach element $blockAST {puts $element\n}; puts +++++++++++++++++++++++; exit
if {$verbose} {puts "++++ expanding blocks ++++"}
# this also parses the Inline elements:
set expandedBlocks [blocksExpand $blockAST]
dict set manual content [list Document {} $expandedBlocks]
if {$verbose} {puts "++++++++ end ++++++++++++++"}
#foreach element $expandedBlocks {puts $element\n}; exit
}
proc ::ndoc::blocksExpand {blockList} {
#
# takes a hierarchical list of blocks and processes them in breadth-first order
# to parse the inline content and convert it into proper inline AST elements
#
# blockList - a list of AST block elements with unparsed inline content
#
# Returns a modified AST with the parsed inline elements
#
variable manual
set newList [list]
foreach block $blockList {
lassign $block blockType blockAttributes blockContent
switch $blockType {
List - Dlist {
lappend newList [list $blockType $blockAttributes [blocksExpand $blockContent]]
}
ListItem - DlistItem {
if {$blockType eq "DlistItem"} {
set content [dict get $blockAttributes -definition]
if {[string range $content 0 5] in {METHOD OPTION COMMAN}} {
# a Tcl syntax element to convert to proper custom AST
set startIndex [string first "_" $content]
incr startIndex
set content [string range $content $startIndex end]
dict set blockAttributes -definition [parseCommand -ast $content]
} else {
dict set blockAttributes -definition [list [parseInline Inline {} $content]]
}
}
lappend newList [list $blockType $blockAttributes [blocksExpand $blockContent]]
}
Span - Div {
# Spans and Divs already come fully expanded, so just add them as they are:
lappend newList $block
}
default {
lappend newList [parseInline $blockType $blockAttributes $blockContent]
}
}
}
return $newList
}
proc ::ndoc::parseBlock {parent manContent} {
#
# parses an nroff document and splits it into its block elements
#
# parent - the surrounding AST block element, i.e. the block in which we are now operating
# manContent - a list of nroff lines to parse
#
# This procedure just splits the whole document into blocks, it does
# not look into the block content and processes the Inlines.
#
# Returns a replacement AST (a list of block elements) for the blocks specified in manContent
#
# Note: this procedure also extracts the 'KEYWORDS' and 'SEE ALSO' sections
# and moves their content into the metadata. This enables
# putting that information anywhere during output
#
#
variable manual
variable verbose
variable sectionTitles
# the accumulative list of blocks so far:
set blockList [list]
# which blockType this one is (inside of $parent):
set blockType {}
# the content of the current block:
set blockContent {}
# a set of attributes for the block (options of an AST element)
set blockAttributes [list]
# a flag, whether a new block starts, so we can finalise the current one.
# when this flag is set, the currently read line is kept and a block is finalised
# before digesting the current line (in a repeated run of the while loop)
set doCloseBlock 0
while {[llength $manContent] > 0} {
if {$doCloseBlock} {
if {$blockContent ne ""} {
# sometimes .PP is directly followed by .CS, producing empty paragraphs
# which we want to ignore
lappend blockList [list $blockType $blockAttributes $blockContent]
if {$verbose} {puts "... closed block: [lindex $blockList end]"}
}
set doCloseBlock 0
set blockType {}
set blockContent {}
set blockAttributes [list]
}
set line [lindex $manContent 0]
if {$verbose} {puts "\nLINE = ->$line<-"}
set markup [string range $line 0 2]
if {$verbose} {puts "MARKUP = ->$markup<-"}
switch -- $markup {
{.\"} - {'\"} {
# a comment, we only collect copyright info here for now
# and put it into the metadata
if $verbose {puts COMMENT}
if {[lindex $line 1] eq "Copyright"} {
if $verbose {puts COPYRIGHT}
dict lappend manual copyright [lrange $line 1 end]
}
# remember the wording of the last comment since we can use it for
# detecting lines with Tcl command syntax:
dict set manual lastComment [lindex $line 1]
set manContent [lrange $manContent 1 end]
}
.so - .BS - .BE - .AS - .ta - .RS - .RE - .nf - .fi - .ta {
# can be ignored
# .so = include files
# .BS .BE = start and end of box enclosure
# .AS = maximum sizes of arguments for setting tab stops
# .ta = set tab stops
# .RS .RE = relative inset, i.e. indentation
# .nf .fi = turn off/on filling of lines
# .ta = tabulator settings
if $verbose {puts "IGNORED ($markup)"}
set manContent [lrange $manContent 1 end]
}
.TH {
# title heading
if $verbose {puts TH}
lassign $line - commandName manualSection version tclPart tclDescription
if {$version eq ""} {set version unknown}
dict lappend manual meta \
CommandName $commandName \
ManualSection $manualSection \
Version $version \
TclPart $tclPart \
TclDescription $tclDescription
set manContent [lrange $manContent 1 end]
}
.TP - .IP {
#set verbose 1
### ... what about a .TP inside a .RS/.RE pair inside a .TP ... as in file(n)?
# .TP = tagged paragraph, used as a delimiter between e.g. subcommands
# .IP = indented paragraph, used for short lists where the label and the description are often in one line
#
# We interpret these lists as definition list or simple list depending on the context.
# .TP is always a definition list
# .IP is a bullet list when "\(bu 3" is used, a numbered list when "[1]" or "(1)" or "1)" is used
# and a definition list when other text is used
# Once an .IP list starts, it cannot change to .TP in the middle
#
# Todo: StdChannels.3 uses
# ../nroff/tcl9.0/doc/StdChannels.3:.IP 1)
# ../nroff/tcl9.0/doc/StdChannels.3:.IP 2)
# ../nroff/tcl9.0/doc/StdChannels.3:.IP (a)
# ../nroff/tcl9.0/doc/StdChannels.3:.IP (b)
# ../nroff/tcl9.0/doc/StdChannels.3:.IP 3)
#
if {$blockType ne ""} {set doCloseBlock 1; continue}
set blockType Dlist
lassign [parseArgs $line] number
set subType [string range $markup 1 end]
set blockAttributes [list]
if {$subType eq "IP"} {
# do we have a simple bullet/numbered list here?
if {[string match {\[[0-9]\]} $number]} {set blockType List; set blockAttributes [list -type numbered]}
if {[string match {([0-9])} $number]} {set blockType List; set blockAttributes [list -type numbered]}
if {[string match {[0-9])} $number]} {set blockType List; set blockAttributes [list -type numbered]}
if {[string match {\\(bu} $number]} {set blockType List; set blockAttributes [list -type bullet]}
}
if $verbose {puts "$blockType (subtype $subType)"}
# collect all material until the end of the definition list
# - if a .TP item has more than one paragraph or a code block, then it is wrapped into a pair of .RS/.RE
# - the list ends at the next unwrapped .PP or .LP or at .SH/.SS
set itemTitle {}
set itemContent {}
set itemVS [list]
set dlistContent [list]
set finishDlist 0
# the following tells us whether we are in a normal paragraph of an item (dlistState = empty string)
# or in an .RS/.RE pair of a .TP list (dlistState = inset)
set dlistState {}
while {! $finishDlist} {
if $verbose {puts "---\nline: $line"}
switch -- $markup {
.RS {
# more than just a simple paragraph (but only for .TP)
if $verbose {puts "inset starts"}
set dlistState inset
}
.RE {
# next item comes or end of list
if $verbose {puts "inset ends"}
set dlistState {}
}
.PP - .LP {
if {$dlistState eq "inset"} {
if $verbose {puts "new paragraph in inset"}
# - inside .RS/.RE we are still within one item
lappend itemContent $line
} else {
# - outside, the list ends
if $verbose {puts "finish dlist"}
set finishDlist 1
}
}
.SH - .SS {
if $verbose {puts "SH/SS - finish list"}
set finishDlist 1
}
.TP - .IP {
if $verbose {puts "TP/IP found"}
if {$dlistState eq "inset"} {
# a list nested within a list item
lappend itemContent $line
} else {
# new item starts, so finish the current one, if any
if {$itemTitle ne ""} {
if {$itemContent eq ""} {set itemContent "see below ..."}
if $verbose {puts "finish ${blockType} item:\n+++\n$itemContent\n+++\n"}
if {$blockType eq "Dlist"} {set itemAttr [list -definition $itemTitle]} else {set itemAttr [list]}
if {[llength $itemVS]} {lappend itemAttr {*}$itemVS}
set itemVS [list]
lappend dlistContent [list ${blockType}Item $itemAttr [parseBlock ${blockType}Item $itemContent]]
if $verbose {puts "dlistContent: $dlistContent"}
}
# !! subType can change in the middle of a .TP list !!
set subType [string range $markup 1 end]
# start new item
if $verbose {puts "start new dlist item"}
if {$subType eq "IP"} {
# itemTitle is on the same line
lassign [parseArgs $line] itemTitle
set itemTitle [parseBackslash [BIRPclean $itemTitle]]
} else {
# itemTitle is on the next line
set manContent [lrange $manContent 1 end]
set itemTitle [parseBackslash [BIRPclean [lindex $manContent 0]]]
# if we are supposed to see a COMMAND, METHOD or OPTION here,
# as determined by the comment line above the .TP line,
# then mark it as such so that expandBlock can handle it nicely:
# (skip RegConfig.3 as it has non-standard syntax for generated Tcl-level commands)
if {[dict get $manual lastComment] in {OPTION: METHOD: COMMAND: OPTION METHOD COMMAND} && [dict get $manual fileName] ne "RegConfig"} {
set itemTitle [dict get $manual lastComment]_$itemTitle
}
}
set itemContent {}
}
}
. - .\\\" {
# make broken ctags happy: "
if $verbose {puts "ignore"}
# ignore
}
.VS {
lassign $line - info
set itemVS [list -vs $info]
}
.VE {
# we assume that VS does not span more than one TP/IP
# so we automatically reset this info when the next TP/IP starts
}
default {
# just collect item material
if $verbose {puts "collect dlist item ($line)"}
lappend itemContent $line
}
}
if {! $finishDlist} {
# prepare next line
set manContent [lrange $manContent 1 end]
if {[llength $manContent] == 0} {
# emergency stop:
break
}
set line [lindex $manContent 0]
set markup [string range $line 0 2]
}
}
# the list is over, finish it and look for the next block
if $verbose {puts "finish dlist"}
if {$itemContent eq ""} {set itemContent "see below ..."}
# as the content of the DlistItem block is itself some blocks, we need to parse it again here:
if $verbose {puts "finish last dlist item:\n+++\n$itemContent\n+++\n"}
if {$blockType eq "Dlist"} {set itemAttr [list -definition $itemTitle]} else {set itemAttr [list]}
if {[llength $itemVS]} {lappend itemAttr {*}$itemVS}
lappend dlistContent [list ${blockType}Item $itemAttr [parseBlock ${blockType}Item $itemContent]]
if $verbose {puts "dlistContent: $dlistContent"}
set blockContent $dlistContent
set doCloseBlock 1
}
.SH {
# section heading (assumption: everything is on one single line)
# this will typically also be one ending a block of "AP" elements
dict set manual lastComment {}
if {$blockType ne ""} {set doCloseBlock 1; continue}
if $verbose {puts Section}
set SHcontent [string totitle [string trim [string range $line 3 end] \"\ ]]
# add to list of possible cross reference targets:
lappend sectionTitles $SHcontent
switch $SHcontent {
"Keywords" - "See also" {
# the content of this section is just a list of keywords
# -> read them and transfer to metadata:
array set SHType {Keywords Keywords "See also" Links}
set markup {}
set keywords [list]
while {1} {
set manContent [lrange $manContent 1 end]
set line [lindex $manContent 0]
set markup [string index $line 0]
if {$markup ni {. '} && [llength $manContent] > 0} {
lappend keywords {*}[split [string trim $line {, }] ,]
} else {
set keywords [lmap el $keywords {string trim $el}]
dict lappend manual meta $SHType($SHcontent) $keywords
break
}
}
}
"Synopsis" {
# this is the place where the commands are listed with their syntax:
lappend blockList [list Header {-level 1} $SHcontent]
# go to first line of section content:
set manContent [lrange $manContent 1 end]
set line [lindex $manContent 0]
# the Tcl.n page is special (has no command syntax):
if {[dict get $manual fileName] eq "Tcl"} {
lappend blockList [list Paragraph {} $line]
set manContent [lrange $manContent 1 end]
continue
}
set cmd [string range $line 0 2]
# the content of this section is some command syntax
# with one command per line
set contentList [list]
set lineCount 0
while {$cmd ne ".SH"} {
if {! [string match ".*" $cmd]} {
# in the synopsis of section 3 pages there are lines of their own with
# the return type of the Tcl API function. We want to get them onto the same
# line as the command for processing:
if {[dict get $manual meta ManualSection] == 3 && [string range $line 0 2] ne "\\fB"} {
set line "#$line "
incr lineCount
append line [lindex $manContent $lineCount]
}
lappend contentList [list Syntax {} [parseCommand -ast $line]]
}
# go to next line:
incr lineCount
set line [lindex $manContent $lineCount]
set cmd [string range $line 0 2]
}
# add to AST wrapped in a fenced div:
lappend blockList [list Div .synopsis $contentList]
# remove eaten lines from manContent:
set manContent [lrange $manContent $lineCount end]
}
"Arguments" {
# C API function arguments
#
# (.AP is a normal one)
# (.AS should be the longest argument name, only used for nroff formatting, can be ignored here)
#
# two examples:
# .AP "struct stat" *statPtr out --> markdown term: [*statPtr]{.carg .out type="struct stat"}
# .AP "const char" *path in --> markdown term: [*path]{.carg .in type="const char"}
#
# every line starting with .AP is the term of a definition-list item, followed by
# one or more lines with explanatory text making up that item's definition
# (same Dlist/DlistItem AST used for .TP/.IP lists, so it gets rendered as native
# Pandoc definition-list markdown, e.g. "Term\n: Definition", instead of a
# hand-parsed fenced div):
lappend blockList [list Header {-level 1} $SHcontent]
# go to first line of section content:
set manContent [lrange $manContent 1 end]
set line [lindex $manContent 0]
set cmd [string range $line 0 2]
set dlistContent [list]
set lineCount 0
set argName ""
while {$cmd ne ".SH"} {
if {$cmd eq ".AP"} {
# finish previous carg:
if {$argName ne ""} {
set cargTerm [list Span ".carg .$argDirection type=\"$argType\"" [list [list Text {} $argName]]]
set cargExplanation [lindex [parseInline Inline {} [string trim $argExplanation]] 2]
lappend dlistContent [list DlistItem [list -definition [list $cargTerm]] \
[list [list Paragraph {} $cargExplanation]]]
}
# new carg:
lassign $line - argType argName argDirection
if {$argDirection eq ""} {set argDirection inout}
set argExplanation ""
} elseif {$cmd in {.AS .BS .BE}} {
# .AS = max size hint for tab stops; .BS .BE = box enclosure: can be ignored
} else {
# explanatory text:
append argExplanation $line { }
}
# next line:
incr lineCount
set line [lindex $manContent $lineCount]
set cmd [string range $line 0 2]
}
# finish last carg:
if {$argName ne ""} {
set cargTerm [list Span ".carg .$argDirection type=\"$argType\"" [list [list Text {} $argName]]]
set cargExplanation [lindex [parseInline Inline {} [string trim $argExplanation]] 2]
lappend dlistContent [list DlistItem [list -definition [list $cargTerm]] \
[list [list Paragraph {} $cargExplanation]]]
}
# add to AST as a definition list, still wrapped in a fenced div so CSS can target
# ".arguments" specifically (e.g. to style the .carg direction/type badges):
lappend blockList [list Div .arguments [list [list Dlist {} $dlistContent]]]
# remove eaten lines from manContent:
set manContent [lrange $manContent $lineCount end]
}
"Class hierarchy" {
# this is a section only present for oo commands
# and presenting a hierarchical view of the object in the man page
lappend blockList [list Header {-level 1} $SHcontent]
# go to first line of section content after the .nf
# (assuming no blank lines and identical formatting in all relevant pages):
set manContent [lrange $manContent 2 end]
set line [lindex $manContent 0]
set cmd [string range $line 0 2]
set contentList [list]
set lineCount 0
while {$cmd ne ".fi"} {
lappend contentList [BIRPstrip $line]
# go to next line:
incr lineCount
set line [lindex $manContent $lineCount]
set cmd [string range $line 0 2]
}
set contentList [join [parseBackslash $contentList] \n]
lappend blockList [list Div .classhierarchy [list [list Code {} $contentList]]]
set manContent [lrange $manContent $lineCount end]
}
default {
# add section to AST
lappend blockList [list Header {-level 1} $SHcontent]
set manContent [lrange $manContent 1 end]
}
}
}
.SS {
# subsection heading (assumption: everything is on one single line)
dict set manual lastComment {}
if {$blockType ne ""} {set doCloseBlock 1; continue}
if $verbose {puts Subsection}
set SScontent [string totitle [string trim [string range $line 3 end] \"\ ]]
# add to list of possible cross reference targets:
lappend sectionTitles $SScontent
#return [list [list Header {-level 2} $SScontent] {*}[parseBlock Header [lrange $manContent 1 end]]]
lappend blockList [list Header {-level 2} $SScontent]
set manContent [lrange $manContent 1 end]
}
.PP - .LP - . {
# beginning of new paragrah
if {$blockType ne ""} {set doCloseBlock 1; continue}
if $verbose {puts PP/LP/.}
set blockType Paragraph
set manContent [lrange $manContent 1 end]
}
.CS {
# code start
if {$blockType ne ""} {set doCloseBlock 1; continue}
if $verbose {puts "CODE"}
set blockType Code
set manContent [lrange $manContent 1 end]
}
.CE - .VE - .DE {
# .CE = code end
# .VE = end of sidebar
# .DE = end of display section
set doCloseBlock 1
set manContent [lrange $manContent 1 end]
continue
}
.QW - .PQ - .QR {
# this is not a block element of the AST but it is a single line in nroff so we must handle it here.
# We convert this to Inline quotes and append to the current content
# with a special syntax starting with "§" and ending with "§"
# (this enables us to distinguish between a quoted text and a literal quote character)
# ToDo: this is often used to write inline Tcl code -> try to detect automatically!
if {$blockType eq ""} {set blockType Paragraph}
if {$verbose} {puts "Quote"}
set myText [parseQuoting $line]
if {$blockContent eq ""} {append blockContent $myText} else {append blockContent { } $myText}
set manContent [lrange $manContent 1 end]
}
.VS - .DS {
# .VS = sidebar; for marking newly-changed parts of manual pages
# .DS = display section
# We just interpret these as a new paragraphs:
if {$blockType ne ""} {set doCloseBlock 1; continue}
set blockType Paragraph
switch $markup {
.VS {
lassign $line - info
set blockAttributes [list version $info]
}
.DS {
set blockAttributes [list DISPLAY yes]
}
}
set manContent [lrange $manContent 1 end]
}
.MT {
# empty string as two double quotes:
# this is not a block element of the AST but it is a single line in nroff so we must handle it here.
# We convert this to Inline quotes
if {$blockType eq ""} {set blockType Paragraph}
if {$verbose} {puts "Double quote pair"}
if {$blockContent eq ""} {append blockContent \"\"} else {append blockContent { } \"\"}
set manContent [lrange $manContent 1 end]
}
default {
# if nothing else, just collect content:
if {$blockType eq ""} {set blockType Paragraph}
if {$verbose} {puts "CONTENT of $blockType"}
if {$blockType eq "Code"} {set separator \n} else {set separator { }}
if {$blockContent eq ""} {append blockContent $line} else {append blockContent $separator $line}
set manContent [lrange $manContent 1 end]
}
}
}
# also process the last still open block:
if {$blockContent ne ""} {lappend blockList [list $blockType $blockAttributes $blockContent]}
if {$verbose} {puts "... produced [lindex $blockList end]"}
return $blockList
}
proc ::ndoc::parseCommand {mode line} {
#
# reads a line of the nroff containing a Tcl syntax (from the SYNOPSIS etc.)
# and returns a list of AST Span elements representing this syntax
#
# mode - the operation mode; '-ast' returns the AST block list, '-internal' returns the internal representation for easier parsing
# line - the complete Tcl command in nroff syntax
#
# Note: the Span elements are alread fully expanded with appropriate AST "Text" elements
#
set DEBUG 0
set line [BIRPclean $line]
# make life a bit easier for parsing by replacing nroff syntax with something simpler,
# so this is the internal representation:
# § is bold
# + is italic
# = is reset
set line [string map {{\fB} § {\fI} + {\fR} = {\fP} =} $line]
set line [string map {\\ {}} $line]
if {$mode eq "-internal"} {return $line}
set spanList [list]
set state =
set chunk {}
# some more processing is needed for section 3 pages:
if {[regexp {^.+\(.*\)$} $line]} {
if {$DEBUG == 3} {puts "===\nline API=$line"}
set l0 {}
set startIndex 0
if {[string index $line 0] eq "#"} {
# return code at the beginning, split into own word:
set startIndex [string first "§" $line]
set l0 [string trim [string range $line 0 [expr {$startIndex - 1}]]]
}
set openParens [string first ( $line $startIndex]
# the API function name:
set l1 [string range $line $startIndex [expr {$openParens - 1}]]
# the arguments to the function:
set l2 [string range $line [expr {$openParens + 1}] end-1]
if {$DEBUG == 3} {puts L0=$l0; puts L1=$l1; puts L2=$l2}
if {$l0 eq ""} {set line [list $l1 $l2]} else {set line [list $l0 $l1 $l2]}
} elseif {[string index $line 0] eq "§" && [string index $line 1] eq "#"} {
# an '#include' line in section 3:
if {$DEBUG == 3} {puts "line # = $line"; puts L=#}
return [list [list Strong {} [list [list Text {} [string range $line 1 end-1]]]]]
}
# [apply] code to expand the content of a Span (except Space) to contain a correct AST Text element:
set expandSpan [list spanList {
lmap el $spanList {
lassign $el sName sAttr sContent
if {$sName eq "Space"} {
set el
} else {
set el [list $sName $sAttr [list [list Text {} $sContent]]]
}
}
}]
# translate line to Span elements with Space elements in between:
if $DEBUG {puts "-------\nparseCommand: $line"}
set cmdType {}
# treat the line as a list so that we easily can detect the individual elements:
for {set i 0} {$i < [llength $line]} {incr i} {
set word [lindex $line $i]
if {$i == 0} {
# the first word
if $DEBUG {puts "1st-word: $word"}
switch -regexp $word {
{^§-.+=$} {
# (this comes first in the switch as otherwise the .cmd branch will match)
# a word starting with a dash (.i.e a mandatory literal but not a command!),
# should on occur in sections where OPTIONs are described, not whole commands:
lappend spanList [list Span .lit [string range $word 1 end-1]]
if $DEBUG {puts "single .lit describing a command options: $spanList"}
}
{^§[|<>2].*=} {
# special case for arg components in the exec command which are literals
lappend spanList [list Span .lit [string range $word 1 end-1]]
if $DEBUG {puts "single .lit describing an exec option: $spanList"}
}
{^§.+=$} {
# only one cmd without subcommand:
if {[string range $word 1 4] eq "Tcl_" || [string range $word 1 9] eq "TclZipfs_"} {
# API command:
set cmdType ccmd
} else {
set cmdType cmd
}
lappend spanList [list Span .$cmdType [string range $word 1 end-1]]
if $DEBUG {puts "single .cmd: $spanList"}
}
{^§.+[^=]$} {
# a cmd with a subcommand and possibly more elements:
lappend spanList [list Span .cmd [string range $word 1 end]]
# there must be a second word = subcommand,
# sometimes also more words and these are then literals
while 1 {
incr i
set word [lindex $line $i]
if {$i == 1} {set type .sub} else {set type .lit}
if {[string index $word end] eq "="} {
lappend spanList [list Space {} {}] [list Span $type [string range $word 0 end-1]]
break
} else {
lappend spanList [list Space {} {}] [list Span $type [string range $word 0 end]]
}
if {$i > [llength $line]} {
puts "emergencyStop 1 in parseCommand"
puts "Line: $line"
exit
}
}
if $DEBUG {puts ".cmd with subcommand: $spanList"}
}
{^\+.+=$} {
# an instance as a command name:
# (this one is normally followd by a subcommand)
lappend spanList [list Span .ins [string range $word 1 end-1]]
incr i
set sub [lindex $line $i]
if {[string index $sub 0] eq "?"} {
# not a subcommand anyway
# (rare case; e.g. for `coroutine`), so revert
incr i -1
} else {
lappend spanList \
[list Space {} {}] \
[list Span .sub [string range $sub 1 end-1]]
}
if $DEBUG {puts "instance command .ins: $spanList"}
}
{^#.+$} {
# the return type of a Tcl C API function
# (the '#' was prefixed in parseBlock so we can detect it here ...)
lappend spanList [list Span .ret [string range $word 1 end]] [list Space {} {}]
if $DEBUG {puts "section 3 return code .ret: $spanList"}
# remove the first word from the line and go again for the first word (avoid code duplication):
set line [lrange $line 1 end]
incr i -1
continue
}
default {
puts "emergencyStop 0 in parseCommand"
puts "Line: $line"
exit
}
}
set spanList [apply $expandSpan $spanList]
} else {
# remaining words of the command:
set sublist [list]
if $DEBUG {puts "word [expr {$i + 1}]: $word"}
if {$cmdType eq "ccmd"} {
# the arguments may be wrapped as a single \fI...\fR group (one leading/trailing marker)
# or as several individual \fI...\fR groups (one marker pair per argument), so strip
# all bold/italic/reset markers here:
set cargsText [string map {§ {} + {} = {}} $word]
if $DEBUG {puts "API arguments: $cargsText"}
lappend spanList [list Span .cargs [list [list Text {} $cargsText]]]
continue
}
switch -regexp $word {
{^\?\+.+ \.\.\.\=\?$} {
# possibly multiple optional args
# a word with trailing "..." and a space between
lappend sublist [list Span .optdot [string range $word 2 end-6]]
lappend spanList [list Space {} {}] {*}[apply $expandSpan $sublist]
if $DEBUG {puts "(multiple) optional .optdot: $spanList"}
}
{^\+.+=$} {
# single mandatory arg: .arg
# + followed by some word followed by =
lappend sublist [list Span .arg [string range $word 1 end-1]]
lappend spanList [list Space {} {}] {*}[apply $expandSpan $sublist]
if $DEBUG {puts "single mandatory .arg: $spanList"}
}
{^\+.+[^=]?$} {
# multiple mandatory args: .arg
lappend sublist [list Space {} {}] [list Span .arg [string range $word 1 end]]
# also get all other members of this group:
while 1 {
incr i
set word [lindex $line $i]
if {[string index $word end] eq "="} {
lappend sublist [list Space {} {}] [list Span .arg [string range $word 0 end-1]]
break
} else {
lappend sublist [list Space {} {}] [list Span .arg $word]
}
if {$i > [llength $line]} {
puts "emergencyStop 2 in parseCommand"
puts "Line: $line"
exit
}
}
lappend spanList {*}[apply $expandSpan $sublist]
if $DEBUG {puts "multiple mandartoy .arg: $spanList"}
}
{^\?\+.+=\?$} {
# single optional arg = .optarg
# ? followed by + followed by a word followed by = followed by ?
lappend sublist [list Span .optarg [string range $word 2 end-2]]
lappend spanList [list Space {} {}] {*}[apply $expandSpan $sublist]
if $DEBUG {puts "single optional arg .optarg: $spanList"}
}
{^§.+=$} {
# single mandatory literal = .lit
# (can also start with a dash and is then called a 'required option' in Tcl jargon):
lappend sublist [list Span .lit [string range $word 1 end-1]]
lappend spanList [list Space {} {}] {*}[apply $expandSpan $sublist]
if $DEBUG {puts "single mandatory literal .lit: $spanList"}
}
{^\?§.+=\?$} {
# single optional literal = .optlit:
lappend sublist [list Span .optlit [string range $word 2 end-2]]
lappend spanList [list Space {} {}] {*}[apply $expandSpan $sublist]
if $DEBUG {puts "single optional literal .optlit: $spanList"}
}
{^\?§.+=$} {
# multiple optional arg group (first arg is mandatory literal):
lappend sublist [list Span .lit [string range $word 2 end-1]]
set grouptype .optarg
# also get all other members of this group and put them into the first span
while 1 {
incr i
set word [lindex $line $i]
# next word is typically optional
if {[string index $word 0] eq "+"} {
if {[string index $word end] eq "?"} {
# end of group
lappend sublist [list Space {} {}] [list Span .arg [string range $word 1 end-2]]
break
} else {
# middle of group
if {[lindex $word end] eq "="} {
lappend sublist [list Space {} {}] [list Span .arg [string range $word 1 end-1]]
} else {
lappend sublist [list Space {} {}] [list Span .arg [string range $word 1 end]]
}
}
} elseif {[string range $word 0 2] eq "..."} {
set grouptype .optdot
break
} else {
return -code error "parseCommand: detected an arg in an optional argument group that not yet a handled case."
}
if {$i > [llength $line]} {
puts "emergencyStop 3 in parseCommand"
puts "Line: $line"
exit
}
}
set sublist [apply $expandSpan $sublist]
lappend spanList [list Space {} {}] [list Span $grouptype $sublist]
if $DEBUG {puts "multiple optional arg group: $spanList"}
}
{^\?\+.+[^=][^\?]} {
# multiple optional arguments
set content [string range $word 2 end]
while 1 {
incr i
set word [lindex $line $i]
if {[string range $word end-1 end] eq "=?"} {
set word [string range $word 0 end-2]
if {$word eq "..."} {
set type .optdot
} else {
set type .optarg
lappend content [string range $word 0 end]
}
break
} else {
lappend content $word
}
if {$i > [llength $line]} {
puts "emergencyStop 4 in parseCommand"
puts "Line: $line"
exit
}
}
lappend spanList [list Space {} {}] {*}[apply $expandSpan [list [list Span $type [join $content " "]]]]
if $DEBUG {puts "multiple optional arguments: $spanList"}
}
default {
puts "parseCommand error: unknown syntax pattern"
puts "Line: $line"
exit
}
}
}
}
if $DEBUG {puts "RESULT = $spanList"}
return $spanList
}
proc ::ndoc::parseInline {keyword attributes content} {
#
# parses an inline element of the (raw) nroff document
#
# keyword - an AST block keyword in which the inline is located
# attributes - AST element options of the AST block element
# content - a string of raw nroff characters representing the inline content
#
# The inline content is processed and a replacement AST is returned for the content
#
# Returns a replacement AST where the content is replaced with a list of (possibly nested) Inline AST elements
#
variable verbose
set DEBUG 0
set inlineAST [list]
if {$verbose || $DEBUG} {puts CONTENT=$content}
if {$keyword eq "Code"} {
# special case for 'Code' where we do not want to have anything expanded
# apart from nroff backslash "formatting"
if $DEBUG {puts =Code}
set content [BIRPstrip $content]
set content [parseBackslash $content]
return [list $keyword $attributes $content]
}
set content [BIRPclean $content]
while {[string length $content]} {
set char [string index $content 0]
set lookahead [string range $content 1 2]
if {$verbose} {puts AST=$inlineAST}
if {$verbose} {puts CHAR=$char}
if {$char eq "\\" && $lookahead in {fB fI fR fP}} {
if {$verbose} {puts STRONG/EMPHASIS}
if {[string index $lookahead end] in {R P}} {
return -code error "found '\\f[string index $lookahead end]' ... this should never happen ..."
}
set Keyword [string map {B Strong I Emphasis} [string index $lookahead end]]
set found [regexp -indices -start 3 {(\\f)[BIRP]} $content endMark]
if {$found} {
set endMark [lindex $endMark 0]
if {$verbose} {puts endMark=$endMark}
} else {
return -code error "unbalanced \\f markup"
}
lappend inlineAST [parseInline $Keyword {} [string range $content 3 $endMark-1]]
# we here assume that \fP is used exactly like \fR as this seems the case in Tk man pages
# but strictly the two are not the same!!
if {[string index $content $endMark+2] in {R P}} {
# the current String/Emphasis just ended, so remove the end marker
set content [string range $content $endMark+3 end]
} else {
# we go directly from bold to italic or vice versa, so keep the start marker:
set content [string range $content $endMark end]
}
} elseif {$char eq "§" && [string index $content 1] eq "\""} {
# quoted text (starts with §" and ends with "§)
if {$verbose || $DEBUG} {puts QUOTED}
set endMark [string first \"§ $content 2]
# "
if {$endMark == -1} {return -code error "parseInline: unbalanced quote (no end marker found)"}
lappend inlineAST [parseInline Quoted {} [string range $content 2 $endMark-1]]
set content [string range $content $endMark+2 end]
} else {
# normal text, digest it until
# - a known backslash sequence comes (\fI, \fB, ...)
# - a quoted text comes
# - or until the end of the content if nothing of the above is found
if {$verbose || $DEBUG} {puts DEFAULT}
# put the first index where an '\f' or a quote was found into 'endMark'
# (note that 'endMark' is a list of two indices)
# \x22 is the quote character
set found [regexp -indices {(\\f)[BIRP]|(§\x22)} $content endMark]
#
if {$found} {
set endMark [lindex $endMark 0]
} else {
set endMark [string length $content]
}
set textContent [string range $content 0 $endMark-1]
# handle escaping of characters:
set textContent [parseBackslash $textContent]
lappend inlineAST [list Text {} $textContent]
set content [string range $content $endMark end]
}
}
return [list $keyword $attributes $inlineAST]
}
proc ::ndoc::AST2Markdown {} {
#
# converts an AST into markdown
#
variable manual
# start with YAML metadata block:
set output "---\n"
foreach {key value} [dict get $manual meta] {
switch $key {
Keywords - Links {
append output $key: \n
foreach el $value {append output { - } $el \n}
}
default {
append output $key : { } $value \n
}
}
}
append output Copyright: \n
foreach el [dict get $manual copyright] {
append output { - } $el \n
}
append output "---\n"
# then continue with the actual content:
set content [dict get $manual content]
lassign $content documentType documentAttributes documentContent
if {$documentType ne "Document"} {
return -code error "AST2Markdown: 'Document' element missing"
}
foreach item $documentContent {
append output [AST2Markdown_Element $documentType 0 $item]
}
return $output
}
proc ::ndoc::AST2Markdown_Element {parentType indent ASTelement} {
#
# convert a (possibly nested) single AST element into Markdown
# and return the conversion result
#
# parentType - the AST type of the parent element (needed in some context to modify the formatting of the child element)
# indent - nmber of spaces the content must be indented
# ASTelement - the AST element (3 element list) to be converted to markdown
#
variable listCounter
variable listType
# type - the AST type of the element to convert
# attributes - the list with option-value-pairs of AST attributes
# content - the actual content of the AST element, may be another nested AST element
lassign $ASTelement type attributes content
set output {}
### prefix: ###
switch $type {
Paragraph {
switch $parentType {
List - Dlist {
append output [string repeat { } $indent]
}
ListItem - DlistItem {
append output [string repeat { } $indent]
}
default {
append output \n
if {[dict size $attributes]} {
# put attributes into fenced div:
append output ::: { } \{ .info
# \x22 is the quote character
dict for {k v} $attributes {append output { } $k=\x22$v\x22}
append output \} \n
}
}
}
}
Code {append output \n [string repeat { } $indent] ``` \n}
Header {append output \n [string repeat # [dict get $attributes -level]] { }}
List {
set listCounter 0
set listType [dict get $attributes -type]
append output \n
}
ListItem {
switch $listType {
bullet {
append output {- }
}
numbered {
incr listCounter
append output $listCounter {. }
}
default {
return -code error "no such List type '$listType'"
}
}
}
Dlist {
if {$parentType eq "Dlist"} {incr indent 4}
append output \n
}
DlistItem {
append output [string repeat { } $indent]
foreach item [dict get $attributes -definition] {
append output [AST2Markdown_Element DlistItem $indent $item]
}
append output \n [string repeat { } $indent] {: }
}
Span {}
Div {
append output \n ::: " {$attributes} " ::: \n
}
Syntax {}
Space {}
Text {}
Emphasis {append output *}
Strong {append output **}
Quoted {append output \x22}
Link {}
Inline {}
default {return -code error "no such AST element type '$type'"}
}
### content: ###
switch $type {
Text {
# just output the text, but escape some characters with special meaning in markdown:
# \u005c = backslash
append output [string map {* \u005c* \u005c \u005c\u005c _ \u005c_} $content]
}
Code {
foreach codeLine [split $content \n] {append output [string repeat { } $indent] $codeLine \n}
}
Space {
append output { }
}
DlistItem {
append output [AST2Markdown_Element $type 0 [lindex $content 0]]
foreach item [lrange $content 1 end] {
lassign $item subtype
if {$subtype eq "Paragraph"} {append output \n}
append output [AST2Markdown_Element $type 4 $item]
}
}
Span {
append output \[
foreach item $content {append output [AST2Markdown_Element $type 0 $item]}
append output \]
append output \{ $attributes \}
}
Div {
foreach item $content {append output [AST2Markdown_Element $type $indent $item]\n}
}
Syntax {
foreach item $content {append output [AST2Markdown_Element $type $indent $item]}
}
default {
foreach item $content {append output [AST2Markdown_Element $type $indent $item]}
}
}
### suffix: ###
switch $type {
Paragraph {
append output \n
if {[dict size $attributes]} {
append output ::: \n
}
}
Header {append output \n}
Code {append output [string repeat { } $indent] ``` \n}
List {}
Dlist {}
ListItem {append output \n}
DlistItem {append output \n}
Span {}
Div {append output ::: \n}
Syntax {}
Space {}
Text {}
Emphasis {append output *}
Strong {append output **}
Quoted {append output \x22}
Link {}
default {}
}
return $output
}
proc ::ndoc::man2markdown {manContent} {
#
# convert the nroff from a Tcl/Tk manual page into markdown
#
# manContent - the content of the nroff file to be converted
#
# Returns the markdown
#
man2AST $manContent
set md [AST2Markdown]
set md [mdLinks $md]
set md [mdExceptions $md]
return $md
}
proc ::ndoc::mdExceptions {md} {
#
# deal with stuff we cannot easily do automatically,
# i.e. all sorts of things that fall through the normal handling
# or are being done over-agressively
#
variable manual
set myFile [dict get $manual meta CommandName]
switch $myFile {
append {
set md [string map {
{"**append a $b**"} {`append a $b`}
{"**set a $a$b**" if **$a** is long} {`set a $a$b` if **$a** is long}
{[set]: set.md} {}
} $md]
}
binary {
# add two cross references:
set md [string map {{subcommand **binary format**} {subcommand [binary format](Binary format)}} $md]
set md [string map {{subcommand **binary scan**} {subcommand [binary scan](Binary scan)}} $md]
}
clock {
set md [string map [list \
{.sp **clock format now -f %a; # current day of the week** .sp **clock add now 1 month; # next month**} \
"\n\n ```\n clock format now -f %a; # current day of the week\n clock add now 1 month; # next month\n ```" \
\
"1. the environment variable **TCL\\_TZ**.\n" \
{ 1. the environment variable **TCL\_TZ**.} \
\
"2. the environment variable **TZ**.\n" \
{ 2. the environment variable **TZ**.} \
\
"3. on Windows systems, the time zone settings from the Control Panel.\n" \
{ 3. on Windows systems, the time zone settings from the Control Panel.} \
\
{*https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd\_chap08.html*} \
{<https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html>} \
\
{*https://tip.tcl-lang.org/173*} \
{<https://tip.tcl-lang.org/173>} \
] $md]
}
configurable {
set md [string map {
{uses **info object properties** with} {uses [info object properties][info] with}
} $md]
append md \n {[info]: info.md}
}
dde {
set md [string map {{Dde and tcl} {DDE and Tcl} Dde DDE} $md]
}
fcopy {
set md [string map {{two [open "|hal 9000" r+]} {two `open "|hal 9000" r+`}} $md]
}
file {
set md [string map {
{the form [**ugo**]?[[**+-=**][**rwxst**]**,**[...]]} {the form `[**ugo**]?[[**+-=**][**rwxst**]**,**[...]]`}
{Other attributes may be present in the returned list. These should be ignored.} { Other attributes may be present in the returned list. These should be ignored.}
} $md]
}
filename {
set md [string map {
{file called [file]} {file called **file**}
} $md]
}
format {
set md [string map {{Differences from ansi sprintf} {Differences from ANSI sprintf}} $md]
}
glob {
set md [string map {
{"**glob -tails -directory $dir \***" is equivalent to "**set pwd [pwd]; cd $dir; glob \*; cd $pwd**"} {`glob -tails -directory $dir *` is equivalent to `set pwd [pwd]; cd $dir; glob *; cd $pwd`}
{"**glob -tails -path [file rootname /home/fred/foo.tex] .\***"} {`glob -tails -path [file rootname /home/fred/foo.tex] .*`}
{"glob -join \* \* \* \*"} {`glob -join * * * *`}
{[] construct} {\[\] construct}
{[set]: set.md} {}
} $md]
}
http {
set md [string map {
{GET / HTTP/1.1 GET} { GET / HTTP/1.1 GET}
{https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml} {<https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml>}
} $md]
}
info {
set md [string map {
{by **coroutine**} {by [coroutine]}
{by **proc**} {by [proc]}
{ [interp]} { **interp**}
{like "foo [bar [x]]"} {like `foo [bar [x]]`}
} $md]
}
lappend {
set md [string map {
{"**lappend a $b**" is} {`lappend a $b` is}
{"**set a [concat $a [list $b]]**"} {`set a [concat $a [list $b]]`}
} $md]
}
library {
set md [string map {
{[text=|§binary]} {[text|binary]}
} $md]
}
lrepeat {
set md [string map {
{Note that **lrepeat 1 element ...** is identical to **list element ...**} {Note that `lrepeat 1 element ...` is identical to `list element ...`}
} $md]
}
mathfunc {
set md [string map {
{form **[tcl::mathfunc::sin [expr {$x}]]**} {form `[tcl::mathfunc::sin [expr {$x}]]`}
{or **[tcl::mathfunc::atan2 [expr {$y}] [expr {$x}]]**.} {or `[tcl::mathfunc::atan2 [expr {$y}] [expr {$x}]]`.}
{"**atan** [[expr] {*y***/***x*}]"} {`atan [expr {y/x}]`}
{"**sqrt** [[expr] {*x***\****x***+***y***\****y*}]"} {`sqrt [expr {x*x+y*y}]`}
{to **string is boolean**} {to [string is boolean][string]}
{with **string is true** and **string is false**} {with [string is true][string] and [string is false][string]}
} $md]
append md \m {[string]: string.md}
regsub -all {range \[([^\]]*)\]} $md {range \\[\1\\]} md
}
mathop {
set md [string map {
{as "**\*\* 2 [\*\* 3 4]**"} {as "**\*\* 2 \[\*\* 3 4\]**"}
} $md]
}
msgcat {
set md [string map {
{by **::msgcat::mcpreferences** {\*}[**::msgcat::mcutil getpreferences** *newLocale*].} {by `::msgcat::mcpreferences** {*}[::msgcat::mcutil getpreferences newLocale]`.}
{**1) In class definition script**} { 1. In class definition script}
{**2) method defined in a class**} { 2. method definedin a class}
{**3) method defined in a classless object**} { 3. method defined in a classless object}
{: **msgcat** command is called } { **msgcat** command is called }
} $md]
}
namespace {
set md [string map {
{the command **set script [namespace code {foo bar}]** is invoked} {the command `set script [namespace code {foo bar}]` is invoked}
{Then **eval $script [list x y]** can be} {Then `eval $script [list x y]` can be}
{as the command **::namespace eval ::a::b {foo bar x y}**} {as the command `::namespace eval ::a::b {foo bar x y}`}
{The command **namespace upvar $ns a b** has the same behaviour as **upvar 0 ${ns}::a b**} {The command `namespace upvar $ns a b` has the same behaviour as `upvar 0 ${ns}::a b`}
{same behaviour as **upvar 0 ${ns}::a b**} {same behaviour as `upvar 0 ${ns}::a b`}
} $md]
}
open {
set md [string map {
{[baud=§,=+parity=§,=+data=§,=+stop]{.arg}} {[baud,parity,data,stop]{.arg}}
{Error codes (windows only)} {Error codes (Windows only)}
{[reset]{.cmd}} {**reset**}
} $md]
}
package {
set md [string map {
{equivalent to **package require** *package version*-*version*.} {equivalent to `package require package version-version`.}
{is **foo bar** and later the command **foo bar test 2.4**} {is `foo bar` and later the command `foo bar test 2.4`}
{command **package require test 2.4**} {command `package require test 2.4`}
{[latest=|§stable]} {[latest|stable]}
} $md]
}
refchan {
set md [string map {
{the strings [read] or} {the strings **read** or}
{any of [read] and} {any of **read** and}
{.,\\ } {e.g., }
} $md]
}
regexp - regsub {
set md [string map {
{"[^" bracket expressions} {"\[^" bracket expressions}
} $md]
}
registry {set md [string map {{[binary]} {**binary**}} $md]}
re_syntax {
set md [string map {{Different flavors of res} {Different flavours of REs}} $md]
}
return {
set md [string map {
{[error] (or **1**)} {**error** (or **1**)}
{[break] (or **3**)} {**break** (or **3**)}
{[continue] (or **4**)} {**continue** (or **4**)}
} $md]
}
scan {
set md [string map {
{**[***chars***]**} {**\[***chars***\]**}
{**]**} {**\]**}
{*[^***chars***]**} {*\[^***chars***\]**}
{ansi} {ANSI}
} $md]
}
self {
set md [string map {
{**<constructor>**} {**\<constructor\>**}
{**<destructor>**} {**\<destructor\>**}
} $md]
}
set {
set md [string map {
{**NAME RESOLUTION**} {[Name resolution](namespace.html#name-resolution)}
} $md]
}
singleton {
set md {string map {
{**<cloned>**} {**\<cloned\>**}
} $md}
}
string {
set md [string map {
{resorting to [return] **-level 0*} {resorting to `return -level 0`}
{character ([0-9A-Fa-f]).} {character (\[0-9A-Fa-f\]).}
{**[***chars***]**} {**\[***chars***\]**}
{[A-z]} {\[A-z\]}
{[A-Za-z]} {\[A-Za-z\]}
{characters **\*?[]\\** i} {characters **\*?\[\]\\** i}
} $md]
}
subst {
set md [string map {
{returns "**[b] c**", not "**[b] tricky**".} {returns "**\[b\] c**", not "**\[b\] tricky**".}
} $md]
}
tcltest {
set md [string map {
{are **exact**, [glob], and [regexp].} {are **exact**, **glob**, and **regexp**.}
{for *mode* are [regexp], [glob]} {for *mode* are **regexp**, **glob**}
} $md]
}
tclvars {
set md [string map {
{running [interp debug][interp] **{} -frame 1**} {running `interp debug {} -frame 1`}
} $md]
}
tm {
set md [string map {
{"**tcl***X***/site-tcl**", and "**tcl***X***/***X***.***y*"} {"**tcl**_X_**/site-tcl**", and "**tcl**_X_**/**_X_**.**_y_"}
{MF = /module_path/PNAME\(fm-PVERSION.tm} {MF = /module_path/PNAME'-PVERSION.tm}
{https://core.tcl-lang.org/tips/doc/trunk/tip/189.md} {<https://core.tcl-lang.org/tips/doc/trunk/tip/189.md>}
{https://core.tcl-lang.org/tips/doc/trunk/tip/190.md} {<https://core.tcl-lang.org/tips/doc/trunk/tip/190.md>}
} $md]
}
unicode {
set md [string map {
{see https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/).} {see <https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/>).}
} $md]
}
unload {
set md [string map {
{command **unload libxyz4.2.so**} {command `unload libxyz4.2.so`}
{the command **unload bin/last.so {}**} {the command `unload bin/last.so {}`}
} $md]
}
vwait {
set md [string map {
{e.g.,\\ **http**} {e.g., [http]}
} $md]
append md \n {[http]: http.md}
}
zipfs {
set md [string map {
{1. the name of the ZIP archive file that contains the file,} { 1. the name of the ZIP archive file that contains the file,}
{2. the size of the file after decompressions,} { 2. the size of the file after decompressions,}
{3. the compressed size of the file, and} { 3. the compressed size of the file, and}
{4. the offset of the compressed data in the ZIP archive file.} { 4. the offset of the compressed data in the ZIP archive file.}
} $md]
}
}
regsub {\s+$} $md \n md
return $md
}
proc ::ndoc::mdLinks {md} {
#
# find words in the final md output that qualify as links to other manual pages
# and insert markdown links there in the form of implicit reference links
# (using Pandoc's shortcut_reference_links extension)
#
# md - string containing manual page in markdown format
#
variable tclCmdList
variable tclCmdListRemap
variable manual
variable tclCmdListExclude
variable tclCApiFileMap
variable tkCApiFileMap
variable sectionTitles
# list to build the markdown references for external links (these are put at the end of the document):
set refList [list]
set cmdName [dict get $manual meta CommandName]
set fileName [dict get $manual fileName]
# rename links as done in ::ndoc::main to avoid clashing with a same-named section "n" page:
set fileRoot $fileName
if {$fileRoot in {Class Concat Encoding Eval Exit Load Namespace Object RegExp UpVar zipfs}} {
append fileRoot 3
}
# detect all strings with ** around, using a non-greedy regexp.
# we go through the file one by one as ce can't use '-all' here
# (it would shift indices into the md after each match is replaced)
set matchIndices [regexp -inline -expanded -indices -line {\*\*(.+?)\*\*} $md]
while {[llength $matchIndices]} {
lassign $matchIndices fullRange coreRange
set linkText [string range $md {*}$coreRange]
# check whether the string qualifies as a link to another Tcl command
## extract the command name:
set linkList [split $linkText { }]
set linkCmd [lindex $linkList 0]
# isValidLink: 0 = no link, 1 = external link, 2 = internal link, 9 = looks like a link but is none:
set isValidLink 0
# if the text has more than two words and the first word is not starting with an uppercase char (indicating an internal link),
# it is typically nothing to link to but just example code in the text,
# so exclude this (exceptions are handled in ndoc::mdExceptions):
if {[llength $linkList] > 2 && ! [string is upper [string index $linkCmd 0]]} {set isValidLink 9}
if {! $isValidLink && [lindex $linkList 0] eq "const" && [llength $linkList] >= 1} {
## exclude some corner cases
set isValidLink 0
}
if {$linkCmd in [dict getwithdefault $tclCmdListExclude $fileName {}]} {
## link is to be excluded explicitly as it is on the negative list:
set isValidLink 9
}
if {! $isValidLink && $linkCmd ne $cmdName && $linkCmd in $tclCmdList} {
## link to a known Tcl command (the file to link to is the same as the command name)
set linkTarget $linkCmd
set isValidLink 1
}
if {! $isValidLink && [string match {Tcl\\_*} $linkCmd]} {
## a Tcl C API function (Tcl_...)
# (note that we can't handle this in tclCmdList as the md conversion has added a backslash (Tcl\_...):
set linkCmdSubst [subst -novariables -nocommands $linkCmd]
if {[dict exists $tclCApiFileMap $linkCmdSubst]} {
set apiTarget [dict get $tclCApiFileMap $linkCmdSubst]
if {$apiTarget ne $fileRoot} {
## don't link to another Tcl_ function documented on this very page:
set linkTarget $apiTarget
set isValidLink 1
}
}
}
if {! $isValidLink && [string match {Tk\\_*} $linkCmd]} {
## a Tk C API function (Tk_...)
# (note that we can't handle this in tclCmdList as the md conversion has added a backslash (Tk\_...):
set linkCmdSubst [subst -novariables -nocommands $linkCmd]
if {[dict exists $tkCApiFileMap $linkCmdSubst]} {
set apiTarget [dict get $tkCApiFileMap $linkCmdSubst]
if {$apiTarget ne $fileRoot} {
## don't link to another Tk_ function documented on this very page:
set linkTarget $apiTarget
set isValidLink 1
}
}
}
if {! $isValidLink && $linkCmd ne $cmdName && [dict exists $tclCmdListRemap $fileName]} {
## it's a valid link if there is a remapping entry here
## (note that we need to 'subst' the linkCmd word here as it may contain a literal backslash
## used to escape an underscore in a command name in markdown such as in 'tcl\_platform'):
set linkTarget [dict getwithdefault $tclCmdListRemap $fileName [subst -novariables -nocommands $linkCmd] {}]
if {$linkTarget ne ""} {set isValidLink 1}
}
if {! $isValidLink && ! [string is lower [string index $linkText 0]] && [string totitle $linkText] in $sectionTitles} {
# it's a valid cross reference to another section/subsection in this text:
set linkText [string totitle $linkText]
set isValidLink 2
set linkTarget $linkText
}
if {$isValidLink > 0 && $isValidLink != 9} {
set replaceString \[$linkText\]
if {$linkTarget ne $linkText} {append replaceString \[$linkTarget\]}
set md [string replace $md {*}$fullRange $replaceString]
# only add external links, not internal ones:
if {$isValidLink == 1} {lappend refList $linkTarget}
# the next search should start at the character after $fullMatch,
# but since we have changed the content with a string that is
# different in length, the new index will be offset by the length
# of the replacement string, starting from the beginning of the match:
set nextIndex [expr {[lindex $fullRange 0] + [string length $replaceString]}]
} else {
# no link, we did not change anything, so the next index is +1 here:
set nextIndex [expr {[lindex $fullRange end] + 1}]
}
set matchIndices [regexp -inline -expanded -indices -line -start $nextIndex {\*\*(.+?)\*\*} $md]
}
# add link references at the bottom of the page:
if {[llength $refList]} {
append md \n\n
foreach linkCmd [lsort -dictionary -unique $refList] {
append md \[ $linkCmd \] : { } $linkCmd .md \n
}
}
return $md
}
proc ::ndoc::readFile {filename} {
#
# read a text file and returns its content as a list split at \n
#
# filename - name (including path) of the file to be read
#
# Side effect: sets the 'name' property in the variable 'manual'
#
variable manual
dict set manual fileName [file root [file tail $filename]]
if {![file exists $filename]} {
return -code error "readFile: File '$filename' does not exist."
}
set fh [open $filename r]
set manContent [read $fh]
close $fh
return $manContent
}
proc ::ndoc::main {} {
#
# main entry point to the script
# when called directly from the command line
# (i.e. not [source]d)
#
global argv
variable manual
variable verbose
variable sectionTitles
if {[lindex $argv 0] eq ""} {
#### main testing code follows (prints to stdout) ####
set myDir [file dirname [info script]]
set tclManDir [file join $myDir .. doc]
set tkManDir [file join $myDir .. doc]
set myFile [file join $tclManDir string.n]
#set myFile [file join $tclManDir clock.n]
#set myFile [file join $tclManDir Dstring.3]
#set myFile [file join $tclManDir exec.n]
#set myFile [file join $tclManDir filename.n]
#set myFile [file join $tclManDir SetResult.3]
#set myFile [file join $tclManDir SetVar.3]
#set myFile [file join $tclManDir subst.n]
#set myFile [file join $tkManDir bind.n]
#set myFile [file join $tclManDir filename.n]
#set myFile [file join $tkManDir scrollbar.n]
puts [man2markdown [readFile $myFile]]
} elseif {[llength $argv] == 2} {
# convert whole directory:
lassign $argv inDir outDir
if {! [file isdirectory $inDir]} {
return -code error "Error: first argument is not a directory"
}
if {[file exists $outDir] && ! [file isdirectory $outDir]} {
return -code error "Error: second argument is not a directory"
} elseif {! [file exists $outDir]} {
file mkdir $outDir
}
# first the files in section "n", then in section "1", finally in section "3":
foreach section {n 1 3} {
foreach file [lsort -dictionary [glob [file join $inDir *.$section]]] {
puts "converting $file ..."
set sectionTitles [list]
set md [man2markdown [readFile $file]]
set stem [file rootname [file tail $file]]
# make sure not to overwrite files in the n section with
# files from the 3 section having the same name
# (was no problem previously as they had different
# file extensions):
if {$section ne "n" && $stem in {Class Concat Encoding Eval Exit Load Namespace Object RegExp UpVar zipfs}} {append stem $section}
set fh [open [file join $outDir ${stem}.md] w]
puts $fh $md
close $fh
}
}
} else {
# convert single file (to stdout):
puts [man2markdown [readFile [lindex $argv 0]]]
}
}
if {[info exists argv0] && [file tail [info script]] eq [file tail $argv0]} {
# call [main] when the script is *not* sourced by another script
# but called from the command line
::ndoc::main
}