Skip to content
Tcl Source Code Artifact [cbfc9ddcaa]
Login

Artifact [cbfc9ddcaa]

Artifact cbfc9ddcaaec97057ec980456b04c42e56afe593df5f79e073b2f71651cdd31c:


# man2markdown.tcl --
#
# 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/nroff-original ../doc/markdown
# ```
#
# Note that the second directory is a base directory. The actual files will be placed
# into subdirectories under the base directory (called Tcl, TclCAPI, Tk TkCAPI)
#
# 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>
#

package require Tcl 9

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!)
		| 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

	# 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_DString DString
		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 Namespace 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 Object 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 Class Tcl_ClassSetConstructor Method Tcl_ClassSetDestructor Method
		Tcl_ClassSetMetadata Class Tcl_ClearChannelHandlers CrtChannel Tcl_Close OpenFileChnl Tcl_CloseEx OpenFileChnl
		Tcl_CommandComplete CmdCmplt Tcl_CommandTraceInfo TraceCmd Tcl_Concat Concat 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 Class
		Tcl_CreateAlias CrtAlias Tcl_CreateAliasObj CrtAlias Tcl_CreateChannel CrtChannel Tcl_CreateChannelHandler CrtChnlHdlr
		Tcl_CreateChild CrtAlias Tcl_CreateCloseHandler CrtCloseHdlr Tcl_CreateCommand CrtCommand Tcl_CreateEncoding Encoding
		Tcl_CreateEnsemble Ensemble Tcl_CreateEventSource Notifier Tcl_CreateExitHandler Exit Tcl_CreateFileHandler CrtFileHdlr
		Tcl_CreateHashEntry Hash Tcl_CreateInterp CrtInterp Tcl_CreateNamespace Namespace Tcl_CreateObjCommand CrtObjCmd
		Tcl_CreateObjCommand2 CrtObjCmd Tcl_CreateObjTrace CrtTrace Tcl_CreateObjTrace2 CrtTrace Tcl_CreateThread Thread
		Tcl_CreateThreadExitHandler Exit 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 Object Tcl_DeleteAssocData AssocData Tcl_DeleteChannelHandler CrtChnlHdlr Tcl_DeleteCloseHandler CrtCloseHdlr
		Tcl_DeleteCommand CrtObjCmd Tcl_DeleteCommandFromToken CrtObjCmd Tcl_DeleteEventSource Notifier Tcl_DeleteEvents Notifier
		Tcl_DeleteExitHandler Exit Tcl_DeleteFileHandler CrtFileHdlr Tcl_DeleteHashEntry Hash Tcl_DeleteHashTable Hash
		Tcl_DeleteInterp CrtInterp Tcl_DeleteNamespace Namespace Tcl_DeleteThreadExitHandler Exit 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 Object Tcl_Eof OpenFileChnl Tcl_ErrnoId SetErrno
		Tcl_ErrnoMsg SetErrno Tcl_Eval Eval Tcl_EvalEx Eval Tcl_EvalFile Eval
		Tcl_EvalObjEx Eval Tcl_EvalObjv Eval Tcl_EvalTokensStandard ParseCmd Tcl_EventuallyFree Preserve
		Tcl_Exit Exit Tcl_ExitThread Exit Tcl_Export Namespace 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 Encoding Tcl_ExternalToUtfDString Encoding Tcl_ExternalToUtfDStringEx Encoding 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 Exit
		Tcl_FinalizeNotifier Notifier Tcl_FinalizeThread Exit Tcl_FindCommand Namespace Tcl_FindEnsemble Ensemble
		Tcl_FindExecutable FindExec Tcl_FindHashEntry Hash Tcl_FindNamespace Namespace Tcl_FindSymbol Load
		Tcl_FirstHashEntry Hash Tcl_Flush OpenFileChnl Tcl_ForgetImport Namespace Tcl_Format StringObj
		Tcl_Free Alloc Tcl_FreeEncoding Encoding 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 Class
		Tcl_GetCommandFromObj CrtObjCmd Tcl_GetCommandFullName CrtObjCmd Tcl_GetCommandInfo CrtObjCmd Tcl_GetCommandInfoFromToken CrtObjCmd
		Tcl_GetCommandName CrtObjCmd Tcl_GetCurrentNamespace Namespace Tcl_GetCurrentThread Notifier Tcl_GetCwd GetCwd
		Tcl_GetDeviceTypeFromStat FileSystem Tcl_GetDouble GetInt Tcl_GetDoubleFromObj DoubleObj Tcl_GetEncoding Encoding
		Tcl_GetEncodingFromObj Encoding Tcl_GetEncodingName Encoding Tcl_GetEncodingNameForUser Encoding Tcl_GetEncodingNameFromEnvironment Encoding
		Tcl_GetEncodingNames Encoding Tcl_GetEncodingSearchPath Encoding 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 Namespace 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 Namespace Tcl_GetNumber Number Tcl_GetNumberFromObj Number
		Tcl_GetObjResult SetResult Tcl_GetObjType ObjectType Tcl_GetObjectAsClass Class Tcl_GetObjectCommand Class
		Tcl_GetObjectFromObj Class Tcl_GetObjectName Class Tcl_GetObjectNamespace Class Tcl_GetOpenFile GetOpnFl
		Tcl_GetParent CrtAlias Tcl_GetPathType SplitPath Tcl_GetRange StringObj Tcl_GetRegExpFromObj RegExp
		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 Eval Tcl_GlobalEvalObj Eval Tcl_HasStringRep ObjectType
		Tcl_HashStats Hash Tcl_HideCommand CrtAlias Tcl_Import Namespace Tcl_IncrRefCount Object
		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 Object Tcl_IsChannelExisting CrtChannel Tcl_IsChannelRegistered CrtChannel
		Tcl_IsChannelShared CrtChannel Tcl_IsEmpty StringObj Tcl_IsEnsemble Ensemble Tcl_IsSafe CrtAlias
		Tcl_IsShared Object 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 Load 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 Object Tcl_NewObjectInstance Class 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 Class
		Tcl_ObjectGetMetadata Class Tcl_ObjectGetMethodNameMapper Class Tcl_ObjectSetMetadata Class Tcl_ObjectSetMethodNameMapper Class
		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 RegExp Tcl_RegExpExec RegExp
		Tcl_RegExpExecObj RegExp Tcl_RegExpGetInfo RegExp Tcl_RegExpMatch RegExp Tcl_RegExpMatchObj RegExp
		Tcl_RegExpRange RegExp 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 Encoding 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 Exit
		Tcl_SetHashValue Hash Tcl_SetIntObj IntObj Tcl_SetListObj ListObj Tcl_SetLongObj IntObj
		Tcl_SetMainLoop Tcl_Main Tcl_SetMaxBlockTime Notifier Tcl_SetNamespaceUnknownHandler Namespace 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 Encoding
		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 UpVar Tcl_UpVar2 UpVar 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 Encoding
		Tcl_UtfToExternalDString Encoding Tcl_UtfToExternalDStringEx Encoding 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 Eval 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_ZlibAdler2 TclZlib Tcl_ZlibCRC2 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
		TclZipfs_AppHook zipfs TclZipfs_Mount zipfs TclZipfs_MountBuffer zipfs Tcl_zipfsUnmount zipfs
	}]

	# 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 Clipboard Tk_ClipboardClear Clipboard
		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 Grab 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 Grab
		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 mapping every documented Tk command (and Tk variable/option page name) to the
	# manual page (file root) that documents it (generated from the NAME sections of the Tk man pages):
	set tkCmdFileMap [dict create {*}{
		accessible accessible attribtable attribtable bell bell bind bind
		bindtags bindtags bitmap bitmap busy busy button button
		canvas canvas checkbutton checkbutton clipboard clipboard colors colors
		console console cursors cursors destroy destroy entry entry
		event event fileicon fileicon focus focus font font
		fontchooser fontchooser frame frame geometry tkvars grab grab
		grid grid image image keysyms keysyms label label
		labelframe labelframe listbox listbox lower lower menu menu
		menubutton menubutton message message nsimage nsimage option option
		options options pack pack panedwindow panedwindow photo photo
		place place print print radiobutton radiobutton raise raise
		safe::loadTk loadTk scale scale scrollbar scrollbar selection selection
		send send spinbox spinbox sysnotify sysnotify systray systray
		text text tk tk tk::mac tk_mac tk::scalingPct tkvars
		tk::svgFmt tkvars tk_bisque palette tk_chooseColor chooseColor tk_chooseDirectory chooseDirectory
		tk_dialog dialog tk_focusFollowsMouse focusNext tk_focusNext focusNext tk_focusPrev focusNext
		tk_getOpenFile getOpenFile tk_getSaveFile getOpenFile tk_library tkvars tk_menuSetFocus menu
		tk_messageBox messageBox tk_optionMenu optionMenu tk_patchLevel tkvars tk_popup popup
		tk_setPalette palette tk_strictMotif tkvars tk_textCopy text tk_textCut text
		tk_textPaste text tk_version tkvars tkerror tkerror tkwait tkwait
		toplevel toplevel ttk::button ttk_button ttk::checkbutton ttk_checkbutton ttk::combobox ttk_combobox
		ttk::entry ttk_entry ttk::frame ttk_frame ttk::intro ttk_intro ttk::label ttk_label
		ttk::labelframe ttk_labelframe ttk::menubutton ttk_menubutton ttk::notebook ttk_notebook ttk::panedwindow ttk_panedwindow
		ttk::progressbar ttk_progressbar ttk::radiobutton ttk_radiobutton ttk::scale ttk_scale ttk::scrollbar ttk_scrollbar
		ttk::separator ttk_separator ttk::sizegrip ttk_sizegrip ttk::spinbox ttk_spinbox ttk::style ttk_style
		ttk::toggleswitch ttk_toggleswitch ttk::treeview ttk_treeview ttk::widget ttk_widget ttk_image ttk_image
		ttk_vsapi ttk_vsapi winfo winfo wish wish wm wm
	}]

	# dictionary mapping Tcl's return code constants to the manual page (file root) that documents them:
	set tclReturnCodeFileMap [dict create {*}{
		TCL_OK catch TCL_ERROR catch TCL_RETURN catch TCL_BREAK catch TCL_CONTINUE catch
	}]

	# 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}
		Class         {oo::class class}
		
	}]
	
	# 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 destroy}
		entry		{string}
		event		{return}
		expr            {variable}
		file            {socket}
		font		{menu}
		GetIndex        {option}
		getOpenFile	{file open text}
		grab		{global}
		history		{exec event}
		http 		{error Tcl binary text}
		info            {coroutine proc}
		interp		{time}
		library         {text}
		menu		{checkbutton radiobutton}
		messageBox	{error info}
		namespace       {text}
		next		{unknown destroy}
		options		{bitmap image set}
		radiobutton	{image}
		regexp          {binary}
		re_syntax       {lower print}
		safe		{join split}
		scale		{label variable}
		scrollbar	{set}
		selection	{string}
		string          {lower print}
		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 time}
	}]
}


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)
	# \\(+-          = \(+-    ->   ± (plus-or-minus, used e.g. in format(n)/scan(n))
	# \\(^o          = \(^o    ->   ô (o with circumflex, used e.g. in re_syntax(n))
	# \\(mc          = \(mc    ->   µ (micro sign, used e.g. in timerate(n))
	#
	# 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 '
		\\(+- \u00b1
		\\(^o \u00f4
		\\(mc \u00b5
	} $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]
					# a .VS region that tightly wraps just this item's title (nothing of
					# its own body in between, e.g. unicode.n's TIP726) has no text left
					# to tag once its body closes (see parseBlock), so it is tagged here
					# on the title/term itself instead - see the -vs itemAttr set in
					# parseBlock's .TP/.IP handling:
					set titleVs {}
					if {[dict exists $blockAttributes -vs]} {
						set titleVs [dict get $blockAttributes -vs]
						dict unset blockAttributes -vs
					}
					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 $titleVs]
					} elseif {$titleVs ne ""} {
						dict set blockAttributes -definition \
							[list [list Span "-vs {$titleVs}" [lindex [parseInline Inline {} $content] 2]]]
					} 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
	# whether a ‡-marked (.VS) region is still open within the CURRENT block's content
	# (see the .VS/.VE case below); tracked explicitly since a block can carry over an unrelated, already-closed ¤ from
	# an earlier .VS/.VE pair that ran past its own block boundary (see below):
	set vsOpen 0
	# the TIP/version info of the currently open .VS region, kept alongside vsOpen so
	# it can be handed off (see pendingVsInfo below) if the region turns out to have
	# no real text in it once its block closes:
	set vsInfo {}
	# when a .VS region closes (auto- or otherwise) with no real text of its own -
	# either because it is literally all the block had (e.g. CrtChannel.3's
	# '.PP'/'.VS TIPxxx'/'.PP') or because it trails at the very end of an otherwise
	# non-empty block (e.g. unicode.n's TIP726, which opens after real prose but right
	# before a .TP with nothing of its own in between) - AND that close was triggered
	# by an upcoming .TP/.IP, the info is stashed here so the new .TP/.IP list can pick
	# it up and mark its first item instead of losing it entirely; consumed (and
	# cleared) by the .TP/.IP case below, and cleared here too on any close that is NOT
	# such a hand-off, so it never leaks forward into some unrelated, later .TP/.IP:
	set pendingVsInfo {}
	while {[llength $manContent] > 0} {
		if {$doCloseBlock} {
			if {$blockContent ne ""} {
				# sometimes .PP is directly followed by .CS, producing empty paragraphs
				# which we want to ignore
				if {$vsOpen} {
					# a .VS region was still open when this block ended without a matching
					# .VE (it runs on into a later block, e.g. across an intervening .PP or
					# a .CS/.CE code block) - close it off here so this block's content stays
					# well-formed. We do NOT carry it over into whatever
					# block comes next (that would also wrongly re-open it inside a Code block).
					append blockContent ¤
					set vsOpen 0
				}
				set pendingVsInfo {}
				if {[regexp {‡([^:]*):¤$} $blockContent -> trailingInfo]} {
					# the region that just closed (auto- or for real) has nothing in it
					# and sits right at the end of the block - strip it out (it would
					# otherwise render as a stray empty '[]{version="..."}') and, if an
					# upcoming .TP/.IP is what closed this block, hand its info off to
					# that new list instead of just losing it (see pendingVsInfo above):
					set blockContent [string trimright [regsub {‡[^:]*:¤$} $blockContent {}]]
					if {$markup in {.TP .IP}} {set pendingVsInfo $trailingInfo}
				}
				if {[string trim [regsub -all {‡[^:]*:|¤} $blockContent {}]] eq ""} {
					# nothing real left at all - drop the block entirely rather than
					# emitting an empty one:
				} else {
					lappend blockList [list $blockType $blockAttributes $blockContent]
					if {$verbose} {puts "... closed block: [lindex $blockList end]"}
				}
			} else {
				set pendingVsInfo {}
			}
			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 - .sp {
				# 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
				# .sp = vertical space: markdown prose has no equivalent mid-paragraph
				#       gap, so it is just dropped and the surrounding lines flow
				#       together with the usual single-space line join (matching how
				#       .sp is already treated inside the ARGUMENTS .AP loop)
				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 {}
				# the .VS info (if any) that was open when itemTitle was set - see the
				# .TP/.IP case below:
				set itemTitleVs {}
				set itemContent {}
				# the TIP/version marker of a .VS region that is still open when the
				# CURRENT item finishes (no matching .VE seen yet within it) - carried
				# forward so it gets re-opened at the start of the NEXT item's content
				# too (a .VS/.VE pair can span a .TP/.IP boundary, e.g. chan.n's
				# TIP656 which starts at the end of one option's description and ends
				# at the end of the next option's); empty when no region is open.
				# Also seeded from a .VS that was still open (with nothing but the
				# .TP/.IP right after it) when THIS list started - see pendingVsInfo -
				# so its first item picks up the marking instead of losing it entirely:
				set dlistVsInfo $pendingVsInfo
				set pendingVsInfo {}
				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]
										if {$itemTitleVs ne ""} {lappend itemAttr -vs $itemTitleVs}
									} else {
										set itemAttr [list]
									}
									lappend dlistContent [list ${blockType}Item $itemAttr [parseDlistItemContent $blockType $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 - this is always a same-line-title
									# item such as a nested character-class/pattern-sequence sub-list
									# (e.g. "string is"'s alnum/alpha/... or "string match"'s */?/[chars]),
									# never a METHOD:/OPTION:/COMMAND:-tagged entry, so lastComment is
									# neither consulted nor touched here - touching it would clobber a
									# value set by a ".\" METHOD: xxx" comment that was already consumed
									# for the *enclosing* list's next .TP item (whose own "start new
									# item" handling below only runs once this nested sub-list's
									# recursive parse - triggered by parseDlistItemContent finishing the
									# enclosing item - has fully returned):
									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
									}
									# the comment only ever labels the single .TP directly below it, so it
									# must not leak into a later, unlabeled .TP (which would otherwise be
									# misidentified as Tcl syntax and mishandled by parseCommand):
									dict set manual lastComment {}
								}
								# snapshot whatever .VS region is open right now as belonging to THIS
								# item's title too (e.g. unicode.n's TIP726, which wraps a .TP's title
								# tightly with nothing else in between) - used when this item is finished
								# (see the itemAttr construction above/below), independently of whatever
								# .VS/.VE this item's own body might additionally open/close:
								set itemTitleVs $dlistVsInfo
								if {$dlistVsInfo ne ""} {
									# a .VS region was still open when the PREVIOUS item finished -
									# re-open it here so it keeps marking into this new item too:
									set itemContent [list ".VS $dlistVsInfo"]
								} else {
									set itemContent {}
								}
							}
						}
						. {
							if $verbose {puts "ignore"}
							# ignore
						}
						{.\"} - {'\"} {
							# remember the wording for the *next* .TP/.IP title, same as
							# the top-level switch does - otherwise every comment inside
							# an already-open .TP/.IP list is silently dropped, and only
							# the list's first item ever gets tagged as METHOD:/OPTION:/COMMAND:
							dict set manual lastComment [lindex $line 1]
							if $verbose {puts "comment (lastComment=[dict get $manual lastComment])"}
						}
						.VS {
							# .VS/.VE are handled generically like any other inline text by the
							# recursive parseBlock call below on this item's content (see the
							# .VS/.VE case in the main switch), so just collect the line like any
							# other; dlistVsInfo only tracks whether the region is still open once
							# this item's content ends, so it can be carried into the next item:
							lassign $line - dlistVsInfo
							lappend itemContent $line
						}
						.VE {
							set dlistVsInfo {}
							lappend itemContent $line
						}
						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]
					if {$itemTitleVs ne ""} {lappend itemAttr -vs $itemTitleVs}
				} else {
					set itemAttr [list]
				}
				lappend dlistContent [list ${blockType}Item $itemAttr [parseDlistItemContent $blockType $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
						# synVersion tracks whether the command line currently being read is inside a
						# .VS/.VE pair, so its TIP marker can be attached to the command's own Span:
						set synVersion {}
						# the synopsis end at the next section header or a Tk section with "STANDARD OPTIONS":
						while {$cmd ne ".SH" && $cmd ne ".SO"} {
							if {$cmd eq ".VS"} {
								lassign $line - synVersion
							} elseif {$cmd eq ".VE"} {
								set synVersion {}
							} elseif {! [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. Only do this when the line is truly
								# just the bare return type (no \fB...\fR anywhere on it yet): a line such as
								# 'typedef int \fBTcl_PostInitProc\fR(...)' already has its own function name
								# embedded and must not have the following (unrelated) line appended to it:
								if {[dict get $manual meta ManualSection] == 3 && [string range $line 0 2] ne "\\fB" && ![string match {*\\fB*} $line]} {
									set line "#$line "
									incr lineCount
									append line [lindex $manContent $lineCount]
								}
								lappend contentList [list Syntax {} [parseCommand -ast $line $synVersion]]
							}
							# 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 ""
						# argRuns collects the explanation text of the current .AP as a list of
						# {version lines} pairs (version == "" outside any .VS/.VE), so a TIP marker
						# wrapping part of the explanation ends up as its own inline Span:
						set argRuns [list]
						set curVersion {}
						set curText [list]
						while {$cmd ne ".SH"} {
							if {$cmd eq ".AP"} {
								# finish previous carg:
								if {$argName ne ""} {
									if {[llength $curText]} {lappend argRuns [list $curVersion $curText]}
									set cargTerm [list Span ".carg .$argDirection type=\"$argType\"" [list [list Text {} $argName]]]
									set cargExplanation [wrapVersionedRuns $argRuns]
									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 argRuns [list]
								set curVersion {}
								set curText [list]
							} elseif {$cmd in {.AS .BS .BE .sp}} {
								# .AS = max size hint for tab stops; .BS .BE = box enclosure;
								# .sp = vertical space: all of these can be ignored
							} elseif {$cmd eq ".VS"} {
								if {[llength $curText]} {lappend argRuns [list $curVersion $curText]; set curText [list]}
								lassign $line - curVersion
							} elseif {$cmd eq ".VE"} {
								if {[llength $curText]} {lappend argRuns [list $curVersion $curText]; set curText [list]}
								set curVersion {}
							} elseif {$cmd in {.QW .PQ .QR}} {
								# inline quoting:
								lappend curText [parseQuoting $line]
							} else {
								# explanatory text:
								lappend curText $line
							}
							# next line:
							incr lineCount
							set line [lindex $manContent $lineCount]
							set cmd [string range $line 0 2]
						}
						# finish last carg:
						if {$argName ne ""} {
							if {[llength $curText]} {lappend argRuns [list $curVersion $curText]}
							set cargTerm [list Span ".carg .$argDirection type=\"$argType\"" [list [list Text {} $argName]]]
							set cargExplanation [wrapVersionedRuns $argRuns]
							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]
					}				
				}
			}
			.SO {
				# standard options of Tk manual pages.
				dict set manual lastComment {}
				if {$blockType ne ""} {set doCloseBlock 1; continue}
				if $verbose {puts "Standard options"}
				lassign $line - refPage
				if {$refPage eq ""} {set refPage options}
				# collect the option names up to the line with .SE:
				set optionList [list]
				set lineCount 1
				while {$lineCount < [llength $manContent] && [string range [lindex $manContent $lineCount] 0 2] ne ".SE"} {
					foreach option [split [parseBackslash [BIRPstrip [lindex $manContent $lineCount]]] "\t "] {
						if {$option ne ""} {lappend optionList $option}
					}
					incr lineCount
				}
				# add to list of possible cross reference targets:
				lappend sectionTitles "Standard options"
				lappend blockList [list Header {-level 1} "Standard options"]
				# (Divs come fully expanded, so we need to give the final AST here):
				set optionTexts [lmap option [lsort -dictionary -unique $optionList] {list Text {} $option}]
				lappend blockList [list Div .standardoptions $optionTexts]
				# (a normal Paragraph still has raw nroff inline content which is expanded later):
				lappend blockList [list Paragraph {} "See the \\fB$refPage\\fR manual entry for details on the standard options."]
				# remove the eaten lines including the .SE from manContent:
				set manContent [lrange $manContent [expr {$lineCount + 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 - .DE {
				# .CE = code end
				# .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 {
				# .VS/.VE mark a region "new in this version" (a TIP number as $info).
				# It commonly occurs *inside* an already-running paragraph
				# so it must not split that paragraph into its own block;
				# instead it stays part of the same block's content and is turned into an
				# inline Span later (see the matching §-style handling in parseInline),
				# just like .QW's quoted text above. This also covers the case where .VS
				# opens the very first sentence of a fresh paragraph.
				if {$blockType eq ""} {set blockType Paragraph}
				lassign $line - info
				set myText ‡$info:
				if {$blockContent eq ""} {append blockContent $myText} else {append blockContent { } $myText}
				set vsOpen 1
				set vsInfo $info
				set manContent [lrange $manContent 1 end]
			}
			.VE {
				# closes the inline region opened by .VS above, but only if one is actually
				# still open in THIS block: a .VS that ran on past its own block boundary
				# already got auto-closed there (see the doCloseBlock handling above) and
				# does not carry forward, so a .VE reaching us here with vsOpen false is a
				# leftover from such a region - ignore it rather than emit a stray, unmatched ¤:
				if {$vsOpen} {
					append blockContent ¤
					set vsOpen 0
				}
				set manContent [lrange $manContent 1 end]
			}
			.DS {
				# .DS = display section: still treated as a whole new (attributed) paragraph:
				if {$blockType ne ""} {set doCloseBlock 1; continue}
				set blockType Paragraph
				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 ""} {
		if {$vsOpen} {append blockContent ¤}
		if {[string trim [regsub -all {‡[^:]*:|¤} $blockContent {}]] ne ""} {
			lappend blockList [list $blockType $blockAttributes $blockContent]
		}
	}
	if {$verbose} {puts "... produced [lindex $blockList end]"}
	return $blockList
}


proc ::ndoc::parseDlistItemContent {blockType itemContent} {
	#
	# parses a .TP/.IP item's raw content the same way parseBlock's callers already
	# do, but also covers the case where the raw text was non-empty (so the earlier
	# 'set itemContent "see below ..."' fallback never kicked in) yet still parses
	# down to nothing at all - e.g. a .VS/.VE pair that turns out to wrap no real
	# text (see parseBlock), which can leave content that is ONLY that marker pair.
	# Without this, the item would render as a bare, dangling "Term\n: " with
	# nothing after the colon instead of the same "see below ..." placeholder used
	# for a genuinely empty item.
	#
	set parsed [parseBlock ${blockType}Item $itemContent]
	if {![llength $parsed]} {
		set parsed [parseBlock ${blockType}Item {{see below ...}}]
	}
	return $parsed
}


proc ::ndoc::parseCommand {mode line {version {}}} {
	#
	# 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
	# version - if the command line was wrapped in a .VS/.VE pair, the TIP/version marker
	#           given to .VS; attached to the command's own Span (.cmd/.ccmd) as a dashed
	#           '-vs' AST attribute (see dashedAttrLabel/formatSpanAttributes), so it shows
	#           up as e.g. [Tcl_LinkArray]{.ccmd version="TIP312"}
	#
	# Note: the Span elements are alread fully expanded with appropriate AST "Text" elements
	#
	set DEBUG 0
	set verAttr {}
	if {$version ne ""} {set verAttr " -vs {$version}"}
	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 {[string match "typedef *" $line]} {
		# a raw 'typedef <returntype> \fBname\fR(...)' declaration appearing directly in
		# the SYNOPSIS of a section 3 page:
		# treat "typedef <returntype>" as the return type (.ret), just like the bare return
		# type on its own line does for a normal API function, then fall through to
		# the regular command()/args splitting below:
		set startIndex [string first "§" $line]
		set l0 "#[string trim [string range $line 0 [expr {$startIndex - 1}]]]"
		set openParens [string first ( $line $startIndex]
		set l1 [string range $line $startIndex [expr {$openParens - 1}]]
		set l2 [string range $line [expr {$openParens + 1}] end-1]
		set line [list $l0 $l1 $l2]
	} elseif {[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$verAttr" [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$verAttr" [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 Space {} {}] [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]
		} elseif {$char eq "‡"} {
			# a .VS/.VE region (starts with ‡<info>: and ends with ¤, see parseBlock):
			# recurse so any markup inside the region (bold, quotes, ...) still works,
			# then wrap the result in a Span carrying the version as a -vs attribute:
			if {$verbose || $DEBUG} {puts VERSIONED}
			set infoEnd [string first : $content 1]
			if {$infoEnd == -1} {return -code error "parseInline: unbalanced .VS marker (no info separator found)"}
			set info [string range $content 1 $infoEnd-1]
			set endMark [string first ¤ $content $infoEnd+1]
			if {$endMark == -1} {return -code error "parseInline: unbalanced .VS marker (no matching .VE found)"}
			# trim: the join-separator before the first line inside the region ends up
			# right after the ':', since that line is appended like any other content line:
			set innerText [string trim [string range $content $infoEnd+1 $endMark-1]]
			if {$innerText ne ""} {
				# a region with no real text (e.g. .VS sitting right at the end of a
				# .TP item, its .VE only closing much further along) has nothing to
				# tag - emitting an empty '[]{version="..."}' would just be noise:
				lappend inlineAST [list Span "-vs {$info}" [lindex [parseInline Inline {} $innerText] 2]]
			}
			set content [string range $content $endMark+1 end]
		} else {
			# normal text, digest it until
			# - a known backslash sequence comes (\fI, \fB, ...)
			# - a quoted text comes
			# - a .VS/.VE region starts
			# - 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', a quote or a .VS marker 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::dashedAttrLabel {key} {
	#
	# maps an internal dashed AST attribute name (e.g. '-vs', as used for Header's
	# -level, Dlist's -definition etc.) to the attribute name it is given when
	# formatted into markdown (e.g. 'version'). This lets the AST keep a short,
	# stable internal name for an attribute while the rendered output uses a
	# more descriptive one; a key with no explicit mapping below is rendered
	# under its own name, with the leading dash(es) stripped.
	#
	set label [string trimleft $key -]
	switch -- $label {
		vs {return version}
		default {return $label}
	}
}


proc ::ndoc::formatSpanAttributes {attributes} {
	#
	# formats a Span's 'attributes' string for markdown output.
	#
	# A Span's attributes are normally just a literal, pre-built string of Pandoc
	# classes and already-formatted key="value" pairs (e.g. '.carg .in type="Tcl_Interp"',
	# '.ccmd') that is used as-is and MUST NOT be touched here.
	#
	# On top of that literal class string, a Span may also carry one or more dashed
	# AST attributes appended to it (e.g. '.ccmd -vs {TIP312}'), using the same
	# '-key {value}' convention used elsewhere in the AST (see dashedAttrLabel). The
	# value is brace-quoted (rather than a bare \S+) because a .VS marker's info can
	# itself contain whitespace, e.g. .VS "TIP607, TIP656" or .VS "TIP 551". Those
	# are extracted here and rendered into markdown attribute syntax; everything
	# else in the string (the dotted classes) passes through unchanged.
	#
	set extra {}
	foreach {- key val} [regexp -all -inline -- {-([A-Za-z][A-Za-z0-9]*)\s+\{([^\}]*)\}} $attributes] {
		append extra { } [dashedAttrLabel -$key] = \x22 $val \x22
	}
	set classes [string trim [regsub -all -- {-([A-Za-z][A-Za-z0-9]*)\s+\{([^\}]*)\}} $attributes {}]]
	return [string trim "$classes$extra"]
}


proc ::ndoc::wrapVersionedRuns {runs} {
	#
	# converts a list of "runs" of raw nroff text into a list of AST inline elements,
	# wrapping any run that carries a TIP/version marker (as set by a .VS/.VE pair)
	# in a Span so it shows up inline as e.g. [some text]{version="TIP312"},
	# instead of the text being dropped or forcing a whole new block.
	# This is the general way a .VS/.VE region occurring inside a paragraph or
	# other inline text is rendered (a .VS/.VE pair wrapping a *whole* top-level
	# paragraph or command is handled elsewhere, e.g. by tagging the enclosing
	# Paragraph/Span node directly).
	#
	# runs - a list of {version lines} pairs, in document order, where "lines" is
	#        a list of raw (backslash/quote-processed) nroff text fragments that
	#        belong to one contiguous run of the same version marker
	#        ("version" is the empty string for text outside any .VS/.VE)
	#
	set contentList [list]
	foreach run $runs {
		lassign $run version lines
		set text [string trim [join $lines { }]]
		if {$text eq ""} continue
		set inlineContent [lindex [parseInline Inline {} $text] 2]
		if {[llength $contentList]} {lappend contentList [list Space {} {}]}
		if {$version ne ""} {
			lappend contentList [list Span "-vs {$version}" $inlineContent]
		} else {
			lappend contentList {*}$inlineContent
		}
	}
	return $contentList
}


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
				if {$key eq "CommandName"} {append output "title: $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; dashed AST attribute names (e.g. -vs)
						# are mapped to their markdown attribute name (e.g. version):
						dict for {k v} $attributes {append output { } [dashedAttrLabel $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_ [ \u005c[ ] \u005c]} $content]
		}
		Code {
			foreach codeLine [split $content \n] {append output [string repeat { } $indent] $codeLine \n}
		}
		Space {
			append output { }
		}
		DlistItem {
			# a DlistItem can legitimately have no body at all (e.g. two .TP's in a
			# row describing alternate call signatures, where only the second one
			# carries the description; or a .VS/.VE pair that turned out to wrap no
			# real text and was dropped - see parseBlock/parseInline), so guard
			# against an empty content list instead of assuming a first element:
			if {[llength $content]} {
				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 \{ [formatSpanAttributes $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
	#
	variable manual
	man2AST $manContent
	#
	# determine the output group (= output subdirectory) of this page: Tcl or Tk,
	# with the suffix CAPI for the C API pages (manual section 3).
	# This is needed in mdLinks to build the paths of cross references.
	# (a page belongs to Tk if the part name given in its .TH line is "Tk"):
	if {[dict get $manual meta TclPart] eq "Tk"} {
		set group Tk
	} else {
		set group Tcl
	}
	if {[dict get $manual meta ManualSection] eq "3"} {append group CAPI}
	dict set manual outGroup $group
	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 \
				{**clock format now -f %a; # current day of the week** **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]
		}
		interp {
			# the page has links to both Eval.3 and to eval.n, which Pandoc will normalize into the same reference.
			# So, we need to rename one of them:
			set md [string map {
				{[Eval]} {[Eval3]}
			} $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`}
				{[Eval]} {[Eval3]}
			} $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]
		}
		Tcl {
			set md [string map {
				{double-quote ("\\"") then the word} {double-quote ('\"') then the word}
			} $md]
			## " (make my Geany editor syntaxhighlight happy again)
		}
		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]
		}
		Tcl_Class {
			set md [string map {
				{## Tcl\_objectmetadatatype structure} {## Tcl\_ObjectMetadataType structure}
				{## Tcl\_objectmetadatadeleteproc function signature} {## Tcl\_ObjectMetadataDeleteProc function signature}
				{## Tcl\_cloneproc function signature} {## Tcl\_CloneProc function signature}
				{## Tcl\_objectmapmethodnameproc function signature} {## Tcl\_ObjectMapMethodNameProc function signature}
			} $md]
		}
		Tcl_CreateChannel {
			set md [string map {
				{## Typename} {## typeName}
				{## Version} {## version}
				{## Blockmodeproc} {## blockModeProc}
				{## Close2proc} {## close2Proc}
				{## Inputproc} {## inputProc}
				{## Outputproc} {## outputProc}
				{## Wideseekproc} {## wideSeekProc}
				{## Setoptionproc} {## setOptionProc}
				{## Getoptionproc} {## getOptionProc}
				{## Watchproc} {## watchProc}
				{## Gethandleproc} {## getHandleProc}
				{## Flushproc} {## flushProc}
				{## Handlerproc} {## handlerProc}
				{## Threadactionproc} {## threadActionProc}
				{## Truncateproc} {## truncateProc}
				{# Tcl\_badchanneloption} {# Tcl\_BadChannelOption}
				{and "<specific options>" is} {and "\<specific options\>" is}
			} $md]
		}
		Tcl_GetEncoding {
			set md [string map {
				{using tcl\_dstring} {using Tcl\_DString}
			} $md]
		}
		Filesystem {
			set md [string map {
				{(e.g.\\ } {(e.g. }
				{[open], etc.\\ Tcl commands} {[open], etc. Tcl commands}
				{## Fs api functions} {## FS API functions}
				{.i.e\\ } {i.e. }
				{## Portable stat result api} {## Portable stat result API}
				{# The virtual filesystem api} {# The virtual filesystem API}
				{## The tcl\_filesystem structure} {## The Tcl\_Filesystem structure}
				{## Typename} {## typeName}
				{## Structure length} {## structureLength}
				{## Version} {## version}
				{## Pathinfilesystemproc} {## pathInFilesystemProc}
				{## Dupinternalrepproc} {## dupInternalRepProc}
				{## Freeinternalrepproc} {## freeInternalRepProc}
				{## Internaltonormalizedproc} {## internalToNormalizedProc}
				{## Createinternalrepproc} {## createInternalRepProc}
				{## Normalizepathproc} {## normalizePathProc}
				{## Filesystempathtypeproc} {## filesystemPathTypeProc}
				{## Filesystemseparatorproc} {## filesystemSeparatorProc}
				{## Statproc} {## statProc}
				{## Accessproc} {## accessProc}
				{## Openfilechannelproc} {## openFileChannelProc}
				{## Matchindirectoryproc} {## matchInDirectoryProc}
				{## Utimeproc} {## utimeProc}
				{## Linkproc} {## linkProc}
				{## Listvolumesproc} {## listVolumesProc}
				{## Fileattrstringsproc} {## fileAttrStringsProc}
				{## Fileattrsgetproc} {## fileAttrsGetProc}
				{## Fileattrssetproc} {## fileAttrsSetProc}
				{## Createdirectoryproc} {## createDirectoryProc}
				{## Removedirectoryproc} {## removeDirectoryProc}
				{## Deletefileproc} {## deleteFileProc}
				{## Lstatproc} {## lstatProc}
				{## Copyfileproc} {## copyFileProc}
				{## Renamefileproc} {## renameFileProc}
				{## Copydirectoryproc} {## copyDirectoryProc}
				{## Loadfileproc} {## loadFileProc}
				{## Unloadfileproc} {## unloadFileProc}
				{## Getcwdproc} {## getCwdProc}
				{## Chdirproc} {## chdirProc}
				{## Public api calls} {## Public API calls}
				{[Load]} {[Load3]}
			} $md]
		}
		Tcl_GetIndexFromObj {
			set md [string map {
				{bad option \\"firt\\"} {bad option "firt"}
			} $md]
		}
		Tcl_Hash {
			set md [string map {
				{# The tcl\_hashkeytype structure} {# The Tcl\_HashKeyType structure}
			} $md]
		}
		Tcl_LimitCheck {
			set md [string map {
				{# Limit checking api} {# Limit checking API}
			} $md]
		}
		Tcl_Method {
			set md [string map {
				{## Tcl\_methodcallproc function signature} {## Tcl\_MethodCallProc function signature}
				{## Tcl\_methoddeleteproc function signature} {## Tcl\_MethodDeleteProc function signature}
				{## Tcl\_cloneproc function signature} {## Tcl\_CloneProc function signature}
			} $md]
		}
		NRE {
			set md [string map {
				{[\*data0]{.carg .in type="void"}
: 

[\*data1]{.carg .in type="void"}
: 

[\*data2]{.carg .in type="void"}
: 

[\*data3]{.carg .in type="void"}} {[\*data0]{.carg .in type="void"}, [\*data1]{.carg .in type="void"}, [\*data2]{.carg .in type="void"}, [\*data3]{.carg .in type="void"}}
			} $md]
		}
		Tcl_Obj {
			set md [string map {
				{# The tcl\_obj structure} {# The Tcl\_Obj structure}
			} $md]
		}
		Tcl_ObjType {
			set md [string map {
				{## The updatestringproc field} {## The updateStringProc field}
				{## The dupintrepproc field} {## The dupIntRepProc field}
				{## The freeintrepproc field} {## The freeIntRepProc field}
				{## The lengthproc field} {## The lengthProc field}
				{## The indexproc field} {## The indexProc field}
				{## The sliceproc field} {## The sliceProc field}
				{## The reverseproc field} {## The reverseProc field}
				{## The getelements field} {## The getElements field}
				{## The setelement field} {## The setElement field}
				{## The replaceproc field} {## ReplaceProc field}
				{## The inoperproc field} {## The InOperProc field}
			} $md]
		}
		Tcl_OpenFileChannel {
			set md [string map {
				{# Tcl\_openfilechannel} {# Tcl\_OpenFileChannel}
				{# Tcl\_opencommandchannel} {# Tcl\_OpenCommandChannel}
				{# Tcl\_makefilechannel} {# Tcl\_MakeFileChannel}
				{# Tcl\_getchanneloption} {# Tcl\_GetChannelOption}
				{# Tcl\_getchannel} {# Tcl\_GetChannel}
				{# Tcl\_registerchannel} {# Tcl\_RegisterChannel}
				{# Tcl\_unregisterchannel} {# Tcl\_UnregisterChannel}
				{# Tcl\_detachchannel} {# Tcl\_DetachChannel}
				{# Tcl\_isstandardchannel} {# Tcl\_IsStandardChannel}
				{# Tcl\_close and tcl\_closeex} {# Tcl\_Close and Tcl\_CloseEx}
				{# Tcl\_readchars and tcl\_read} {# Tcl\_ReadChars and Tcl\_Read}
				{# Tcl\_getsobj and tcl\_gets} {# Tcl\_GetsObj and Tcl\_Gets}
				{# Tcl\_ungets} {# Tcl\_Ungets}
				{# Tcl\_writechars, tcl\_writeobj, and tcl\_write} {# Tcl\_WriteChars, Tcl\_WriteObj, and Tcl\_Write}
				{# Tcl\_flush} {# Tcl\_Flush}
				{# Tcl\_seek} {# Tcl\_Seek}
				{# Tcl\_tell} {# Tcl\_Tell}
				{# Tcl\_truncatechannel} {# Tcl\_TruncateChannel}
				{# Tcl\_setchanneloption} {# Tcl\_SetChannelOption}
				{# Tcl\_eof} {# Tcl\_Eof}
				{# Tcl\_inputblocked} {# Tcl\_InputBlocked}
				{# Tcl\_inputbuffered} {# Tcl\_InputBuffered}
				{# Tcl\_outputbuffered} {# Tcl\_OutputBuffered}
			} $md]
		}
		Tcl_OpenTcpClient {
			set md [string map {
				{## Tcl\_opentcpclient} {## Tcl\_OpenTcpClient}
				{## Tcl\_maketcpclientchannel} {## Tcl\_MakeTcpClientChannel}
				{## Tcl\_opentcpserverex} {## Tcl\_OpenTcpServerEx}
				{## Tcl\_opentcpserver} {## Tcl\_OpenTcpServer}
			} $md]
		}
		Tcl_RegisterConfig {
			set md [string map {
				{# Tcl\_config} {# Tcl\_Config}
			} $md]
		}
		TclSetResult {
			set md [string map {
				{# The tcl\_freeproc argument to tcl\_setresult} {# The Tcl\_FreeProc argument to Tcl\_SetResult}
			} $md]
		}
		Tcl_SplitList {
			set md [string map {
				{[Eval]} {[Eval3]}
			} $md]
		}
		"Standard Channels" {
			set md [string map {
				{# Initialization of tcl standard channels} {# Initialization of Tcl standard channels}
				{# Re-initialization of tcl standard channels} {# Re-initialization of Tcl standard channels}
			} $md]
		}
		Tcl_TraceCommand - Tcl_TraceVar {
			set md [string map {
				{# Tcl\_trace\_destroyed flag} {# TCL\_TRACE\_DESTROYED flag}
			} $md]
		}
		
	}
	regsub {\s+$} $md \n md
	# tidy up a blank lines at divs:
	set md [string map  [list "\n\n:::\n" "\n:::\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 tkCmdFileMap
	variable tclReturnCodeFileMap
	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]
	set fileRoot $fileName
	set outGroup [dict get $manual outGroup]
	# 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 linkGroup Tcl
			set isValidLink 1
		}
		if {! $isValidLink && $linkCmd ne $cmdName} {
			## link to a known Tk command (or a Tk variable/option page);
			## the file to link to is not always the command name (e.g. tk_chooseColor -> chooseColor):
			set linkCmdSubst [subst -novariables -nocommands $linkCmd]
			if {![dict exists $tkCmdFileMap $linkCmdSubst] && [string match ttk_* $linkCmdSubst]} {
				## the ttk man pages are also referred to by their file name (e.g. ttk_widget for ttk::widget):
				set linkCmdSubst ttk::[string range $linkCmdSubst 4 end]
			}
			if {[dict exists $tkCmdFileMap $linkCmdSubst]} {
				set apiTarget [dict get $tkCmdFileMap $linkCmdSubst]
				if {$apiTarget ne $fileRoot || $outGroup ne "Tk"} {
					set linkTarget $apiTarget
					set linkGroup Tk
					set isValidLink 1
				}
			}
		}
		if {! $isValidLink && ([string match {Tcl\\_*} $linkCmd] || [string match {TclZipfs\\_*} $linkCmd])} {
			## a Tcl C API function (Tcl_... or TclZipfs_...)
			# (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 || $outGroup ne "TclCAPI"} {
					## don't link to another Tcl_ function documented on this very page:
					set linkTarget $apiTarget
					set linkGroup TclCAPI
					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 || $outGroup ne "TkCAPI"} {
					## don't link to another Tk_ function documented on this very page:
					set linkTarget $apiTarget
					set linkGroup TkCAPI
					set isValidLink 1
				}
			}
		}
		if {! $isValidLink && [string match {TCL\\_*} $linkCmd]} {
			## a Tcl script-level return code constant (TCL_OK, TCL_ERROR, ...):
			# (note that we can't handle this in tclCmdList as the md conversion has added a backslash (TCL\_...);
			#  dict exists also excludes unrelated TCL_-prefixed tokens such as TCL_LIBRARY or TCL_VERSION):
			set linkCmdSubst [subst -novariables -nocommands $linkCmd]
			if {[dict exists $tclReturnCodeFileMap $linkCmdSubst]} {
				set apiTarget [dict get $tclReturnCodeFileMap $linkCmdSubst]
				if {$apiTarget ne $fileRoot || $outGroup ne "Tcl"} {
					## don't link to catch.md from catch.n itself:
					set linkTarget $apiTarget
					set linkGroup Tcl
					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 ""} {
				if {[string is upper [string index $linkTarget 0]] && $linkTarget ne "Tcl"} {
					set linkGroup TclCAPI
				} else {
					set linkGroup Tcl
				}
				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
			set linkGroup internal
		}
		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 $linkGroup}
			# 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]
	}
	# second pass for plain text Tcl_OK, TCL_ERROR etc.
	# while skiping text that is already inside a markdown link/span or in an inline code span:
	set pos 0
	while 1 {
		set matchIndices [regexp -inline -expanded -indices -start $pos {
			(\[[^]\n]*\](?:\{[^\}\n]*\}|\([^)\n]*\)|\[[^]\n]*\])?)  # existing link or span: skip over
			|
			(`[^`\n]*`)                                             # inline code span: skip over
			|
			(\m(?:Tcl|Tk|TCL)\\_[A-Za-z0-9]+)                       # candidate API identifier
		} $md]
		if {![llength $matchIndices]} break
		lassign $matchIndices fullRange skipRange codeRange candRange
		if {[lindex $candRange 0] == -1} {
			# a link/span or inline code span: leave untouched:
			set pos [expr {[lindex $fullRange 1] + 1}]
			continue
		}
		set linkCmd [string range $md {*}$candRange]
		set linkCmdSubst [subst -novariables -nocommands $linkCmd]
		set apiTarget {}
		set linkGroup {}
		if {[dict exists $tclCApiFileMap $linkCmdSubst]} {
			set apiTarget [dict get $tclCApiFileMap $linkCmdSubst]
			set linkGroup TclCAPI
		} elseif {[dict exists $tkCApiFileMap $linkCmdSubst]} {
			set apiTarget [dict get $tkCApiFileMap $linkCmdSubst]
			set linkGroup TkCAPI
		} elseif {[dict exists $tclReturnCodeFileMap $linkCmdSubst]} {
			set apiTarget [dict get $tclReturnCodeFileMap $linkCmdSubst]
			set linkGroup Tcl
		}
		if {$apiTarget ne {} && ($apiTarget ne $fileRoot || $outGroup ne $linkGroup)} {
			## don't link to the very page that documents this identifier:
			set replaceString \[$linkCmd\]\[$apiTarget\]
			set md [string replace $md {*}$candRange $replaceString]
			lappend refList $apiTarget $linkGroup
			set pos [expr {[lindex $candRange 0] + [string length $replaceString]}]
		} else {
			set pos [expr {[lindex $candRange 1] + 1}]
		}
	}
	# add link references at the bottom of the page:
	if {[llength $refList]} {
		append md \n\n
		foreach {linkCmd linkGroup} [lsort -dictionary -stride 2 -unique $refList] {
			if {$outGroup ne $linkGroup} {
				append md \[ $linkCmd \] : { } .. / $linkGroup / $linkCmd .md \n
			} else {
				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 nroff-original]
		set tkManDir [file join $myDir .. doc]	
		set myFile [file join $tclManDir string.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
		}
		# The output goes into a subdirectory of outDir that depends on where the page belongs
		# (ndoc::man2markdown determines this from the manual page itself and puts it into
		#  the 'outGroup' key of the $manual dictionary):
		#   Tcl      - Tcl commands (sections n and 1)
		#   TclCAPI  - Tcl C API (from section 3)
		#   Tk       - Tk and ttk commands (sections n and 1)
		#   TkCAPI   - Tk C API (section 3)
		#
		foreach section {n 1 3} {
			foreach file [lsort -dictionary [glob -nocomplain [file join $inDir *.$section]]] {
				puts "converting $file ..."
				set sectionTitles [list]
				set md [man2markdown [readFile $file]]
				set MDdir [dict get $manual outGroup]
				set stem [file rootname [file tail $file]]
				file mkdir [file join $outDir $MDdir]
				set fh [open [file join $outDir $MDdir $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
}