CAWT 2.9.1 Reference Manual

::WordTop, Main, Index

The Word namespace provides commands to control Microsoft Word.

CommandsTop, Main, Index

AddBookmark [::Word]Top, Main, Index

Add a bookmark to a text range.

AddBookmark rangeId name
rangeIdIdentifier of the text range.
nameName of the bookmark.

Returns the bookmark identifier.

See also: SetLinkToBookmark, GetBookmarkName

proc ::Word::AddBookmark {rangeId name} {

    # Add a bookmark to a text range.
    #
    # rangeId - Identifier of the text range.
    # name    - Name of the bookmark.
    #
    # Returns the bookmark identifier.
    #
    # See also: SetLinkToBookmark GetBookmarkName

    set docId [Word GetDocumentId $rangeId]
    set bookmarks [$docId Bookmarks]
    # Create valid bookmark names.
    set validName [regsub -all { } $name {_}]
    set validName [regsub -all -- {-} $validName {_}]
    set bookmarkId [$bookmarks Add $validName $rangeId]

    Cawt Destroy $bookmarks
    Cawt Destroy $docId
    return $bookmarkId
}

AddContentControl [::Word]Top, Main, Index

Add a content control to a text range.

AddContentControl rangeId type ?title?
rangeIdIdentifier of the text range.
typeValue of enumeration type Enum::WdContentControlType. Often used values: wdContentControlCheckBox, wdContentControlText.
titleTitle string for the control. Optional, default "".

Returns the content control identifier.

See also: SetContentControlText, SetContentControlDropdown

proc ::Word::AddContentControl {rangeId type {title {}}} {

    # Add a content control to a text range.
    #
    # rangeId - Identifier of the text range.
    # type    - Value of enumeration type [Enum::WdContentControlType].
    #           Often used values: `wdContentControlCheckBox`, `wdContentControlText`.
    # title   - Title string for the control.
    #
    # Returns the content control identifier.
    #
    # See also: SetContentControlText SetContentControlDropdown

    variable wordVersion

    if { $wordVersion < 12.0 } {
        error "Content controls available only in Word 2007 or newer. Running [Word GetVersion $rangeId true]."
    }

    set controlId [$rangeId -with { ContentControls } Add [Word GetEnum $type]]
    if { $title ne "" } {
        $controlId Title $title
    }
    return $controlId
}

AddDocument [::Word]Top, Main, Index

Add a new empty document to a Word instance.

AddDocument appId ?type? ?visible?
appIdIdentifier of the Word instance.
typeValue of enumeration type Enum::WdNewDocumentType. Optional, default "".
visibleIf set to true, show the application window. Otherwise hide the application window. Optional, default true.

Returns the identifier of the new document.

See also: OpenDocument, SetPageSetup

proc ::Word::AddDocument {appId {type {}} {visible true}} {

    # Add a new empty document to a Word instance.
    #
    # appId   - Identifier of the Word instance.
    # type    - Value of enumeration type [Enum::WdNewDocumentType].
    # visible - If set to true, show the application window.
    #           Otherwise hide the application window.
    #
    # Returns the identifier of the new document.
    #
    # See also: OpenDocument SetPageSetup

    if { $type eq "" } {
        set type $Word::wdNewBlankDocument
    }
    set docs [$appId Documents]
    # Add([Template], [NewTemplate], [DocumentType], [Visible]) As Document
    set docId [$docs -callnamedargs Add  DocumentType [Word GetEnum $type]  Visible [Cawt TclInt $visible]]
    Cawt Destroy $docs
    return $docId
}

AddImageTable [::Word]Top, Main, Index

Add a new table and fill the cells with images.

AddImageTable rangeId numCols imgList ?captionList?
rangeIdIdentifier of the text range.
numColsNumber of columns of the new table.
imgListList of image file names.
captionListList of caption texts. Optional, default "".

Returns the identifier of the new table.

See also: AddTable, InsertImage

proc ::Word::AddImageTable {rangeId numCols imgList {captionList {}}} {

    # Add a new table and fill the cells with images.
    #
    # rangeId     - Identifier of the text range.
    # numCols     - Number of columns of the new table.
    # imgList     - List of image file names.
    # captionList - List of caption texts.
    #
    # Returns the identifier of the new table.
    #
    # See also: AddTable InsertImage

    set numImgs  [llength $imgList]
    set numTexts [llength $captionList]

    if { $numCols <= 0 } {
        error "AddImageTable: Number of columns must be greater than zero."
    }

    set numRowsToAdd 1
    if { $numTexts > 0 } {
        incr numRowsToAdd
    }
    set tableId [Word AddTable $rangeId $numRowsToAdd $numCols]

    set curRow  1
    set curCol  1
    set curElem 0
    foreach img $imgList {
        set caption ""
        if { $curElem < $numTexts } {
            set caption [lindex $captionList $curElem]
        }
        if { $numTexts > 0 } {
            Word SetCellValue $tableId [expr { $curRow + 1}] $curCol $caption
        }
        set rangeId [Word GetCellRange $tableId $curRow $curCol]
        Word InsertImage $rangeId $img
        Cawt Destroy $rangeId
        incr curCol
        incr curElem
        if { $curCol > $numCols } {
            set curCol 1
            incr curRow $numRowsToAdd
            if { $curElem < $numImgs } {
                Word AddRow $tableId end $numRowsToAdd
            }
        }
    }
    return $tableId
}

AddPageBreak [::Word]Top, Main, Index

Add a page break to a text range.

AddPageBreak rangeId
rangeIdIdentifier of the text range.

Returns no value.

See also: AddParagraph

proc ::Word::AddPageBreak {rangeId} {

    # Add a page break to a text range.
    #
    # rangeId - Identifier of the text range.
    #
    # Returns no value.
    #
    # See also: AddParagraph

    $rangeId Collapse $Word::wdCollapseEnd
    $rangeId InsertBreak [expr { int ($Word::wdPageBreak) }]
    $rangeId Collapse $Word::wdCollapseEnd
}

AddParagraph [::Word]Top, Main, Index

Add a new paragraph to a document.

AddParagraph rangeId ?spaceAfter?
rangeIdIdentifier of the text range.
spaceAfterSpacing after the range. Optional, default -1.

The spacing value may be specified in a format acceptable by procedure ::Cawt::ValueToPoints, i.e. centimeters, inches or points.

Returns the new extended range.

See also: AppendParagraph

proc ::Word::AddParagraph {rangeId {spaceAfter -1}} {

    # Add a new paragraph to a document.
    #
    # rangeId    - Identifier of the text range.
    # spaceAfter - Spacing after the range.
    #
    # The spacing value may be specified in a format acceptable by
    # procedure [::Cawt::ValueToPoints], i.e. centimeters, inches or points.
    #
    # Returns the new extended range.
    #
    # See also: AppendParagraph

    $rangeId InsertParagraphAfter
    set spaceAfter [Cawt ValueToPoints $spaceAfter]
    if { $spaceAfter >= 0 } {
        $rangeId -with { ParagraphFormat } SpaceAfter $spaceAfter
    }
    return $rangeId
}

AddRow [::Word]Top, Main, Index

Add one or more rows to a table.

AddRow tableId ?beforeRowNum? ?numRows?
tableIdIdentifier of the Word table.
beforeRowNumInsertion row number. Row numbering starts with 1. The new row is inserted before the given row number. If not specified or end, the new row is appended at the end. Optional, default end.
numRowsNumber of rows to be inserted. Optional, default 1.

Returns no value.

See also: DeleteRow, GetNumRows

proc ::Word::AddRow {tableId {beforeRowNum end} {numRows 1}} {

    # Add one or more rows to a table.
    #
    # tableId      - Identifier of the Word table.
    # beforeRowNum - Insertion row number. Row numbering starts with 1.
    #                The new row is inserted before the given row number.
    #                If not specified or `end`, the new row is appended at
    #                the end.
    # numRows      - Number of rows to be inserted.
    #
    # Returns no value.
    #
    # See also: DeleteRow GetNumRows

    Cawt PushComObjects

    set rowsId [$tableId Rows]
    if { $beforeRowNum eq "end" } {
        for { set r 1 } { $r <= $numRows } {incr r } {
            $rowsId Add
        }
    } else {
        if { $beforeRowNum < 1 || $beforeRowNum > [Word GetNumRows $tableId] } {
            error "AddRow: Invalid row number $beforeRowNum given."
        }
        set rowId [$tableId -with { Rows } Item $beforeRowNum]
        for { set r 1 } { $r <= $numRows } {incr r } {
            $rowsId Add $rowId
        }
    }

    Cawt PopComObjects
}

AddTable [::Word]Top, Main, Index

Add a new table in a text range.

AddTable rangeId numRows numCols ?spaceAfter?
rangeIdIdentifier of the text range.
numRowsNumber of rows of the new table.
numColsNumber of columns of the new table.
spaceAfterSpacing in points after the table. Optional, default -1.

The spacing value may be specified in a format acceptable by procedure ::Cawt::ValueToPoints, i.e. centimeters, inches or points.

Returns the identifier of the new table.

See also: DeleteTable, GetNumTables, GetNumRows, GetNumColumns

proc ::Word::AddTable {rangeId numRows numCols {spaceAfter -1}} {

    # Add a new table in a text range.
    #
    # rangeId    - Identifier of the text range.
    # numRows    - Number of rows of the new table.
    # numCols    - Number of columns of the new table.
    # spaceAfter - Spacing in points after the table.
    #
    # The spacing value may be specified in a format acceptable by
    # procedure [::Cawt::ValueToPoints], i.e. centimeters, inches or points.
    #
    # Returns the identifier of the new table.
    #
    # See also: DeleteTable GetNumTables GetNumRows GetNumColumns

    set docId [Word GetDocumentId $rangeId]
    set tableId [$docId -with { Tables } Add $rangeId $numRows $numCols]
    set spaceAfter [Cawt ValueToPoints $spaceAfter]
    if { $spaceAfter >= 0 } {
        $tableId -with { Range ParagraphFormat } SpaceAfter $spaceAfter
    }
    Cawt Destroy $docId
    return $tableId
}

AddText [::Word]Top, Main, Index

Add text to a Word document.

AddText rangeId text ?addParagraph? ?style?
rangeIdIdentifier of the text range.
textText string to be added.
addParagraphAdd a paragraph after the text. Optional, default false.
styleValue of enumeration type Enum::WdBuiltinStyle. Optional, default wdStyleNormal.

The text string is appended to the supplied text range with given style.

Returns the new text range.

See also: AddText, InsertText, AppendParagraph, SetRangeStyle

proc ::Word::AddText {rangeId text {addParagraph false} {style wdStyleNormal}} {

    # Add text to a Word document.
    #
    # rangeId      - Identifier of the text range.
    # text         - Text string to be added.
    # addParagraph - Add a paragraph after the text.
    # style        - Value of enumeration type [Enum::WdBuiltinStyle].
    #
    # The text string is appended to the supplied text range with given style.
    #
    # Returns the new text range.
    #
    # See also: AddText InsertText AppendParagraph SetRangeStyle

    set newStartIndex [$rangeId End]
    set docId [Word GetDocumentId $rangeId]
    set newRange [Word CreateRange $docId $newStartIndex $newStartIndex]
    $newRange InsertAfter $text
    if { $addParagraph } {
        $newRange InsertParagraphAfter
    }
    Word SetRangeStyle $newRange $style
    Cawt Destroy $docId
    return $newRange
}

AppendParagraph [::Word]Top, Main, Index

Append a paragraph at the end of the document.

AppendParagraph docId ?spaceAfter?
docIdIdentifier of the document.
spaceAfterSpacing after the range. Optional, default -1.

The spacing value may be specified in a format acceptable by procedure ::Cawt::ValueToPoints, i.e. centimeters, inches or points.

Returns no value.

See also: GetEndRange, AddParagraph

proc ::Word::AppendParagraph {docId {spaceAfter -1}} {

    # Append a paragraph at the end of the document.
    #
    # docId      - Identifier of the document.
    # spaceAfter - Spacing after the range.
    #
    # The spacing value may be specified in a format acceptable by
    # procedure [::Cawt::ValueToPoints], i.e. centimeters, inches or points.
    #
    # Returns no value.
    #
    # See also: GetEndRange AddParagraph

    set endRange [Word GetEndRange $docId]
    $endRange InsertParagraphAfter
    set spaceAfter [Cawt ValueToPoints $spaceAfter]
    if { $spaceAfter >= 0 } {
        $endRange -with { ParagraphFormat } SpaceAfter $spaceAfter
    }
    return $endRange
}

AppendText [::Word]Top, Main, Index

Append text to a Word document.

AppendText docId text ?addParagraph? ?style?
docIdIdentifier of the document.
textText string to be appended.
addParagraphAdd a paragraph after the text. Optional, default false.
styleValue of enumeration type Enum::WdBuiltinStyle. Optional, default wdStyleNormal.

The text string is appended at the end of the document with given style.

Returns the new text range.

See also: GetEndRange, AddText, InsertText, AppendParagraph, SetRangeStyle

proc ::Word::AppendText {docId text {addParagraph false} {style wdStyleNormal}} {

    # Append text to a Word document.
    #
    # docId        - Identifier of the document.
    # text         - Text string to be appended.
    # addParagraph - Add a paragraph after the text.
    # style        - Value of enumeration type [Enum::WdBuiltinStyle].
    #
    # The text string is appended at the end of the document with given style.
    #
    # Returns the new text range.
    #
    # See also: GetEndRange AddText InsertText AppendParagraph SetRangeStyle

    set newRange [Word GetEndRange $docId]
    $newRange InsertAfter $text
    if { $addParagraph } {
        $newRange InsertParagraphAfter
    }
    Word SetRangeStyle $newRange $style
    return $newRange
}

Close [::Word]Top, Main, Index

Close a document without saving changes.

Close docId
docIdIdentifier of the document.

Use the SaveAs method before closing, if you want to save changes.

Returns no value.

See also: SaveAs

proc ::Word::Close {docId} {

    # Close a document without saving changes.
    #
    # docId - Identifier of the document.
    #
    # Use the [SaveAs] method before closing, if you want to save changes.
    #
    # Returns no value.
    #
    # See also: SaveAs

    $docId Close [Cawt TclBool false]
}

CollapseRange [::Word]Top, Main, Index

Collapse a text range to the start or end position.

CollapseRange rangeId ?direction?
rangeIdIdentifier of the text range.
directionCollapse direction: begin or end. Optional, default begin.

After a range is collapsed, the start and end points are equal.

See also: CreateRange, GetStartRange, GetEndRange

proc ::Word::CollapseRange {rangeId {direction begin}} {

    # Collapse a text range to the start or end position.
    #
    # rangeId   - Identifier of the text range.
    # direction - Collapse direction: `begin` or `end`.
    #
    # After a range is collapsed, the start and end points are equal.
    #
    # See also: CreateRange GetStartRange GetEndRange

    if { $direction eq "begin" } {
        $rangeId Collapse $::Word::wdCollapseStart
    } else {
        $rangeId Collapse $::Word::wdCollapseEnd
    }
}

ConfigureCaption [::Word]Top, Main, Index

Configure style of a caption type identified by its label identifier.

ConfigureCaption appId labelId chapterStyleLevel ?includeChapterNumber? ?numberStyle? ?separator?
appIdIdentifier of the Word instance.
labelIdValue of enumeration type Enum::WdCaptionLabelID. Possible values: wdCaptionEquation, wdCaptionFigure, wdCaptionTable.
chapterStyleLevel1 corresponds to Heading1, 2 corresponds to Heading2, ...
includeChapterNumberFlag indicating whether to include the chapter number. Optional, default true.
numberStyleValue of enumeration type Enum::WdCaptionNumberStyle. Optional, default wdCaptionNumberStyleArabic.
separatorValue of enumeration type Enum::WdSeparatorType. Optional, default wdSeparatorHyphen.

Returns no value.

See also: InsertCaption

proc ::Word::ConfigureCaption {appId labelId chapterStyleLevel {includeChapterNumber true} {numberStyle wdCaptionNumberStyleArabic} {separator wdSeparatorHyphen}} {

    # Configure style of a caption type identified by its label identifier.
    #
    # appId                - Identifier of the Word instance.
    # labelId              - Value of enumeration type [Enum::WdCaptionLabelID].
    #                        Possible values: `wdCaptionEquation`, `wdCaptionFigure`, `wdCaptionTable`.
    # chapterStyleLevel    - 1 corresponds to `Heading1`, 2 corresponds to `Heading2`, ...
    # includeChapterNumber - Flag indicating whether to include the chapter number.
    # numberStyle          - Value of enumeration type [Enum::WdCaptionNumberStyle].
    # separator            - Value of enumeration type [Enum::WdSeparatorType].
    #
    # Returns no value.
    #
    # See also: InsertCaption

    set captionItem [$appId -with { CaptionLabels } Item [Word GetEnum $labelId]]
    $captionItem ChapterStyleLevel    [expr $chapterStyleLevel]
    $captionItem IncludeChapterNumber [Cawt TclBool $includeChapterNumber]
    $captionItem NumberStyle          [Word GetEnum $numberStyle]
    $captionItem Separator            [Word GetEnum $separator]
}

CopyRange [::Word]Top, Main, Index

Copy the contents of a range into another range.

CopyRange fromRangeId toRangeId
fromRangeIdIdentifier of the source range.
toRangeIdIdentifier of the destination range.

Note: The contents of the destination range are overwritten.

Returns no value.

See also: CreateRange

proc ::Word::CopyRange {fromRangeId toRangeId} {

    # Copy the contents of a range into another range.
    #
    # fromRangeId - Identifier of the source range.
    # toRangeId   - Identifier of the destination range.
    #
    # **Note:**
    # The contents of the destination range are overwritten.
    #
    # Returns no value.
    #
    # See also: CreateRange

    $fromRangeId Copy
    $toRangeId Paste
}

CountWords [::Word]Top, Main, Index

Count words contained in a Word document.

CountWords docId ?args?
docIdIdentifier of the document.
argsOptions described below.
-maxlength <int>Only count words having less than maxlength characters. Default: No limit.
-minlength <int>Only count words having more than minlength characters. Default: No limit.
-shownumbers <bool>If set to false, only count words which are no numbers.
-sortmode <string>Sorting mode of output list. Default: length. Possible values: dictionary, length, increasing, decreasing.

This procedure is used in the CAWT application WordAbbrCheck to get a list of words contained in a Word document.

Returns a key-value list containing the found words and their corresponding count.

See also: ::Cawt::CountWords

proc ::Word::CountWords {docId args} {

    # Count words contained in a Word document.
    #
    # docId - Identifier of the document.
    # args  - Options described below.
    #
    # -sortmode <string>  - Sorting mode of output list.
    #                       Default: length.
    #                       Possible values: dictionary, length, increasing, decreasing.
    # -minlength <int>    - Only count words having more than minlength characters.
    #                       Default: No limit.
    # -maxlength <int>    - Only count words having less than maxlength characters.
    #                       Default: No limit.
    # -shownumbers <bool> - If set to false, only count words which are no numbers.
    #
    # This procedure is used in the CAWT application `WordAbbrCheck`
    # to get a list of words contained in a Word document.
    #
    # Returns a key-value list containing the found words and their
    # corresponding count.
    #
    # See also: ::Cawt::CountWords

    set rangeId [Word GetStartRange $docId]
    Word SetRangeStartIndex $rangeId "begin"
    Word SetRangeEndIndex   $rangeId "end"

    set docText [$rangeId Text]

    set wordCountList [Cawt CountWords $docText {*}$args]
    Cawt Destroy $rangeId
    return $wordCountList
}

CreateRange [::Word]Top, Main, Index

Create a new text range.

CreateRange docId startIndex endIndex
docIdIdentifier of the document.
startIndexThe start index of the range in characters.
endIndexThe end index of the range in characters.

Returns the identifier of the new text range.

See also: CreateRangeAfter, SelectRange, GetSelectionRange

proc ::Word::CreateRange {docId startIndex endIndex} {

    # Create a new text range.
    #
    # docId      - Identifier of the document.
    # startIndex - The start index of the range in characters.
    # endIndex   - The end index of the range in characters.
    #
    # Returns the identifier of the new text range.
    #
    # See also: CreateRangeAfter SelectRange GetSelectionRange

    return [$docId Range $startIndex $endIndex]
}

CreateRangeAfter [::Word]Top, Main, Index

Create a new text range after specified range.

CreateRangeAfter rangeId
rangeIdIdentifier of the text range.

Returns the identifier of the new text range.

See also: CreateRange, SelectRange, GetSelectionRange

proc ::Word::CreateRangeAfter {rangeId} {

    # Create a new text range after specified range.
    #
    # rangeId - Identifier of the text range.
    #
    # Returns the identifier of the new text range.
    #
    # See also: CreateRange SelectRange GetSelectionRange

    set docId [Word GetDocumentId $rangeId]
    set index [Word GetRangeEndIndex $rangeId]
    set rangeId [Word CreateRange $docId $index $index]
    Cawt Destroy $docId
    return $rangeId
}

CropImage [::Word]Top, Main, Index

Crop an image at the four borders.

CropImage shapeId ?cropBottom? ?cropTop? ?cropLeft? ?cropRight?
shapeIdIdentifier of the image InlineShape.
cropBottomCrop amount at the bottom border. Optional, default 0.0.
cropTopCrop amount at the top border. Optional, default 0.0.
cropLeftCrop amount at the left border. Optional, default 0.0.
cropRightCrop amount at the right border. Optional, default 0.0.

The crop values may be specified in a format acceptable by procedure ::Cawt::ValueToPoints, i.e. centimeters, inches or points.

See GetImageList for a description of InlineShapes and Shapes.

Returns no value.

See also: GetNumImages, InsertImage, ScaleImage

proc ::Word::CropImage {shapeId {cropBottom 0.0} {cropTop 0.0} {cropLeft 0.0} {cropRight 0.0}} {

    # Crop an image at the four borders.
    #
    # shapeId    - Identifier of the image InlineShape.
    # cropBottom - Crop amount at the bottom border.
    # cropTop    - Crop amount at the top border.
    # cropLeft   - Crop amount at the left border.
    # cropRight  - Crop amount at the right border.
    #
    # The crop values may be specified in a format acceptable by
    # procedure [::Cawt::ValueToPoints], i.e. centimeters, inches or points.
    #
    # Returns no value.
    #
    # See [GetImageList] for a description of InlineShapes and Shapes.
    #
    # See also: GetNumImages InsertImage ScaleImage

    $shapeId -with { PictureFormat } CropBottom [Cawt ValueToPoints $cropBottom]
    $shapeId -with { PictureFormat } CropTop    [Cawt ValueToPoints $cropTop]
    $shapeId -with { PictureFormat } CropLeft   [Cawt ValueToPoints $cropLeft]
    $shapeId -with { PictureFormat } CropRight  [Cawt ValueToPoints $cropRight]
}

DeleteRow [::Word]Top, Main, Index

Delete a row of a table.

DeleteRow tableId ?row?
tableIdIdentifier of the Word table.
rowRow number. Row numbering starts with 1. If not specified or end, the last row is deleted. Optional, default end.

Returns no value.

See also: AddRow, GetNumRows

proc ::Word::DeleteRow {tableId {row end}} {

    # Delete a row of a table.
    #
    # tableId - Identifier of the Word table.
    # row     - Row number. Row numbering starts with 1.
    #           If not specified or `end`, the last row
    #           is deleted.
    #
    # Returns no value.
    #
    # See also: AddRow GetNumRows

    if { $row eq "end" } {
        set row [Word GetNumRows $tableId]
    } else {
        if { $row < 1 || $row > [Word GetNumRows $tableId] } {
            error "DeleteRow: Invalid row number $row given."
        }
    }
    Cawt PushComObjects
    set rowsId [$tableId Rows]
    set rowId  [$tableId -with { Rows } Item $row]
    $rowId Delete
    Cawt PopComObjects
}

DeleteSubdocumentLinks [::Word]Top, Main, Index

Delete all subdocument links from a Word document.

DeleteSubdocumentLinks docId
docIdIdentifier of the document.

Returns no value.

See also: GetNumSubdocuments, GetSubdocumentPath, ExpandSubdocuments

proc ::Word::DeleteSubdocumentLinks {docId} {

    # Delete all subdocument links from a Word document.
    #
    # docId - Identifier of the document.
    #
    # Returns no value.
    #
    # See also: GetNumSubdocuments GetSubdocumentPath ExpandSubdocuments

    variable wordVersion

    if { $wordVersion < 14.0 } {
        error "DeleteSubdocumentLinks available only in Word 2010 or newer. Running [Word GetVersion $docId true]."
    }

    $docId -with { Subdocuments } Delete
}

DeleteTable [::Word]Top, Main, Index

Delete a table.

DeleteTable tableId
tableIdIdentifier of the Word table.

Returns no value.

See also: AddTable, GetNumTables

proc ::Word::DeleteTable {tableId} {

    # Delete a table.
    #
    # tableId - Identifier of the Word table.
    #
    # Returns no value.
    #
    # See also: AddTable GetNumTables

    $tableId Delete
}

DiffWordFiles [::Word]Top, Main, Index

Compare two Word files visually.

DiffWordFiles wordBaseFile wordNewFile
wordBaseFileName of the base Word file.
wordNewFileName of the new Word file.

The two files are opened in Word's compare mode.

Returns the identifier of the new Word application instance.

See also: OpenNew

proc ::Word::DiffWordFiles {wordBaseFile wordNewFile} {

    # Compare two Word files visually.
    #
    # wordBaseFile - Name of the base Word file.
    # wordNewFile  - Name of the new Word file.
    #
    # The two files are opened in Word's compare mode.
    #
    # Returns the identifier of the new Word application instance.
    #
    # See also: OpenNew

    variable wordVersion

    if { ! [file exists $wordBaseFile] } {
        error "Diff: Base file $wordBaseFile does not exists"
    }
    if { ! [file exists $wordNewFile] } {
        error "Diff: New file $wordNewFile does not exists"
    }
    if { [file normalize $wordBaseFile] eq [file normalize $wordNewFile] } {
        error "Diff: Base and new file are equal. Cannot compare."
    }

    set appId [Word OpenNew true]

    if { $wordVersion >= 12.0 } {
        # From Word 2007 and up, change order of files.
        set tmpFile $wordBaseFile
        set wordBaseFile $wordNewFile
        set wordNewFile $tmpFile
    }

    set newDocId [Word OpenDocument $appId $wordNewFile -readonly true]
    $newDocId -with { ActiveWindow View } Type $Word::wdNormalView

    $newDocId Compare [file nativename [file normalize $wordBaseFile]]  "CawtDiff" $Word::wdCompareTargetNew true true

    $appId -with { ActiveDocument } Saved [Cawt TclBool true]
    Word Close $newDocId

    return $appId
}

ExpandSubdocuments [::Word]Top, Main, Index

Expand all subdocuments in a Word document.

ExpandSubdocuments docId ?onOff?
docIdIdentifier of the document.
onOffSwitch expansion on or off. Optional, default true.

Returns no value.

See also: GetNumSubdocuments, GetSubdocumentPath, DeleteSubdocumentLinks

proc ::Word::ExpandSubdocuments {docId {onOff true}} {

    # Expand all subdocuments in a Word document.
    #
    # docId - Identifier of the document.
    # onOff - Switch expansion on or off.
    #
    # Returns no value.
    #
    # See also: GetNumSubdocuments GetSubdocumentPath DeleteSubdocumentLinks

    variable wordVersion

    if { $wordVersion < 14.0 } {
        error "ExpandSubdocuments available only in Word 2010 or newer. Running [Word GetVersion $docId true]."
    }

    $docId -with { ActiveWindow ActivePane View } Type $::Word::wdOutlineView
    $docId -with { Subdocuments } Expanded [Cawt TclBool $onOff]
}

ExtendRange [::Word]Top, Main, Index

Extend the range indices of a text range.

ExtendRange rangeId ?startIncr? ?endIncr?
rangeIdIdentifier of the text range.
startIncrIncrement of the range start index. Optional, default 0.
endIncrIncrement of the range end index. Optional, default 0.

Increment is either an integer value or strings begin or end to use the start or end of the document.

Returns the new extended range.

See also: SetRangeStartIndex, SetRangeEndIndex

proc ::Word::ExtendRange {rangeId {startIncr 0} {endIncr 0}} {

    # Extend the range indices of a text range.
    #
    # rangeId   - Identifier of the text range.
    # startIncr - Increment of the range start index.
    # endIncr   - Increment of the range end index.
    #
    # Increment is either an integer value or strings `begin` or `end` to
    # use the start or end of the document.
    #
    # Returns the new extended range.
    #
    # See also: SetRangeStartIndex SetRangeEndIndex

    set startIndex [Word GetRangeStartIndex $rangeId]
    set endIndex   [Word GetRangeEndIndex   $rangeId]
    if { [string is integer $startIncr] } {
        set startIndex [expr $startIndex + $startIncr]
    } elseif { $startIncr eq "begin" } {
        set startIndex 0
    }
    if { [string is integer $endIncr] } {
        set endIndex [expr $endIndex + $endIncr]
    } elseif { $endIncr eq "end" } {
        set docId [Word GetDocumentId $rangeId]
        set endRange [GetEndRange $docId]
        set endIndex [$endRange End]
        Cawt Destroy $endRange
        Cawt Destroy $docId
    }
    $rangeId Start $startIndex
    $rangeId End $endIndex
    return $rangeId
}

FindString [::Word]Top, Main, Index

Find a string in a text range or a document.

FindString rangeOrDocId searchStr ?matchCase? ?matchWildcards?
rangeOrDocIdIdentifier of a text range or a document identifier.
searchStrSearch string.
matchCaseFlag indicating case sensitive search. Optional, default true.
matchWildcardsFlag indicating wildcard search. Optional, default false.

Returns zero, if string could not be found. Otherwise a positive integer. If the string was found, the selection is set to the found string.

See also: ReplaceString, ReplaceByProc, Search, GetSelectionRange

proc ::Word::FindString {rangeOrDocId searchStr {matchCase true} {matchWildcards false}} {

    # Find a string in a text range or a document.
    #
    # rangeOrDocId   - Identifier of a text range or a document identifier.
    # searchStr      - Search string.
    # matchCase      - Flag indicating case sensitive search.
    # matchWildcards - Flag indicating wildcard search.
    #
    # Returns zero, if string could not be found. Otherwise a positive integer.
    # If the string was found, the selection is set to the found string.
    #
    # See also: ReplaceString ReplaceByProc Search GetSelectionRange

    return [Word::Search $rangeOrDocId $searchStr  -matchcase $matchCase -matchwildcards $matchWildcards  -wrap $Word::wdFindStop -forward true]
}

FormatHeaderRow [::Word]Top, Main, Index

Format a row as a header row.

FormatHeaderRow tableId row startCol endCol
tableIdIdentifier of the Word table.
rowRow number. Row numbering starts with 1.
startColColumn number of formatting start. Column numbering starts with 1.
endColColumn number of formatting end. Column numbering starts with 1.

The cell values of a header are formatted as bold text with both vertical and horizontal centered alignment.

Returns no value.

See also: SetHeaderRow, SetHeadingFormat

proc ::Word::FormatHeaderRow {tableId row startCol endCol} {

    # Format a row as a header row.
    #
    # tableId  - Identifier of the Word table.
    # row      - Row number. Row numbering starts with 1.
    # startCol - Column number of formatting start. Column numbering starts with 1.
    # endCol   - Column number of formatting end. Column numbering starts with 1.
    #
    # The cell values of a header are formatted as bold text with both vertical and
    # horizontal centered alignment.
    #
    # Returns no value.
    #
    # See also: SetHeaderRow SetHeadingFormat

    set header [Word GetRowRange $tableId $row]
    Word SetRangeHorizontalAlignment $header $Word::wdAlignParagraphCenter
    Word SetRangeBackgroundColorByEnum $header $Word::wdColorGray25
    Word SetRangeFontBold $header
}

GetBookmarkName [::Word]Top, Main, Index

Get the name of a bookmark.

GetBookmarkName bookmarkId
bookmarkIdIdentifier of the bookmark.

Returns the name of the bookmark.

See also: AddBookmark, SetLinkToBookmark

proc ::Word::GetBookmarkName {bookmarkId} {

    # Get the name of a bookmark.
    #
    # bookmarkId - Identifier of the bookmark.
    #
    # Returns the name of the bookmark.
    #
    # See also: AddBookmark SetLinkToBookmark

    return [$bookmarkId Name]
}

GetBookmarkNames [::Word]Top, Main, Index

Get the names of all bookmarks of a document.

GetBookmarkNames docId ?args?
docIdIdentifier of the document.
argsOptions described below.
-showhidden <bool>Show hidden bookmarks. Default value is false.

Returns a list containing the names of all bookmarks of the document.

See also: AddBookmark, SetLinkToBookmark, GetHyperlinksAsDict

proc ::Word::GetBookmarkNames {docId args} {

    # Get the names of all bookmarks of a document.
    #
    # docId - Identifier of the document.
    # args  - Options described below.
    #
    # -showhidden <bool> - Show hidden bookmarks. Default value is false.
    #
    # Returns a list containing the names of all bookmarks of the document.
    #
    # See also: AddBookmark SetLinkToBookmark GetHyperlinksAsDict

    set opts [dict create  -showhidden false  ]
    foreach { key value } $args {
        if { [dict exists $opts $key] } {
            if { $value eq "" } {
                error "GetBookmarkNames: No value specified for key \"$key\""
            }
            dict set opts $key $value
        } else {
            error "GetBookmarkNames: Unknown option \"$key\" specified"
        }
    }

    set nameList [list]
    set showHidden [Cawt TclBool [dict get $opts "-showhidden"]]
    $docId -with { Bookmarks } ShowHidden $showHidden
    set bookmarks [$docId Bookmarks]
    $bookmarks -iterate bookmark {
        lappend nameList [$bookmark Name]
        Cawt Destroy $bookmark
    }
    Cawt Destroy $bookmarks
    return $nameList
}

GetCellRange [::Word]Top, Main, Index

Return a cell or cells of a Word table as a range.

GetCellRange tableId row1 col1 ?row2? ?col2?
tableIdIdentifier of the Word table.
row1Row number of upper-left corner of the cell range.
col1Column number of upper-left corner of the cell range.
row2Row number of lower-right corner of the cell range. Optional, default -1.
col2Column number of lower-right corner of the cell range. Optional, default -1.

Row and column numbering starts with 1.

Returns a range consisting of 1 cell of a Word table.

See also: GetRowRange, GetColumnRange

proc ::Word::GetCellRange {tableId row1 col1 {row2 -1} {col2 -1}} {

    # Return a cell or cells of a Word table as a range.
    #
    # tableId - Identifier of the Word table.
    # row1    - Row number of upper-left corner of the cell range.
    # col1    - Column number of upper-left corner of the cell range.
    # row2    - Row number of lower-right corner of the cell range.
    # col2    - Column number of lower-right corner of the cell range.
    #
    # Row and column numbering starts with 1.
    #
    # Returns a range consisting of 1 cell of a Word table.
    #
    # See also: GetRowRange GetColumnRange

    set cellId1  [$tableId Cell $row1 $col1]
    set rangeId1 [$cellId1 Range]
    Cawt Destroy $cellId1
    if { $row2 >= $row1 && $col2 >= $col1 } {
        set cellId2  [$tableId Cell $row2 $col2]
        set rangeId2 [$cellId2 Range]
        Word SetRangeEndIndex $rangeId1 [Word GetRangeEndIndex $rangeId2]
        Cawt Destroy $cellId2
        Cawt Destroy $rangeId2
    }
    return $rangeId1
}

GetCellValue [::Word]Top, Main, Index

Return the value of a Word table cell.

GetCellValue tableId row col
tableIdIdentifier of the Word table.
rowRow number. Row numbering starts with 1.
colColumn number. Column numbering starts with 1.

Returns the value of the specified cell as a string.

See also: SetCellValue, IsValidCell

proc ::Word::GetCellValue {tableId row col} {

    # Return the value of a Word table cell.
    #
    # tableId - Identifier of the Word table.
    # row     - Row number. Row numbering starts with 1.
    # col     - Column number. Column numbering starts with 1.
    #
    # Returns the value of the specified cell as a string.
    #
    # See also: SetCellValue IsValidCell

    set rangeId [Word GetCellRange $tableId $row $col]
    set val [Word::TrimString [$rangeId Text]]
    Cawt Destroy $rangeId
    return $val
}

GetColumnRange [::Word]Top, Main, Index

Return a column of a Word table as a selection.

GetColumnRange tableId col
tableIdIdentifier of the Word table.
colColumn number. Column numbering starts with 1.

Note: A selection is returned and not a range, because columns do not have a range property.

Returns a selection consisting of all cells of a column.

See also: GetCellRange, GetRowRange

proc ::Word::GetColumnRange {tableId col} {

    # Return a column of a Word table as a selection.
    #
    # tableId - Identifier of the Word table.
    # col     - Column number. Column numbering starts with 1.
    #
    # Returns a selection consisting of all cells of a column.
    #
    # **Note:**
    # A selection is returned and not a range,
    # because columns do not have a range property.
    #
    # See also: GetCellRange GetRowRange

    set colId [$tableId -with { Columns } Item $col]
    $colId Select
    set selectId [$tableId -with { Application } Selection]
    $selectId SelectColumn
    Cawt Destroy $colId
    return $selectId
}

GetColumnValues [::Word]Top, Main, Index

Return column values of a Word table as a Tcl list.

GetColumnValues tableId col ?startRow? ?numVals?
tableIdIdentifier of the Word table.
colColumn number. Column numbering starts with 1.
startRowRow number of start. Row numbering starts with 1. Optional, default 1.
numValsIf negative or zero, all available column values are returned. If positive, only $numVals values of the column are returned. Optional, default 0.

Returns the values of the specified column or column range as a Tcl list.

See also: SetColumnValues, GetRowValues, GetCellValue

proc ::Word::GetColumnValues {tableId col {startRow 1} {numVals 0}} {

    # Return column values of a Word table as a Tcl list.
    #
    # tableId  - Identifier of the Word table.
    # col      - Column number. Column numbering starts with 1.
    # startRow - Row number of start. Row numbering starts with 1.
    # numVals  - If negative or zero, all available column values are returned.
    #            If positive, only $numVals values of the column are returned.
    #
    # Returns the values of the specified column or column range as a Tcl list.
    #
    # See also: SetColumnValues GetRowValues GetCellValue

    if { $numVals <= 0 } {
        set len [GetNumRows $tableId]
    } else {
        set len $numVals
    }
    set valList [list]
    set row $startRow
    set ind 0
    while { $ind < $len } {
        set val [GetCellValue $tableId $row $col]
        if { $val eq "" } {
            set val2 [GetCellValue $tableId [expr {$row+1}] $col]
            if { $val2 eq "" } {
                break
            }
        }
        lappend valList $val
        incr ind
        incr row
    }
    return $valList
}

GetCompatibilityMode [::Word]Top, Main, Index

Return the compatibility version of a Word application.

GetCompatibilityMode appId ?version?
appIdIdentifier of the Word instance.
versionWord version number. Optional, default "".

Note: The compatibility mode is a value of enumeration Enum::WdCompatibilityMode.

Returns the compatibility mode of the current Word application, if version is not specified or the empty string. If version is a valid Word version as returned by GetVersion, the corresponding compatibility mode is returned.

See also: GetVersion, GetExtString

proc ::Word::GetCompatibilityMode {appId {version {}}} {

    # Return the compatibility version of a Word application.
    #
    # appId   - Identifier of the Word instance.
    # version - Word version number.
    #
    # Returns the compatibility mode of the current Word application, if
    # version is not specified or the empty string.
    # If version is a valid Word version as returned by [GetVersion], the
    # corresponding compatibility mode is returned.
    #
    # **Note:** The compatibility mode is a value of enumeration [Enum::WdCompatibilityMode].
    #
    # See also: GetVersion GetExtString

    if { $version eq "" } {
        return $Word::wdCurrent
    } else {
        array set map {
            "11.0" $Word::wdWord2003
            "12.0" $Word::wdWord2007
            "14.0" $Word::wdWord2010
            "15.0" $Word::wdWord2013
        }
        if { [info exists map($version)] } {
            return $map($version)
        } else {
            error "Unknown Word version $version"
        }
    }
}

GetCrossReferenceItems [::Word]Top, Main, Index

Get all cross reference items of a given type.

GetCrossReferenceItems docId refType
docIdIdentifier of the document.
refTypeValue of enumeration type Enum::WdReferenceType.

Returns the texts of the cross reference items as a list.

See also: GetHeadingRanges

proc ::Word::GetCrossReferenceItems {docId refType} {

    # Get all cross reference items of a given type.
    #
    # docId   - Identifier of the document.
    # refType - Value of enumeration type [Enum::WdReferenceType].
    #
    # Returns the texts of the cross reference items as a list.
    #
    # See also: GetHeadingRanges

    set pureRefList [$docId GetCrossReferenceItems [Word GetEnum $refType]]
    # The cross reference items might contain whitespaces at the left.
    set refList [list]
    foreach ref $pureRefList {
        lappend refList [Word::TrimString $ref]
    }
    return $refList
}

GetDocumentId [::Word]Top, Main, Index

Get the document identifier of a Word component.

GetDocumentId componentId
componentIdThe identifier of a Word component.

Word components having the Document property are ex. ranges, panes.

Returns the document identifier of a Word component.

See also: GetNumDocuments, GetDocumentName

proc ::Word::GetDocumentId {componentId} {

    # Get the document identifier of a Word component.
    #
    # componentId - The identifier of a Word component.
    #
    # Returns the document identifier of a Word component.
    #
    # Word components having the Document property are ex. ranges, panes.
    #
    # See also: GetNumDocuments GetDocumentName

    return [$componentId Document]
}

GetDocumentIdByIndex [::Word]Top, Main, Index

Find a document by its index.

GetDocumentIdByIndex appId index
appIdIdentifier of the Word instance.
indexIndex of the document to find.

Returns the identifier of the found document. If the index is out of bounds an error is thrown.

See also: GetNumDocuments, GetDocumentId, GetDocumentName

proc ::Word::GetDocumentIdByIndex {appId index} {

    # Find a document by its index.
    #
    # appId - Identifier of the Word instance.
    # index - Index of the document to find.
    #
    # Returns the identifier of the found document.
    # If the index is out of bounds an error is thrown.
    #
    # See also: GetNumDocuments GetDocumentId GetDocumentName

    set count [Word GetNumDocuments $appId]

    if { $index < 1 || $index > $count } {
        error "GetDocumentIdByIndex: Invalid index $index given."
    }
    return [$appId -with { Documents } Item $index]
}

GetDocumentName [::Word]Top, Main, Index

Get the name of a document.

GetDocumentName docId
docIdIdentifier of the document.

Returns the name of the document (i.e. the full path name of the corresponding Word file) as a string.

See also: GetNumDocuments, GetDocumentId

proc ::Word::GetDocumentName {docId} {

    # Get the name of a document.
    #
    # docId - Identifier of the document.
    #
    # Returns the name of the document (i.e. the full path name of the
    # corresponding Word file) as a string.
    #
    # See also: GetNumDocuments GetDocumentId

    return [$docId FullName]
}

GetEndRange [::Word]Top, Main, Index

Return the text range representing the end of the document.

GetEndRange docId
docIdIdentifier of the document.

Note: This corresponds to the built-in bookmark \endofdoc. The end range of an empty document is (0, 0), although GetNumCharacters returns 1.

Returns the text range representing the end of the document.

See also: GetSelectionRange, GetStartRange, GetNumCharacters

proc ::Word::GetEndRange {docId} {

    # Return the text range representing the end of the document.
    #
    # docId - Identifier of the document.
    #
    # **Note:**
    # This corresponds to the built-in bookmark `\endofdoc`.
    # The end range of an empty document is (0, 0), although
    # [GetNumCharacters] returns 1.
    #
    # Returns the text range representing the end of the document.
    #
    # See also: GetSelectionRange GetStartRange GetNumCharacters

    set bookMarks [$docId Bookmarks]
    set endOfDoc  [$bookMarks Item "\\endofdoc"]
    set endRange  [$endOfDoc Range]
    Cawt Destroy $endOfDoc
    Cawt Destroy $bookMarks
    set endIndex [Word GetRangeEndIndex $endRange]
    Cawt Destroy $endRange
    return [Word CreateRange $docId $endIndex $endIndex]
}

GetEnum [::Word]Top, Main, Index

Get numeric value of an enumeration.

GetEnum enumOrString
enumOrStringEnumeration name

Returns the numeric value of an enumeration.

See also: GetEnumName, GetEnumTypes, GetEnumVal, GetEnumNames

proc ::Word::GetEnum {enumOrString} {

    # Get numeric value of an enumeration.
    #
    # enumOrString - Enumeration name
    #
    # Returns the numeric value of an enumeration.
    #
    # See also: GetEnumName GetEnumTypes GetEnumVal GetEnumNames

    set retVal [catch { expr int($enumOrString) } enumInt]
    if { $retVal == 0 } {
        return $enumInt
    } else {
        return [GetEnumVal $enumOrString]
    }
}

GetEnumName [::Word]Top, Main, Index

Get name of a given enumeration type and numeric value.

GetEnumName enumType enumVal
enumTypeEnumeration type
enumValEnumeration numeric value.

Returns the list of names of a given enumeration type.

See also: GetEnumNames, GetEnumTypes, GetEnumVal, GetEnum

proc ::Word::GetEnumName {enumType enumVal} {

    # Get name of a given enumeration type and numeric value.
    #
    # enumType - Enumeration type
    # enumVal  - Enumeration numeric value.
    #
    # Returns the list of names of a given enumeration type.
    #
    # See also: GetEnumNames GetEnumTypes GetEnumVal GetEnum

    variable enums

    set enumName ""
    if { [info exists enums($enumType)] } {
        foreach { key val } $enums($enumType) {
            if { $val eq $enumVal } {
                set enumName $key
                break
            }
        }
    }
    return $enumName
}

GetEnumNames [::Word]Top, Main, Index

Get names of a given enumeration type.

GetEnumNames enumType
enumTypeEnumeration type

Returns the list of names of a given enumeration type.

See also: GetEnumName, GetEnumTypes, GetEnumVal, GetEnum

proc ::Word::GetEnumNames {enumType} {

    # Get names of a given enumeration type.
    #
    # enumType - Enumeration type
    #
    # Returns the list of names of a given enumeration type.
    #
    # See also: GetEnumName GetEnumTypes GetEnumVal GetEnum

    variable enums

    if { [info exists enums($enumType)] } {
        foreach { key val } $enums($enumType) {
            lappend nameList $key
        }
        return $nameList
    } else {
        return [list]
    }
}

GetEnumTypes [::Word]Top, Main, Index

Get available enumeration types.

GetEnumTypes

Returns the list of available enumeration types.

See also: GetEnumName, GetEnumNames, GetEnumVal, GetEnum

proc ::Word::GetEnumTypes {} {

    # Get available enumeration types.
    #
    # Returns the list of available enumeration types.
    #
    # See also: GetEnumName GetEnumNames GetEnumVal GetEnum

    variable enums

    return [lsort -dictionary [array names enums]]
}

GetEnumVal [::Word]Top, Main, Index

Get numeric value of an enumeration name.

GetEnumVal enumName
enumNameEnumeration name

Returns the numeric value of an enumeration name.

See also: GetEnumName, GetEnumTypes, GetEnumNames, GetEnum

proc ::Word::GetEnumVal {enumName} {

    # Get numeric value of an enumeration name.
    #
    # enumName - Enumeration name
    #
    # Returns the numeric value of an enumeration name.
    #
    # See also: GetEnumName GetEnumTypes GetEnumNames GetEnum

    variable enums

    foreach enumType [GetEnumTypes] {
        set ind [lsearch -exact $enums($enumType) $enumName]
        if { $ind >= 0 } {
            return [lindex $enums($enumType) [expr { $ind + 1 }]]
        }
    }
    return ""
}

GetExtString [::Word]Top, Main, Index

Return the default extension of a Word file.

GetExtString appId
appIdIdentifier of the Word instance.

Starting with Word 12 (2007) this is the string .docx. In previous versions it was .doc.

Returns the default extension of a Word file.

See also: GetCompatibilityMode, GetVersion, ::Office::GetOfficeType

proc ::Word::GetExtString {appId} {

    # Return the default extension of a Word file.
    #
    # appId - Identifier of the Word instance.
    #
    # Starting with Word 12 (2007) this is the string `.docx`.
    # In previous versions it was `.doc`.
    #
    # Returns the default extension of a Word file.
    #
    # See also: GetCompatibilityMode GetVersion ::Office::GetOfficeType

    # appId is only needed, so we are sure, that wordVersion is initialized.

    variable wordVersion

    if { $wordVersion >= 12.0 } {
        return ".docx"
    } else {
        return ".doc"
    }
}

GetFooterText [::Word]Top, Main, Index

Get the text of the document footer.

GetFooterText docId ?type?
docIdIdentifier of the document.
typeValue of enumeration type Enum::WdHeaderFooterIndex. Optional, default $Word::wdHeaderFooterPrimary.

Returns the footer text.

See also: GetHeaderText

proc ::Word::GetFooterText {docId {type {$Word::wdHeaderFooterPrimary}}} {

    # Get the text of the document footer.
    #
    # docId - Identifier of the document.
    # type  - Value of enumeration type [Enum::WdHeaderFooterIndex].
    #
    # Returns the footer text.
    #
    # See also: GetHeaderText

    set footerType [Word GetEnum $type]
    set sections [$docId Sections]
    $sections -iterate section {
        set footers [$section Footers]
        set footer  [$footers Item $footerType]
        set text    [$footer -with { Range } Text]
        Cawt Destroy $footer
        Cawt Destroy $footers
        break
    }
    Cawt Destroy $sections
    return  [Word::TrimString $text]
}

GetHeaderText [::Word]Top, Main, Index

Get the text of the document header.

GetHeaderText docId ?type?
docIdIdentifier of the document.
typeValue of enumeration type Enum::WdHeaderFooterIndex. Optional, default $Word::wdHeaderFooterPrimary.

Returns the header text.

See also: GetFooterText

proc ::Word::GetHeaderText {docId {type {$Word::wdHeaderFooterPrimary}}} {

    # Get the text of the document header.
    #
    # docId - Identifier of the document.
    # type  - Value of enumeration type [Enum::WdHeaderFooterIndex].
    #
    # Returns the header text.
    #
    # See also: GetFooterText

    set headerType [Word GetEnum $type]
    set sections [$docId Sections]
    $sections -iterate section {
        set headers [$section Headers]
        set header  [$headers Item $headerType]
        set text    [$header -with { Range } Text]
        Cawt Destroy $header
        Cawt Destroy $headers
        break
    }
    Cawt Destroy $sections
    return  [Word::TrimString $text]
}

GetHeadingRanges [::Word]Top, Main, Index

Get the ranges of a specific heading level.

GetHeadingRanges docId level
docIdIdentifier of the document.
levelLevel(s) to retrieve. The level(s) can be specified in the following ways:
Value of enumeration type Enum::WdOutlineLevel.
A list of integer numbers between 1 and 9.
Keyword all to get all levels.

Returns the ranges and the corresponding level index of the specified heading levels as a Tcl list.

See also: GetCrossReferenceItems, GetHeadingsAsDict

proc ::Word::GetHeadingRanges {docId level} {

    # Get the ranges of a specific heading level.
    #
    # docId - Identifier of the document.
    # level - Level(s) to retrieve.
    #         The level(s) can be specified in the following ways:<br/>
    #         Value of enumeration type [Enum::WdOutlineLevel].<br/>
    #         A list of integer numbers between 1 and 9.<br/>
    #         Keyword `all` to get all levels.<br/>
    #
    # Returns the ranges and the corresponding level index
    # of the specified heading levels as a Tcl list.
    #
    # See also: GetCrossReferenceItems GetHeadingsAsDict

    set searchLevelList [list]
    if { $level eq "all" } {
        set searchLevelList [list 1 2 3 4 5 6 7 8 9]
    } else {
        set enumVal [Word GetEnum $level]
        if { $enumVal ne "" } {
            set searchLevelList [list $enumVal]
        } else {
            foreach lev $level {
                lappend searchLevelList $lev
            }
        }
    }

    set rangeIdList    [list]
    set tmpRangeIdList [list]
    set headingRangeId [Word GetStartRange $docId]
    while { true } {
        set currentIndex [Word GetRangeStartIndex $headingRangeId]
        set headingRangeId [$headingRangeId GoTo $::Word::wdGoToHeading $::Word::wdGoToNext]
        if { [Word GetRangeStartIndex $headingRangeId] == $currentIndex } {
            # We haven't moved, so there are no more headings.
            Cawt Destroy $headingRangeId
            break
        }
        set paragraphId [$headingRangeId -with { Paragraphs } Item 1]
        set foundLevel [$paragraphId OutlineLevel]
        Cawt Destroy $paragraphId
        if { [lsearch -exact -integer $searchLevelList $foundLevel] >= 0 } {
            $headingRangeId Expand $::Word::wdParagraph
            lappend rangeIdList $headingRangeId
            lappend rangeIdList $foundLevel
        } else {
            lappend tmpRangeIdList $headingRangeId
        }
    }
    foreach rangeId $tmpRangeIdList {
        Cawt Destroy $rangeId
    }
    return $rangeIdList
}

GetHeadingsAsDict [::Word]Top, Main, Index

Get a dictionary with headings of a document.

GetHeadingsAsDict docId ?args?
docIdIdentifier of the document.
argsNumbers between 1 and 9 specifying the heading levels to be retrieved. If empty, all heading levels from 1 to 9 are returned.

The dictionary is structured as follows:

Key:    Heading number
Values: text level start end

Note:

Returns a dictionary containing the headings matching the specified level criterias.

See also: GetHeadingRanges, GetHyperlinksAsDict, PrintHeadingDict, GetBookmarkNames

proc ::Word::GetHeadingsAsDict {docId args} {

    # Get a dictionary with headings of a document.
    #
    # docId - Identifier of the document.
    # args  - Numbers between 1 and 9 specifying the heading levels to be retrieved.
    #         If empty, all heading levels from 1 to 9 are returned.
    #
    # Returns a dictionary containing the headings matching the specified
    # level criterias.
    #
    # The dictionary is structured as follows:
    #     Key:    Heading number
    #     Values: text level start end
    #
    # * `Key` is a unique heading number formatted as "%06d" integer.
    # * `text` stores the heading text.
    # * `level` stores the heading level.
    # * `start` stores the numerical start range of the heading.
    # * `end` stores the numerical end range of the heading.
    #
    # Note:
    #  * This procedure can be called as a coroutine. It yields
    #    every 10 headings processed. The yield return value
    #    is the number of headings already processed.
    #
    # See also: GetHeadingRanges GetHyperlinksAsDict PrintHeadingDict GetBookmarkNames

    set levelList [list]
    if { [llength $args] == 0 } {
        set levelList [list 1 2 3 4 5 6 7 8 9]
    } else {
        foreach level $args {
            lappend levelList $level
        }
    }

    if { [info coroutine] ne "" } {
        yield 0
    }

    Cawt PushComObjects

    set countAdded 1
    set curHeadingNum 0
    set headingDict [dict create]

    foreach level $levelList {
        set styleName [format "wdStyleHeading%d" $level]

        set rangeId [Word GetStartRange $docId]
        set rangeId [Word ExtendRange $rangeId 0 end]

        while { 1 } {
            set myFind [$rangeId Find]
            $myFind Style [Word GetEnum $styleName]
            set retVal [$myFind -callnamedargs Execute Forward True]
            if { ! $retVal } {
                break
            }
            set startRange [Word GetRangeStartIndex $rangeId]
            set endRange   [Word GetRangeEndIndex   $rangeId]
            set rangeText  [Word GetRangeText       $rangeId]

            set key [format "%06d" $countAdded]
            dict set headingDict $key text       $rangeText
            dict set headingDict $key level      $level
            dict set headingDict $key start      $startRange
            dict set headingDict $key end        $endRange
            incr countAdded

            Word CollapseRange $rangeId end

            incr curHeadingNum
            if { $curHeadingNum % 10 == 0 } {
                if { [info coroutine] ne "" } {
                    yield $curHeadingNum
                }
            }
        }
    }

    if { [info coroutine] ne "" } {
        yield $curHeadingNum
    }
    Cawt PopComObjects
    return $headingDict
}

GetHyperlinksAsDict [::Word]Top, Main, Index

Get a dictionary with hyperlinks of a document.

GetHyperlinksAsDict docId ?args?
docIdIdentifier of the document.
argsOptions described below.
-check <bool>Check hyperlinks for validity. Default: No check.
-file <string>If checking is enabled, the full path of the Word document. This option is only needed when checking relative file links and the document is not saved yet. If not specified, Word property FullName is used for checking relative file links. If the property is not set, the current working directory is used.
-type <string>Consider only hyperlinks of specified type. Possible values: internal, file, url. This option may be specified multiple times. If this option is not specified, all hyperlinks are returned.
-valid <bool>If checking is enabled, return either valid or invalid links. Default: Return all matching hyperlinks.

The dictionary is structured as follows:

Key:    Hyperlink number
Values: address text type start end valid

Note:

Returns a dictionary containing the hyperlinks matching the search criterias.

See also: SetHyperlink, SetLinkToBookmark, PrintHyperlinkDict, GetBookmarkNames, GetNumHyperlinks, ::Cawt::IsValidUrlAddress

proc ::Word::GetHyperlinksAsDict {docId args} {

    # Get a dictionary with hyperlinks of a document.
    #
    # docId - Identifier of the document.
    # args  - Options described below.
    #
    # -type <string> - Consider only hyperlinks of specified type.
    #                  Possible values: `internal`, `file`, `url`.
    #                  This option may be specified multiple times.
    #                  If this option is not specified, all hyperlinks
    #                  are returned.
    # -check <bool>  - Check hyperlinks for validity. Default: No check.
    # -valid <bool>  - If checking is enabled, return either valid or invalid links.
    #                  Default: Return all matching hyperlinks.
    # -file <string> - If checking is enabled, the full path of the Word document.
    #                  This option is only needed when checking relative
    #                  file links and the document is not saved yet.
    #                  If not specified, Word property `FullName` is used for
    #                  checking relative file links. If the property is
    #                  not set, the current working directory is used.
    #
    # Returns a dictionary containing the hyperlinks matching the search
    # criterias.
    #
    # The dictionary is structured as follows:
    #     Key:    Hyperlink number
    #     Values: address text type start end valid
    #
    # * `Key` is the link number formatted as "%06d" integer.
    # * `address` stores the address the link points to.
    # * `subaddress` stores the sub address the link points to.
    # * `text` stores the text displayed for the link.
    # * `type` stores the type of the link (`internal`, `file`, `url`).
    # * `start` stores the numerical start range of the link.
    # * `end` stores the numerical end range of the link.
    # * `valid` stores the validity of the link.
    #    0 for invalid link.
    #    1 for valid link.
    #    -1 if the validity was not checked.
    #
    # Note:
    #  * This procedure can be called as a coroutine. It yields
    #    every 10 hyperlinks processed. The yield return value
    #    is the number of hyperlinks already processed.
    #
    # See also: SetHyperlink SetLinkToBookmark PrintHyperlinkDict GetBookmarkNames
    # GetNumHyperlinks ::Cawt::IsValidUrlAddress

    set useTypeList   [list]
    set checkLinks    false
    set useValidMode  -1
    set wordFileName  ""

    foreach { key value } $args {
        if { $value eq "" } {
            error "GetHyperlinksAsDict: No value specified for key \"$key\""
        }
        switch -exact -nocase -- $key {
            "-type"  { lappend useTypeList $value }
            "-check" { set checkLinks      $value }
            "-valid" { if { $value } {
                           set useValidMode 1
                       } else {
                           set useValidMode 0
                       }
                     }
            "-file"  { set wordFileName $value }
            default  { error "GetHyperlinksAsDict: Unknown option \"$key\" specified" }
        }
    }
    if { [llength $useTypeList] == 0 } {
        set useTypeList [list "internal" "file" "url"]
    }

    # Need to set the display of field codes off. (Alt-F9).
    # Otherwise the displayed text is not retrieved correctly.
    set fieldCodeFlag [$docId -with { ActiveWindow ActivePane View } ShowFieldCodes]
    $docId -with { ActiveWindow ActivePane View } ShowFieldCodes [Cawt TclBool false]

    if { [info coroutine] ne "" } {
        yield 0
    }

    set bookmarkList [list]
    if { $checkLinks } {
        if { [lsearch -exact $useTypeList "url"] >= 0 } {
            # Needed to check http and https links.
            package require http
            http::register https 443 [list ::twapi::tls_socket]
        }

        if { [lsearch -exact $useTypeList "internal"] >= 0 } {
            set bookmarkList [lsort -dictionary [Word GetBookmarkNames $docId -showhidden true]]
        }
    }

    set hyperlinks [$docId Hyperlinks]
    set countAdded 1
    set curLinkNum 0
    set linkDict [dict create]
    set numLinks [Word::GetNumHyperlinks $docId]

    # Using "$hyperlinks -iterate hyperlink" instead of
    # the for loop throws an error when running as a coroutine:
    # cannot yield: C stack busy
    for { set i 1 } { $i <= $numLinks } { incr i } {
        set hyperlink [$hyperlinks Item $i]
        set address    [$hyperlink Address]
        set subAddress [$hyperlink SubAddress]
        if { $address eq "" } {
            set address $subAddress
            set type "internal"
        } else {
            if { [string first "http" $address] == 0 } {
                set type "url"
            } else {
                set type "file"
            }
        }
        if { [lsearch -exact $useTypeList $type] >= 0 } {
            if { $checkLinks } {
                set addLink false
                set valid   0
                if { $type eq "internal" } {
                    if { [lsearch -exact $bookmarkList $address] >= 0 } {
                        set valid 1
                    }
                    if { ( $useValidMode == -1 ) ||  ( $valid == 1 && $useValidMode == 1 ) ||  ( $valid == 0 && $useValidMode == 0 ) } {
                        set addLink true
                    }
                } elseif { $type eq "file" } {
                    set fileName $address
                    if { [file pathtype $address] eq "relative" } {
                        if { $wordFileName eq "" } {
                            set fullName [$docId FullName]
                            if { [file exists $fullName] } {
                                set path [file dirname $fullName]
                            } else {
                                set path [pwd]
                            }
                        } else {
                            set path [file dirname $wordFileName]
                        }
                        set fileName [file join $path $address]
                    }
                    if { [file exists $fileName] } {
                        set valid 1
                    }
                    if { ( $useValidMode == -1 ) ||  ( $valid == 1 && $useValidMode == 1 ) ||  ( $valid == 0 && $useValidMode == 0 ) } {
                        set addLink true
                    }
                } elseif { $type eq "url" } {
                    set foundInCache false
                    if { $subAddress eq "" } {
                        set catchVal [catch {  http::geturl $address -validate true -strict false } token]
                    } else {
                        if { [info exists sUrlCache($address,$subAddress)] } {
                            set foundInCache true
                            set catchVal 0
                        } else {
                            set catchVal [catch { http::geturl $address } token]
                            if { $catchVal == 0 } {
                                set htmlData [http::data $token]
                                # Search for <a name="subAddress"> occurences.
                                set exp {<[\s]*a[\s]+name=([^\s>]+)[\s]*>}
                                set matchList [regexp -all -inline -nocase -- $exp $htmlData]
                                set catchVal 1
                                foreach { overall match } $matchList {
                                    set matchStr [string trim $match "\"\'"]
                                    set sUrlCache($address,$matchStr) 1
                                    if { $matchStr eq $subAddress } {
                                        set catchVal 0
                                    }
                                }
                            }
                        }
                    }
                    if { $catchVal != 0 } {
                        set valid 0
                        if { ( $useValidMode == -1 ) ||  ( $valid == 1 && $useValidMode == 1 ) ||  ( $valid == 0 && $useValidMode == 0 ) } {
                            set addLink true
                        }
                    } else {
                        if { $foundInCache || [http::ncode $token] < 400 } {
                            set valid 1
                        }
                        if { ( $useValidMode == -1 ) ||  ( $valid == 1 && $useValidMode == 1 ) ||  ( $valid == 0 && $useValidMode == 0 ) } {
                            set addLink true
                        }
                    }
                    if { ! $foundInCache } {
                        http::cleanup $token
                    }
                }
            } else {
                set valid   -1
                set addLink true
            }

            if { $addLink } {
                set text    [$hyperlink TextToDisplay]
                set rangeId [$hyperlink Range]
                set startRange [Word GetRangeStartIndex $rangeId]
                set endRange   [Word GetRangeEndIndex $rangeId]
                if { $text eq "" } {
                    set text [$rangeId Text]
                }
                Cawt Destroy $rangeId

                set key [format "%06d" $countAdded]
                dict set linkDict $key address    $address
                dict set linkDict $key subaddress $subAddress
                dict set linkDict $key text       $text
                dict set linkDict $key type       $type
                dict set linkDict $key start      $startRange
                dict set linkDict $key end        $endRange
                dict set linkDict $key valid      $valid
                incr countAdded
            }
        }
        Cawt Destroy $hyperlink
        incr curLinkNum
        if { $curLinkNum % 10 == 0 } {
            if { [info coroutine] ne "" } {
                yield $curLinkNum
            }
        }
    }

    $docId -with { ActiveWindow ActivePane View } ShowFieldCodes $fieldCodeFlag
    Cawt Destroy $hyperlinks

    if { [info coroutine] ne "" } {
        yield $numLinks
    }

    return $linkDict
}

GetImageId [::Word]Top, Main, Index

Find an image by its index or name.

GetImageId docId indexOrName
docIdIdentifier of the document.
indexOrNameIndex or name of the image to find.

Image names are supported since Word 2010. If your Word version is older, an error is thrown.

If the index is out of bounds or the specified name does not exists, an error is thrown.

See GetImageList for a description of InlineShapes and Shapes.

Returns the identifier of the found InlineShape.

See also: GetNumImages, GetImageList, InsertImage, ReplaceImage, SetImageName

proc ::Word::GetImageId {docId indexOrName} {

    # Find an image by its index or name.
    #
    # docId       - Identifier of the document.
    # indexOrName - Index or name of the image to find.
    #
    # Returns the identifier of the found InlineShape.
    #
    # Image names are supported since Word 2010.
    # If your Word version is older, an error is thrown.
    #
    # If the index is out of bounds or the specified name
    # does not exists, an error is thrown.
    #
    # See [GetImageList] for a description of InlineShapes and Shapes.
    #
    # See also: GetNumImages GetImageList InsertImage ReplaceImage SetImageName

    variable wordVersion

    set count [Word::GetNumImages $docId]

    if { [string is integer -strict $indexOrName] } {
        set index [expr int($indexOrName)]
        if { $index < 1 || $index > $count } {
            error "GetImageId: Invalid index $index given."
        }
        return [$docId -with { InlineShapes } Item $index]
    } else {
        if { $wordVersion < 14.0 } {
            error "Image names available only in Word 2010 or newer. Running [Word GetVersion $docId true]."
        }
        for { set i 1 } { $i <= $count } { incr i } {
            set imgId [$docId -with { InlineShapes } Item $i]
            if { [Word::GetImageName $imgId] eq $indexOrName } {
                return $imgId
            }
            Cawt Destroy $imgId
        }
        error "GetImageId: No image with name \"$indexOrName\" found."
    }
}

GetImageList [::Word]Top, Main, Index

Get a list of images of a Word document.

GetImageList docId ?args?
docIdIdentifier of the document.
argsOptions described below.
-inlineshapes <bool>Consider InlineShapes as images. Default value is true.
-shapes <bool>Consider Shapes as images. Default value is true.

Note: If both InlineShapes and Shapes are returned in one list, all InlineShapes come first, followed by the Shapes.

Images are either InlineShapes of enumeration Enum::WdInlineShapeType (wdInlineShapePicture, wdInlineShapeLinkedPicture) or Shapes of enumeration ::Office::Enum::MsoShapeType (msoInlinePicture, msoLinkedPicture).

Returns a list of shape identifiers of the images of the Word document.

See also: GetNumImages, InsertImage, ReplaceImage, GetImageId, SetImageName

proc ::Word::GetImageList {docId args} {

    # Get a list of images of a Word document.
    #
    # docId - Identifier of the document.
    # args  - Options described below.
    #
    # -inlineshapes <bool> - Consider InlineShapes as images. Default value is true.
    # -shapes <bool>       - Consider Shapes as images. Default value is true.
    #
    # Returns a list of shape identifiers of the images of the Word document.
    #
    # **Note:**
    # If both InlineShapes and Shapes are returned in one list,
    # all InlineShapes come first, followed by the Shapes.
    #
    # Images are either InlineShapes of enumeration [Enum::WdInlineShapeType]
    # (`wdInlineShapePicture`, `wdInlineShapeLinkedPicture`) or Shapes of
    # enumeration [::Office::Enum::MsoShapeType] (`msoInlinePicture`, `msoLinkedPicture`).
    #
    # See also: GetNumImages InsertImage ReplaceImage GetImageId SetImageName

    set opts [dict create  -inlineshapes true  -shapes       true  ]
    foreach { key value } $args {
        if { $value eq "" } {
            error "GetImageList: No value specified for key \"$key\""
        }
        if { [dict exists $opts $key] } {
            dict set opts $key $value
        } else {
            error "GetImageList: Unknown option \"$key\" specified"
        }
    }
    set imgIdList [list]

    if { [dict get $opts "-inlineshapes"] } {
        set inlineShapes [$docId InlineShapes]
        $inlineShapes -iterate inlineShape {
            if { [$inlineShape Type] == $::Word::wdInlineShapeLinkedPicture ||  [$inlineShape Type] == $::Word::wdInlineShapePicture } {
                lappend imgIdList $inlineShape
            } else {
                Cawt Destroy $inlineShape
            }
        }
        Cawt Destroy $inlineShapes
    }

    if { [dict get $opts "-shapes"] } {
        set shapes [$docId Shapes]
        $shapes -iterate shape {
            if { [$shape Type] == $::Office::msoPicture ||  [$shape Type] == $::Office::msoLinkedPicture } {
                lappend imgIdList $shape
            } else {
                Cawt Destroy $shape
            }
        }
        Cawt Destroy $shapes
    }
    return $imgIdList
}

GetImageName [::Word]Top, Main, Index

Return the name of an image.

GetImageName shapeId
shapeIdIdentifier of the image InlineShape or Shape.

Image names are supported since Word 2010. If your Word version is older, an error is thrown.

See GetImageList for a description of InlineShapes and Shapes.

Returns the name of the image.

See also: GetNumImages, SetImageName, InsertImage, GetImageId, GetImageList

proc ::Word::GetImageName {shapeId} {

    # Return the name of an image.
    #
    # shapeId - Identifier of the image InlineShape or Shape.
    #
    # Image names are supported since Word 2010.
    # If your Word version is older, an error is thrown.
    #
    # See [GetImageList] for a description of InlineShapes and Shapes.
    #
    # Returns the name of the image.
    #
    # See also: GetNumImages SetImageName InsertImage GetImageId GetImageList

    variable wordVersion

    if { $wordVersion < 14.0 } {
        error "Image names available only in Word 2010 or newer. Running [Word GetVersion $shapeId true]."
    }
    return [$shapeId Title]
}

GetListGalleryId [::Word]Top, Main, Index

Get one of the 3 predefined list galleries.

GetListGalleryId appId galleryType
appIdIdentifier of the Word instance.
galleryTypeValue of enumeration type Enum::WdListGalleryType.

Returns the identifier of the specified list gallery.

See also: GetListTemplateId, InsertList

proc ::Word::GetListGalleryId {appId galleryType} {

    # Get one of the 3 predefined list galleries.
    #
    # appId       - Identifier of the Word instance.
    # galleryType - Value of enumeration type [Enum::WdListGalleryType].
    #
    # Returns the identifier of the specified list gallery.
    #
    # See also: GetListTemplateId InsertList

    return [$appId -with { ListGalleries } Item [Word GetEnum $galleryType]]
}

GetListTemplateId [::Word]Top, Main, Index

Get one of the 7 predefined list templates.

GetListTemplateId galleryId listType
galleryIdIdentifier of the Word gallery.
listTypeValue of enumeration type Enum::WdListType.

Returns the identifier of the specified list template.

See also: GetListGalleryId, InsertList

proc ::Word::GetListTemplateId {galleryId listType} {

    # Get one of the 7 predefined list templates.
    #
    # galleryId - Identifier of the Word gallery.
    # listType  - Value of enumeration type [Enum::WdListType].
    #
    # Returns the identifier of the specified list template.
    #
    # See also: GetListGalleryId InsertList

    return [$galleryId -with { ListTemplates } Item [Word GetEnum $listType]]
}

GetMatrixValues [::Word]Top, Main, Index

Return table values as a matrix.

GetMatrixValues tableId row1 col1 row2 col2
tableIdIdentifier of the Word table.
row1Row number of upper-left corner of the cell range.
col1Column number of upper-left corner of the cell range.
row2Row number of lower-right corner of the cell range.
col2Column number of lower-right corner of the cell range.

Returns table values as a matrix.

See also: SetMatrixValues

proc ::Word::GetMatrixValues {tableId row1 col1 row2 col2} {

    # Return table values as a matrix.
    #
    # tableId - Identifier of the Word table.
    # row1    - Row number of upper-left corner of the cell range.
    # col1    - Column number of upper-left corner of the cell range.
    # row2    - Row number of lower-right corner of the cell range.
    # col2    - Column number of lower-right corner of the cell range.
    #
    # Returns table values as a matrix.
    #
    # See also: SetMatrixValues

    set numVals [expr {$col2-$col1+1}]
    for { set row $row1 } { $row <= $row2 } { incr row } {
        lappend matrixList [Word GetRowValues $tableId $row $col1 $numVals]
    }
    return $matrixList
}

GetNumCharacters [::Word]Top, Main, Index

Return the number of characters in a Word document.

GetNumCharacters docId
docIdIdentifier of the document.

Returns the number of characters in the Word document.

See also: GetNumColumns, GetNumDocuments, GetNumImages, GetNumHyperlinks, GetNumPages, GetNumRows, GetNumSubdocuments, GetNumTables

proc ::Word::GetNumCharacters {docId} {

    # Return the number of characters in a Word document.
    #
    # docId - Identifier of the document.
    #
    # Returns the number of characters in the Word document.
    #
    # See also: GetNumColumns GetNumDocuments GetNumImages GetNumHyperlinks
    # GetNumPages GetNumRows GetNumSubdocuments GetNumTables


    return [$docId -with { Characters } Count]
}

GetNumColumns [::Word]Top, Main, Index

Return the number of columns of a Word table.

GetNumColumns tableId
tableIdIdentifier of the Word table.

Returns the number of columns of the Word table.

See also: GetNumCharacters, GetNumDocuments, GetNumImages, GetNumHyperlinks, GetNumPages, GetNumRows, GetNumSubdocuments, GetNumTables

proc ::Word::GetNumColumns {tableId} {

    # Return the number of columns of a Word table.
    #
    # tableId - Identifier of the Word table.
    #
    # Returns the number of columns of the Word table.
    #
    # See also: GetNumCharacters GetNumDocuments GetNumImages GetNumHyperlinks
    # GetNumPages GetNumRows GetNumSubdocuments GetNumTables

    return [$tableId -with { Columns } Count]
}

GetNumDocuments [::Word]Top, Main, Index

Return the number of documents in a Word application.

GetNumDocuments appId
appIdIdentifier of the Word instance.

Returns the number of documents in the Word application.

See also: AddDocument, OpenDocument, GetNumCharacters, GetNumColumns, GetNumImages, GetNumHyperlinks, GetNumPages, GetNumRows, GetNumSubdocuments, GetNumTables

proc ::Word::GetNumDocuments {appId} {

    # Return the number of documents in a Word application.
    #
    # appId - Identifier of the Word instance.
    #
    # Returns the number of documents in the Word application.
    #
    # See also: AddDocument OpenDocument
    # GetNumCharacters GetNumColumns GetNumImages GetNumHyperlinks
    # GetNumPages GetNumRows GetNumSubdocuments GetNumTables

    return [$appId -with { Documents } Count]
}

GetNumHyperlinks [::Word]Top, Main, Index

Return the number of hyperlinks of a Word document.

GetNumHyperlinks docId
docIdIdentifier of the document.

Returns the number of hyperlinks of the Word document. This counts both internal, file and url links, see GetHyperlinksAsDict for an explanation of link types.

See also: SetHyperlink, GetHyperlinksAsDict, GetBookmarkNames, GetNumCharacters, GetNumColumns, GetNumDocuments, GetNumImages, GetNumPages, GetNumRows, GetNumSubdocuments, GetNumTables

proc ::Word::GetNumHyperlinks {docId} {

    # Return the number of hyperlinks of a Word document.
    #
    # docId - Identifier of the document.
    #
    # Returns the number of hyperlinks of the Word document.
    # This counts both `internal`, `file` and `url` links, see
    # [GetHyperlinksAsDict] for an explanation of link types.
    #
    # See also: SetHyperlink GetHyperlinksAsDict GetBookmarkNames
    # GetNumCharacters GetNumColumns GetNumDocuments GetNumImages
    # GetNumPages GetNumRows GetNumSubdocuments GetNumTables

    return [$docId -with { Hyperlinks } Count]
}

GetNumImages [::Word]Top, Main, Index

Return the number of images of a Word document.

GetNumImages docId ?useInlineShapesOnly?
docIdIdentifier of the document.
useInlineShapesOnlyOnly consider InlineShapes as images. Optional, default true.

See GetImageList for a description of InlineShapes and Shapes.

Returns the number of images of the Word document.

See also: InsertImage, ReplaceImage, GetImageId, GetImageList, SetImageName, GetNumCharacters, GetNumColumns, GetNumDocuments, GetNumHyperlinks, GetNumPages, GetNumRows, GetNumSubdocuments, GetNumTables

proc ::Word::GetNumImages {docId {useInlineShapesOnly true}} {

    # Return the number of images of a Word document.
    #
    # docId               - Identifier of the document.
    # useInlineShapesOnly - Only consider InlineShapes as images.
    #
    # Returns the number of images of the Word document.
    #
    # See [GetImageList] for a description of InlineShapes and Shapes.
    #
    # See also: InsertImage ReplaceImage GetImageId GetImageList SetImageName
    # GetNumCharacters GetNumColumns GetNumDocuments GetNumHyperlinks
    # GetNumPages GetNumRows GetNumSubdocuments GetNumTables

    set numImgs 0

    set inlineShapes [$docId InlineShapes]
    $inlineShapes -iterate inlineShape {
        if { [$inlineShape Type] == $::Word::wdInlineShapeLinkedPicture ||  [$inlineShape Type] == $::Word::wdInlineShapePicture } {
            incr numImgs
        }
        Cawt Destroy $inlineShape
    }
    Cawt Destroy $inlineShapes

    if { ! $useInlineShapesOnly } {
        set shapes [$docId Shapes]
        $shapes -iterate shape {
            if { [$shape Type] == $::Office::msoPicture ||  [$shape Type] == $::Office::msoLinkedPicture } {
                incr numImgs
            }
            Cawt Destroy $shape
        }
        Cawt Destroy $shapes
    }
    return $numImgs
}

GetNumPages [::Word]Top, Main, Index

Return the number of pages in a Word document.

GetNumPages docId
docIdIdentifier of the document.

Returns the number of pages in the Word document.

See also: GetNumCharacters, GetNumColumns, GetNumDocuments, GetNumImages, GetNumHyperlinks, GetNumRows, GetNumSubdocuments, GetNumTables

proc ::Word::GetNumPages {docId} {

    # Return the number of pages in a Word document.
    #
    # docId - Identifier of the document.
    #
    # Returns the number of pages in the Word document.
    #
    # See also: GetNumCharacters GetNumColumns GetNumDocuments GetNumImages
    # GetNumHyperlinks GetNumRows GetNumSubdocuments GetNumTables

    set endRange [Word GetEndRange $docId]
    set numPages [$endRange Information $::Word::wdNumberOfPagesInDocument]
    Cawt Destroy $endRange
    return $numPages
}

GetNumRows [::Word]Top, Main, Index

Return the number of rows of a Word table.

GetNumRows tableId
tableIdIdentifier of the Word table.

Returns the number of rows of the Word table.

See also: GetNumCharacters, GetNumColumns, GetNumDocuments, GetNumImages, GetNumHyperlinks, GetNumPages, GetNumSubdocuments, GetNumTables

proc ::Word::GetNumRows {tableId} {

    # Return the number of rows of a Word table.
    #
    # tableId - Identifier of the Word table.
    #
    # Returns the number of rows of the Word table.
    #
    # See also: GetNumCharacters GetNumColumns GetNumDocuments GetNumImages
    # GetNumHyperlinks GetNumPages GetNumSubdocuments GetNumTables

    return [$tableId -with { Rows } Count]
}

GetNumSubdocuments [::Word]Top, Main, Index

Return the number of subdocuments in a Word document.

GetNumSubdocuments docId
docIdIdentifier of the document.

Returns the number of subdocuments in the Word document.

See also: GetSubdocumentPath, ExpandSubdocuments, DeleteSubdocumentLinks, GetNumCharacters, GetNumColumns, GetNumImages, GetNumHyperlinks, GetNumPages, GetNumRows, GetNumTables

proc ::Word::GetNumSubdocuments {docId} {

    # Return the number of subdocuments in a Word document.
    #
    # docId - Identifier of the document.
    #
    # Returns the number of subdocuments in the Word document.
    #
    # See also: GetSubdocumentPath ExpandSubdocuments DeleteSubdocumentLinks
    # GetNumCharacters GetNumColumns GetNumImages GetNumHyperlinks
    # GetNumPages GetNumRows GetNumTables

    return [$docId -with { Subdocuments } Count]
}

GetNumTables [::Word]Top, Main, Index

Return the number of tables of a Word document.

GetNumTables docId
docIdIdentifier of the document.

Returns the number of tables of the Word document.

See also: AddTable, GetNumCharacters, GetNumColumns, GetNumDocuments, GetNumImages, GetNumHyperlinks, GetNumPages, GetNumRows, GetNumSubdocuments

proc ::Word::GetNumTables {docId} {

    # Return the number of tables of a Word document.
    #
    # docId - Identifier of the document.
    #
    # Returns the number of tables of the Word document.
    #
    # See also: AddTable GetNumCharacters GetNumColumns GetNumDocuments
    # GetNumImages GetNumHyperlinks GetNumPages GetNumRows GetNumSubdocuments

    return [$docId -with { Tables } Count]
}

GetPageSetup [::Word]Top, Main, Index

Get page setup values.

GetPageSetup docId ?args?
docIdIdentifier of the document.
argsOptions described below.
-bottomGet the size of the bottom margin.
-centimeterGet the values in centimeters.
-footerGet the size of the footer margin.
-headerGet the size of the header margin.
-heightGet the height of the page.
-inchGet the values in inches.
-leftGet the size of the left margin.
-rightGet the size of the right margin.
-topGet the size of the top margin.
-usableheightGet the usable height of the page, i.e. height - top - bottom.
-usablewidthGet the usable width of the page, i.e. width - left - right
-widthGet the width of the page.

The values are returned as points, if no unit option is specified.

Example:

lassign [GetPageSetup $docId -top -left -inch] top left
returns the top and left margins in inches.

Returns the specified page setup values as a list.

See also: SetPageSetup, ::Cawt::PointsToCentiMeters, ::Cawt::PointsToInches

proc ::Word::GetPageSetup {docId args} {

    # Get page setup values.
    #
    # docId - Identifier of the document.
    # args  - Options described below.
    #
    # -top          - Get the size of the top margin.
    # -bottom       - Get the size of the bottom margin.
    # -left         - Get the size of the left margin.
    # -right        - Get the size of the right margin.
    # -footer       - Get the size of the footer margin.
    # -header       - Get the size of the header margin.
    # -height       - Get the height of the page.
    # -width        - Get the width of the page.
    # -usableheight - Get the usable height of the page, i.e. `height - top - bottom`.
    # -usablewidth  - Get the usable width of the page,  i.e. `width - left - right`
    # -centimeter   - Get the values in centimeters.
    # -inch         - Get the values in inches.
    #
    # The values are returned as points, if no unit option is specified.
    #
    # Example:
    #     lassign [GetPageSetup $docId -top -left -inch] top left
    #     returns the top and left margins in inches.
    #
    # Returns the specified page setup values as a list.
    #
    # See also: SetPageSetup ::Cawt::PointsToCentiMeters ::Cawt::PointsToInches

    set pageSetup [$docId PageSetup]
    set valList [list]
    set convert "none"
    foreach key $args {
        switch -exact -nocase -- $key {
            "-inch"         { set convert "inch" }
            "-centimeter"   { set convert "centimeter" }
            "-top"          { lappend valList [$pageSetup TopMargin] }
            "-bottom"       { lappend valList [$pageSetup BottomMargin] }
            "-left"         { lappend valList [$pageSetup LeftMargin] }
            "-right"        { lappend valList [$pageSetup RightMargin] }
            "-header"       { lappend valList [$pageSetup HeaderDistance] }
            "-footer"       { lappend valList [$pageSetup FooterDistance] }
            "-height"       { lappend valList [$pageSetup PageHeight] }
            "-width"        { lappend valList [$pageSetup PageWidth] }
            "-usableheight" {
                lappend valList [expr { [$pageSetup PageHeight] - [$pageSetup TopMargin] - [$pageSetup BottomMargin] }]
            }
            "-usablewidth" {
                lappend valList [expr { [$pageSetup PageWidth] - [$pageSetup LeftMargin] - [$pageSetup RightMargin] }]
            }
            default { error "GetPageSetup: Unknown key \"$key\" specified" }
        }
    }
    set convertList [list]
    foreach val $valList {
        if { $convert eq "inch" } {
            lappend convertList [Cawt PointsToInches $val]
        } elseif { $convert eq "centimeter" } {
            lappend convertList [Cawt PointsToCentiMeters $val]
        } else {
            lappend convertList $val
        }
    }
    Cawt Destroy $pageSetup
    return $convertList
}

GetRangeEndIndex [::Word]Top, Main, Index

Return the end index of a text range.

GetRangeEndIndex rangeId
rangeIdIdentifier of the text range.

Returns the end index of the text range.

See also: GetRangeStartIndex, PrintRange, GetRangeText

proc ::Word::GetRangeEndIndex {rangeId} {

    # Return the end index of a text range.
    #
    # rangeId - Identifier of the text range.
    #
    # Returns the end index of the text range.
    #
    # See also: GetRangeStartIndex PrintRange GetRangeText

    return [$rangeId End]
}

GetRangeFont [::Word]Top, Main, Index

Get font specific parameters.

GetRangeFont rangeId ?args?
rangeIdIdentifier of the text range.
argsOptions described below.
-backgroundGet the background color of the text range. Return value is an Office color number.
-boldGet the bold font style flag of the text range.
-colorGet the text color of the text range. Return value is of enumeration type Enum::WdColorIndex.
-italicGet the italic font style flag of the text range.
-nameGet the font name of the text range.
-sizeGet the font size of the text range in points.
-sizecGet the font size of the text range in centimeters.
-sizeiGet the font size of the text range in inches.
-underlineGet the underline font style flag of the text range.
-underlinecolorGet the underline color of the text range. Return value is of enumeration type Enum::WdColor.

Returns the specified font parameter values as a list.

See also: SetRangeFont, CreateRange, ::Cawt::GetColor

proc ::Word::GetRangeFont {rangeId args} {

    # Get font specific parameters.
    #
    # rangeId - Identifier of the text range.
    # args    - Options described below.
    #
    # -name           - Get the font name of the text range.
    # -size           - Get the font size of the text range in points.
    # -sizei          - Get the font size of the text range in inches.
    # -sizec          - Get the font size of the text range in centimeters.
    # -bold           - Get the bold font style flag of the text range.
    # -italic         - Get the italic font style flag of the text range.
    # -underline      - Get the underline font style flag of the text range.
    # -underlinecolor - Get the underline color of the text range.
    #                   Return value is of enumeration type [Enum::WdColor].
    # -background     - Get the background color of the text range.
    #                   Return value is an Office color number.
    # -color          - Get the text color of the text range.
    #                   Return value is of enumeration type [Enum::WdColorIndex].
    #
    # Returns the specified font parameter values as a list.
    #
    # See also: SetRangeFont CreateRange [::Cawt::GetColor]

    set font [$rangeId Font]
    set valList [list]
    foreach key $args {
        switch -exact -nocase -- $key {
            "-name"           { lappend valList [$font Name] }
            "-size"           { lappend valList [$font Size] }
            "-sizei"          { lappend valList [Cawt PointsToInches [$font Size]] }
            "-sizec"          { lappend valList [Cawt PointsToCentiMeters [$font Size]] }
            "-bold"           { lappend valList [Cawt TclBool [$font Bold]] }
            "-italic"         { lappend valList [Cawt TclBool [$font Italic]] }
            "-underline"      { lappend valList [Cawt TclBool [$font Underline]] }
            "-underlinecolor" { lappend valList [$font UnderlineColor] }
            "-background"     { lappend valList [$font -with { Shading } BackgroundPatternColor] }
            "-color"          { lappend valList [$font ColorIndex] }
            default           { error "GetRangeFont: Unknown key \"$key\" specified" }
        }
    }
    Cawt Destroy $font
    return $valList
}

GetRangeInformation [::Word]Top, Main, Index

Get information about a text range.

GetRangeInformation rangeId type
rangeIdIdentifier of the text range.
typeValue of enumeration type Enum::WdInformation.

Returns the range information associated with the supplied type.

See also: GetStartRange, GetEndRange, PrintRange, GetRangeText

proc ::Word::GetRangeInformation {rangeId type} {

    # Get information about a text range.
    #
    # rangeId - Identifier of the text range.
    # type    - Value of enumeration type [Enum::WdInformation].
    #
    # Returns the range information associated with the supplied type.
    #
    # See also: GetStartRange GetEndRange PrintRange GetRangeText

    return [$rangeId Information [Word GetEnum $type]]
}

GetRangeScreenPos [::Word]Top, Main, Index

Return the screen position of a text range.

GetRangeScreenPos rangeId
rangeIdIdentifier of the text range.

Note, that the text range must be in the active window.

Returns the screen position of a text range as a dictionary with keys left, top, width, height.

See also: SelectRange, GetRangeStartIndex, GetRangeText

proc ::Word::GetRangeScreenPos {rangeId} {

    # Return the screen position of a text range.
    #
    # rangeId - Identifier of the text range.
    #
    # Note, that the text range must be in the active window.
    #
    # Returns the screen position of a text range as a
    # dictionary with keys `left`, `top`, `width`, `height`.
    #
    # See also: SelectRange GetRangeStartIndex GetRangeText

    set docId [$rangeId Document]
    set windowId [$docId ActiveWindow]

    $windowId GetPoint  [twapi::outvar screenPixelsLeft]  [twapi::outvar screenPixelsTop]  [twapi::outvar screenPixelsWidth]  [twapi::outvar screenPixelsHeight]  $rangeId

    Cawt Destroy $docId
    Cawt Destroy $windowId

    return [dict create  "left"   [lindex $screenPixelsLeft 1]    "top"    [lindex $screenPixelsTop 1]     "width"  [lindex $screenPixelsWidth 1]   "height" [lindex $screenPixelsHeight 1]  ]
}

GetRangeStartIndex [::Word]Top, Main, Index

Return the start index of a text range.

GetRangeStartIndex rangeId
rangeIdIdentifier of the text range.

Returns the start index of the text range.

See also: GetRangeEndIndex, PrintRange, GetRangeText

proc ::Word::GetRangeStartIndex {rangeId} {

    # Return the start index of a text range.
    #
    # rangeId - Identifier of the text range.
    #
    # Returns the start index of the text range.
    #
    # See also: GetRangeEndIndex PrintRange GetRangeText

    return [$rangeId Start]
}

GetRangeText [::Word]Top, Main, Index

Return the text of a text range.

GetRangeText rangeId
rangeIdIdentifier of the text range.

Returns the text of the specified range as a string.

See also: GetRangeStartIndex, GetRangeEndIndex, GetCellValue, GetHeadingRanges

proc ::Word::GetRangeText {rangeId} {

    # Return the text of a text range.
    #
    # rangeId - Identifier of the text range.
    #
    # Returns the text of the specified range as a string.
    #
    # See also: GetRangeStartIndex GetRangeEndIndex
    # GetCellValue GetHeadingRanges

    set val [Word::TrimString [$rangeId Text]]
    return $val
}

GetRowId [::Word]Top, Main, Index

Return identifier of a Word table row.

GetRowId tableId row
tableIdIdentifier of the Word table.
rowRow number. Row numbering starts with 1. If set to end, the last row of the table is used.

Returns the identifier of the specified row.

See also: GetRowRange, GetCellRange, GetColumnRange

proc ::Word::GetRowId {tableId row} {

    # Return identifier of a Word table row.
    #
    # tableId - Identifier of the Word table.
    # row     - Row number. Row numbering starts with 1.
    #           If set to `end`, the last row of the table is used.
    #
    # Returns the identifier of the specified row.
    #
    # See also: GetRowRange GetCellRange GetColumnRange

    set numRows [Word GetNumRows $tableId]
    if { $row eq "end" } {
        set row $numRows
    } elseif { $row < 1 } {
        error "GetRowId: Row number ($row) must be greater than zero."
    } elseif { $row > $numRows } {
        error "GetRowId: Row number ($row) is greater than available rows ($numRows)."
    }
    return [$tableId -with { Rows } Item $row]
}

GetRowRange [::Word]Top, Main, Index

Return rows of a Word table as a range.

GetRowRange tableId row1 ?row2?
tableIdIdentifier of the Word table.
row1Row range start number.
row2Row range end number. If not specified, only $row1 is used. If set to end, the last row of the table is used. Optional, default "".

Row numbering starts with 1.

Returns a range consisting of all cells of the specified rows.

See also: GetRowId, GetCellRange, GetColumnRange

proc ::Word::GetRowRange {tableId row1 {row2 {}}} {

    # Return rows of a Word table as a range.
    #
    # tableId - Identifier of the Word table.
    # row1    - Row range start number.
    # row2    - Row range end number.
    #           If not specified, only $row1 is used.
    #           If set to `end`, the last row of the table is used.
    #
    # Row numbering starts with 1.
    #
    # Returns a range consisting of all cells of the specified rows.
    #
    # See also: GetRowId GetCellRange GetColumnRange

    if { $row1 eq "end" } {
        set row1 [Word GetNumRows $tableId]
    }
    if { $row2 eq "" } {
        set rowId [$tableId -with { Rows } Item $row1]
        set rangeId [$rowId Range]
        Cawt Destroy $rowId
        return $rangeId
    }

    if { $row2 eq "end" } {
        set row2 [Word GetNumRows $tableId]
    }
    set rowId1 [$tableId -with { Rows } Item $row1]
    set rowId2 [$tableId -with { Rows } Item $row2]
    set rangeId1 [$rowId1 Range]
    set rangeId2 [$rowId2 Range]
    Word SetRangeEndIndex $rangeId1 [Word GetRangeEndIndex $rangeId2]
    Cawt Destroy $rowId1
    Cawt Destroy $rowId2
    Cawt Destroy $rangeId2
    return $rangeId1
}

GetRowValues [::Word]Top, Main, Index

Return row values of a Word table as a Tcl list.

GetRowValues tableId row ?startCol? ?numVals?
tableIdIdentifier of the Word table.
rowRow number. Row numbering starts with 1.
startColColumn number of start. Column numbering starts with 1. Optional, default 1.
numValsIf negative or zero, all available row values are returned. If positive, only numVals values of the row are returned. Optional, default 0.

Returns the values of the specified row or row range as a Tcl list.

See also: SetRowValues, GetColumnValues, GetCellValue

proc ::Word::GetRowValues {tableId row {startCol 1} {numVals 0}} {

    # Return row values of a Word table as a Tcl list.
    #
    # tableId  - Identifier of the Word table.
    # row      - Row number. Row numbering starts with 1.
    # startCol - Column number of start. Column numbering starts with 1.
    # numVals  - If negative or zero, all available row values are returned.
    #            If positive, only numVals values of the row are returned.
    #
    # Returns the values of the specified row or row range as a Tcl list.
    #
    # See also: SetRowValues GetColumnValues GetCellValue

    if { $numVals <= 0 } {
        set len [Word GetNumColumns $tableId]
    } else {
        set len $numVals
    }
    set valList [list]
    set col $startCol
    set ind 0
    while { $ind < $len } {
        set val [Word GetCellValue $tableId $row $col]
        lappend valList $val
        incr ind
        incr col
    }
    return $valList
}

GetSelectionRange [::Word]Top, Main, Index

Return the text range representing the current selection.

GetSelectionRange docId
docIdIdentifier of the document.

Returns the text range representing the current selection.

See also: GetStartRange, GetEndRange, SelectRange

proc ::Word::GetSelectionRange {docId} {

    # Return the text range representing the current selection.
    #
    # docId - Identifier of the document.
    #
    # Returns the text range representing the current selection.
    #
    # See also: GetStartRange GetEndRange SelectRange

    return [$docId -with { ActiveWindow } Selection]
}

GetStartRange [::Word]Top, Main, Index

Return a text range representing the start of the document.

GetStartRange docId
docIdIdentifier of the document.

Returns a text range representing the start of the document.

See also: CreateRange, GetSelectionRange, GetEndRange

proc ::Word::GetStartRange {docId} {

    # Return a text range representing the start of the document.
    #
    # docId - Identifier of the document.
    #
    # Returns a text range representing the start of the document.
    #
    # See also: CreateRange GetSelectionRange GetEndRange

    return [Word CreateRange $docId 0 0]
}

GetSubdocumentPath [::Word]Top, Main, Index

Return the file path of a subdocument.

GetSubdocumentPath docId index
docIdIdentifier of the document.
indexIndex of the subdocument. Indices start at 1.

Returns the normalized path of the subdocument.

See also: GetNumSubdocuments, ExpandSubdocuments, DeleteSubdocumentLinks

proc ::Word::GetSubdocumentPath {docId index} {

    # Return the file path of a subdocument.
    #
    # docId - Identifier of the document.
    # index - Index of the subdocument. Indices start at 1.
    #
    # Returns the normalized path of the subdocument.
    #
    # See also: GetNumSubdocuments ExpandSubdocuments DeleteSubdocumentLinks

    set count [Word GetNumSubdocuments $docId]

    if { $index < 1 || $index > $count } {
        error "GetSubdocumentPath: Invalid index $index given."
    }

    set subDocId [$docId -with { Subdocuments } Item $index]
    set path [$subDocId Path]
    set name [$subDocId Name]
    Cawt Destroy $subDocId
    return [file normalize [file join $path $name]]
}

GetTableIdByIndex [::Word]Top, Main, Index

Find a table by its index.

GetTableIdByIndex docId index
docIdIdentifier of the document.
indexIndex of the table to find.

Returns the identifier of the found table. If the index is out of bounds an error is thrown.

See also: GetTableIdByName, GetNumTables

proc ::Word::GetTableIdByIndex {docId index} {

    # Find a table by its index.
    #
    # docId - Identifier of the document.
    # index - Index of the table to find.
    #
    # Returns the identifier of the found table.
    # If the index is out of bounds an error is thrown.
    #
    # See also: GetTableIdByName GetNumTables

    set count [Word GetNumTables $docId]

    if { $index < 1 || $index > $count } {
        error "GetTableIdByIndex: Invalid index $index given."
    }
    return [$docId -with { Tables } Item $index]
}

GetTableIdByName [::Word]Top, Main, Index

Find table(s) by its name.

GetTableIdByName docId name
docIdIdentifier of the document.
nameName of the table(s) to find.

Table names are supported since Word 2010. If your Word version is older, an error is thrown.

Returns a list of identifiers of the found table(s). If no tables with given name exist, an empty list is returned.

See also: GetTableIdByIndex, GetNumTables

proc ::Word::GetTableIdByName {docId name} {

    # Find table(s) by its name.
    #
    # docId - Identifier of the document.
    # name  - Name of the table(s) to find.
    #
    # Returns a list of identifiers of the found table(s).
    # If no tables with given name exist, an empty list is returned.
    #
    # Table names are supported since Word 2010.
    # If your Word version is older, an error is thrown.
    #
    # See also: GetTableIdByIndex GetNumTables

    variable wordVersion

    if { $wordVersion < 14.0 } {
        error "Table names available only in Word 2010 or newer. Running [Word GetVersion $docId true]."
    }

    set tableIdList [list]
    set count [Word GetNumTables $docId]
    for { set i 1 } { $i <= $count } { incr i } {
        set tableId [$docId -with { Tables } Item [expr $i]]
        if { $name eq [Word::GetTableName $tableId] } {
            lappend tableIdList $tableId
        } else {
            Cawt Destroy $tableId
        }
    }
    return $tableIdList
}

GetTableName [::Word]Top, Main, Index

Return the name of a table.

GetTableName tableId
tableIdIdentifier of the Word table.

Table names are supported since Word 2010. If your Word version is older, an error is thrown.

Returns the name of the table.

See also: SetTableName, GetNumTables, AddTable

proc ::Word::GetTableName {tableId} {

    # Return the name of a table.
    #
    # tableId - Identifier of the Word table.
    #
    # Table names are supported since Word 2010.
    # If your Word version is older, an error is thrown.
    #
    # Returns the name of the table.
    #
    # See also: SetTableName GetNumTables AddTable

    variable wordVersion

    if { $wordVersion < 14.0 } {
        error "Table names available only in Word 2010 or newer. Running [Word GetVersion $tableId true]."
    }
    return [$tableId Title]
}

GetVersion [::Word]Top, Main, Index

Return the version of a Word application.

GetVersion objId ?useString?
objIdIdentifier of a Word object instance.
useStringIf set to true, return the version name (ex. Word 2000). Otherwise return the version number (ex. 9.0). Optional, default false.

Both version name and version number are returned as strings. Version number is in a format, so that it can be evaluated as a floating point number.

Returns the version of the Word application.

See also: GetCompatibilityMode, GetExtString

proc ::Word::GetVersion {objId {useString false}} {

    # Return the version of a Word application.
    #
    # objId     - Identifier of a Word object instance.
    # useString - If set to true, return the version name (ex. `Word 2000`).
    #             Otherwise return the version number (ex. `9.0`).
    #
    # Both version name and version number are returned as strings.
    # Version number is in a format, so that it can be evaluated as a
    # floating point number.
    #
    # Returns the version of the Word application.
    #
    # See also: GetCompatibilityMode GetExtString

    array set map {
        "7.0"  "Word 95"
        "8.0"  "Word 97"
        "9.0"  "Word 2000"
        "10.0" "Word 2002"
        "11.0" "Word 2003"
        "12.0" "Word 2007"
        "14.0" "Word 2010"
        "15.0" "Word 2013"
        "16.0" "Word 2016/2019"
    }
    set version [Office GetApplicationVersion $objId]
    if { $useString } {
        if { [info exists map($version)] } {
            return $map($version)
        } else {
            return "Unknown Word version $version"
        }
    } else {
        return $version
    }
}

InsertCaption [::Word]Top, Main, Index

Insert a caption into a range of a document.

InsertCaption rangeId labelId text ?pos?
rangeIdIdentifier of the text range.
labelIdValue of enumeration type Enum::WdCaptionLabelID. Possible values: wdCaptionEquation, wdCaptionFigure, wdCaptionTable.
textText of the caption.
posValue of enumeration type Enum::WdCaptionPosition. Optional, default wdCaptionPositionBelow.

Returns the new extended range.

See also: ConfigureCaption, InsertFile, InsertImage, InsertList, InsertText

proc ::Word::InsertCaption {rangeId labelId text {pos wdCaptionPositionBelow}} {

    # Insert a caption into a range of a document.
    #
    # rangeId - Identifier of the text range.
    # labelId - Value of enumeration type [Enum::WdCaptionLabelID].
    #           Possible values: `wdCaptionEquation`, `wdCaptionFigure`, `wdCaptionTable`.
    # text    - Text of the caption.
    # pos     - Value of enumeration type [Enum::WdCaptionPosition].
    #
    # Returns the new extended range.
    #
    # See also: ConfigureCaption InsertFile InsertImage InsertList InsertText

    $rangeId InsertCaption [Word GetEnum $labelId] $text "" [Word GetEnum $pos] 0
    return $rangeId
}

InsertFile [::Word]Top, Main, Index

Insert a file into a Word document.

InsertFile rangeId fileName ?pasteFormat?
rangeIdIdentifier of the text range.
fileNameName of the file to insert.
pasteFormatValue of enumeration type Enum::WdRecoveryType. Optional, default "".

Insert an external file at the text range identified by $rangeId. If $pasteFormat is not specified or an empty string, the Word method InsertFile is used. Otherwise the external file is opened in a new Word document, copied to the clipboard and pasted into the text range. For pasting the Word method PasteAndFormat is used, so it is possible to merge the new text from the external file into the Word document in different ways.

Returns no value.

See also: SetHyperlink, InsertCaption, InsertImage, InsertList, InsertText

proc ::Word::InsertFile {rangeId fileName {pasteFormat {}}} {

    # Insert a file into a Word document.
    #
    # rangeId     - Identifier of the text range.
    # fileName    - Name of the file to insert.
    # pasteFormat - Value of enumeration type [Enum::WdRecoveryType].
    #
    # Insert an external file at the text range identified by $rangeId. If $pasteFormat is
    # not specified or an empty string, the Word method `InsertFile` is used.
    # Otherwise the external file is opened in a new Word document, copied to the clipboard
    # and pasted into the text range. For pasting the Word method `PasteAndFormat` is used, so it is
    # possible to merge the new text from the external file into the Word document in different ways.
    #
    # Returns no value.
    #
    # See also: SetHyperlink InsertCaption InsertImage InsertList InsertText

    if { $pasteFormat ne "" } {
        set tmpAppId [Office GetApplicationId $rangeId]
        set tmpDocId [Word OpenDocument $tmpAppId $fileName false]
        set tmpRangeId [Word GetStartRange $tmpDocId]
        $tmpRangeId WholeStory
        $tmpRangeId Copy

        Cawt WaitClipboardReady
        $rangeId PasteAndFormat [Word GetEnum $pasteFormat]

        # Workaround: Select a small portion of text and copy it to clipboard
        # to avoid an alert message regarding lots of data in clipboard.
        # Setting DisplayAlerts to false does not help here.
        set dummyRange [Word CreateRange $tmpDocId 0 1]
        $dummyRange Copy
        Cawt Destroy $dummyRange

        Word Close $tmpDocId
        Cawt Destroy $tmpRangeId
        Cawt Destroy $tmpDocId
        Cawt Destroy $tmpAppId
    } else {
        # InsertFile(FileName, Range, ConfirmConversions, Link, Attachment)
        $rangeId InsertFile [file nativename [file normalize $fileName]]  ""  [Cawt TclBool false]  [Cawt TclBool false]  [Cawt TclBool false]
    }
}

InsertImage [::Word]Top, Main, Index

Insert an image into a range of a document.

InsertImage rangeId imgFileName ?linkToFile? ?saveWithDoc?
rangeIdIdentifier of the text range.
imgFileNameFile name of the image.
linkToFileInsert a link to the image file. Optional, default false.
saveWithDocEmbed the image into the document. Optional, default true.

See GetImageList for a description of InlineShapes and Shapes.

Returns the identifier of the inserted image as an InlineShape.

See also: GetNumImages, ScaleImage, CropImage, InsertFile, InsertCaption, InsertList, InsertText

proc ::Word::InsertImage {rangeId imgFileName {linkToFile false} {saveWithDoc true}} {

            # Insert an image into a range of a document.
            #
            # rangeId     - Identifier of the text range.
            # imgFileName - File name of the image.
            # linkToFile  - Insert a link to the image file.
            # saveWithDoc - Embed the image into the document.
            #
            # Returns the identifier of the inserted image as an InlineShape.
            #
            # See [GetImageList] for a description of InlineShapes and Shapes.
            #
            # See also: GetNumImages ScaleImage CropImage InsertFile InsertCaption
            # InsertList InsertText

            if { ! $linkToFile && ! $saveWithDoc } {
                error "InsertImage: linkToFile and saveWithDoc are both set to false."
            }

    	set fileName [file nativename [file normalize $imgFileName]]
            set shapeId [$rangeId -with { InlineShapes } AddPicture $fileName  [Cawt TclInt $linkToFile]  [Cawt TclInt $saveWithDoc]]
            return $shapeId
}

InsertList [::Word]Top, Main, Index

Insert a Word list.

InsertList rangeId stringList ?galleryType? ?listType?
rangeIdIdentifier of the text range.
stringListList of text strings building up the Word list.
galleryTypeValue of enumeration type Enum::WdListGalleryType. Optional, default wdBulletGallery.
listTypeValue of enumeration type Enum::WdListType. Optional, default wdListListNumOnly.

Returns the range of the Word list.

See also: GetListGalleryId, GetListTemplateId, InsertCaption, InsertFile, InsertImage, InsertText

proc ::Word::InsertList {rangeId stringList {galleryType wdBulletGallery} {listType wdListListNumOnly}} {

    # Insert a Word list.
    #
    # rangeId     - Identifier of the text range.
    # stringList  - List of text strings building up the Word list.
    # galleryType - Value of enumeration type [Enum::WdListGalleryType].
    # listType    - Value of enumeration type [Enum::WdListType].
    #
    # Returns the range of the Word list.
    #
    # See also: GetListGalleryId GetListTemplateId InsertCaption InsertFile InsertImage InsertText

    foreach line $stringList {
        append listStr "$line\n"
    }
    set appId [Office GetApplicationId $rangeId]
    set listRangeId [Word AddText $rangeId $listStr]
    set listGalleryId  [Word GetListGalleryId $appId $galleryType]
    set listTemplateId [Word GetListTemplateId $listGalleryId $listType]
    $listRangeId -with { ListFormat } ApplyListTemplate $listTemplateId
    Cawt Destroy $listTemplateId
    Cawt Destroy $listGalleryId
    Cawt Destroy $appId
    return $listRangeId
}

InsertText [::Word]Top, Main, Index

Insert text in a Word document.

InsertText docId text ?addParagraph? ?style?
docIdIdentifier of the document.
textText string to be inserted.
addParagraphAdd a paragraph after the text. Optional, default false.
styleValue of enumeration type Enum::WdBuiltinStyle. Optional, default wdStyleNormal.

The text string is inserted at the start of the document with given style.

Returns the new text range.

See also: AddText, AppendText, AddParagraph, SetRangeStyle, InsertCaption, InsertFile, InsertImage, InsertList

proc ::Word::InsertText {docId text {addParagraph false} {style wdStyleNormal}} {

    # Insert text in a Word document.
    #
    # docId        - Identifier of the document.
    # text         - Text string to be inserted.
    # addParagraph - Add a paragraph after the text.
    # style        - Value of enumeration type [Enum::WdBuiltinStyle].
    #
    # The text string is inserted at the start of the document with given style.
    #
    # Returns the new text range.
    #
    # See also: AddText AppendText AddParagraph SetRangeStyle
    # InsertCaption InsertFile InsertImage InsertList

    set newRange [Word CreateRange $docId 0 0]
    $newRange InsertAfter $text
    if { $addParagraph } {
        $newRange InsertParagraphAfter
    }
    Word SetRangeStyle $newRange $style
    return $newRange
}

IsInlineShape [::Word]Top, Main, Index

Check, if a Word object is an InlineShape.

IsInlineShape objId
objIdIdentifier of a Word object instance.

Returns true, if the Word object is an InlineShape. Otherwise false.

See also: IsValidCell

proc ::Word::IsInlineShape {objId} {

    # Check, if a Word object is an InlineShape.
    #
    # objId - Identifier of a Word object instance.
    #
    # Returns true, if the Word object is an InlineShape.
    # Otherwise false.
    #
    # See also: IsValidCell

    # Borders is a property of the Word InlineShape class,
    # but not of class Shape.
     set retVal [catch {$objId Borders} errMsg]
     if { $retVal == 0 } {
         Cawt Destroy $errMsg
         return true
     } else {
         return false
     }
}

IsValidCell [::Word]Top, Main, Index

Check, if a Word table cell is valid.

IsValidCell tableId row col
tableIdIdentifier of the Word table.
rowRow number. Row numbering starts with 1.
colColumn number. Column numbering starts with 1.

Returns true, if the cell is valid, otherwise false.

See also: GetCellValue

proc ::Word::IsValidCell {tableId row col} {

    # Check, if a Word table cell is valid.
    #
    # tableId - Identifier of the Word table.
    # row     - Row number. Row numbering starts with 1.
    # col     - Column number. Column numbering starts with 1.
    #
    # Returns true, if the cell is valid, otherwise false.
    #
    # See also: GetCellValue

    set retVal [catch { $tableId Cell $row $col } errMsg]
    if { $retVal == 0 } {
        Cawt Destroy $errMsg
        return true
    } else {
        return false
    }
}

IsVisible [::Word]Top, Main, Index

Check the visibility of a Word application window.

IsVisible appId
appIdIdentifier of the Word instance.

Returns true, if the Word application windows is visible.

See also: Open, OpenNew, Visible

proc ::Word::IsVisible {appId} {

    # Check the visibility of a Word application window.
    #
    # appId - Identifier of the Word instance.
    #
    # Returns true, if the Word application windows is visible.
    #
    # See also: Open OpenNew Visible

    if { [$appId Visible] } {
        return true
    } else {
        return false
    }
}

MergeCells [::Word]Top, Main, Index

Merge a range of cells.

MergeCells tableId row1 col1 row2 col2
tableIdIdentifier of the Word table.
row1Range start row number. Row numbering starts with 1.
col1Range start column number. Column numbering starts with 1.
row2Range end row number. If set to end, the last row of the table is used.
col2Range end column number. If set to end, the last column of the table is used.

Returns the range identifier of the merged cells.

See also: SetRangeMergeCells, SelectRange

proc ::Word::MergeCells {tableId row1 col1 row2 col2} {

    # Merge a range of cells.
    #
    # tableId - Identifier of the Word table.
    # row1    - Range start row number. Row numbering starts with 1.
    # col1    - Range start column number. Column numbering starts with 1.
    # row2    - Range end row number.
    #           If set to `end`, the last row of the table is used.
    # col2    - Range end column number.
    #           If set to `end`, the last column of the table is used.
    #
    # Returns the range identifier of the merged cells.
    #
    # See also: SetRangeMergeCells SelectRange

    set appId [Office GetApplicationId $tableId]
    Word::ShowAlerts $appId false

    if { $row2 eq "end" } {
        set row2 [Word GetNumRows $tableId]
    }
    if { $col2 eq "end" } {
        set col2 [Word GetNumColumns $tableId]
    }

    set cellId1 [$tableId Cell $row1 $col1]
    set cellId2 [$tableId Cell $row2 $col2]
    $cellId1 Merge $cellId2
    set rangeId [$cellId1 Range]

    Word::ShowAlerts $appId true

    Cawt Destroy $cellId1
    Cawt Destroy $cellId2
    Cawt Destroy $appId

    return $rangeId
}

Open [::Word]Top, Main, Index

Open a Word instance. Use an already running instance, if available.

Open ?visible? ?width? ?height?
visibleIf set to true, show the application window. Otherwise hide the application window. Optional, default true.
widthWidth of the application window. If negative, open with last used width. Optional, default -1.
heightHeight of the application window. If negative, open with last used height. Optional, default -1.

Returns the identifier of the Word application instance.

See also: OpenNew, Quit, Visible

proc ::Word::Open {{visible true} {width -1} {height -1}} {

            # Open a Word instance. Use an already running instance, if available.
            #
            # visible - If set to true, show the application window.
            #           Otherwise hide the application window.
            # width   - Width of the application window. If negative, open with last used width.
            # height  - Height of the application window. If negative, open with last used height.
            #
            # Returns the identifier of the Word application instance.
            #
            # See also: OpenNew Quit Visible

            variable wordAppName
    	variable wordVersion

            set appId [Cawt GetOrCreateApp $wordAppName true]
            set wordVersion [Word GetVersion $appId]
            Word Visible $appId $visible
            if { $width >= 0 } {
                $appId Width [expr $width]
            }
            if { $height >= 0 } {
                $appId Height [expr $height]
            }
            return $appId
}

OpenDocument [::Word]Top, Main, Index

Open a document, i.e. load a Word file.

OpenDocument appId fileName ?args?
appIdIdentifier of the Word instance.
fileNameName of the Word file.
argsOptions described below.
-embed <frame>Embed the document into a Tk frame. This frame must exist and must be created with option -container true.
-readonly <bool>If set to true, open the document in read-only mode. Default is to open the document in read-write mode.

Returns the identifier of the opened document. If the document was already open, activate that document and return the identifier to that document.

See also: AddDocument, SetPageSetup

proc ::Word::OpenDocument {appId fileName args} {

    # Open a document, i.e. load a Word file.
    #
    # appId    - Identifier of the Word instance.
    # fileName - Name of the Word file.
    # args     - Options described below.
    #
    # -readonly <bool> - If set to true, open the document in read-only mode.
    #                    Default is to open the document in read-write mode.
    # -embed <frame>   - Embed the document into a Tk frame. This frame must
    #                    exist and must be created with option `-container true`.
    #
    # Returns the identifier of the opened document. If the document was
    # already open, activate that document and return the identifier to
    # that document.
    #
    # See also: AddDocument SetPageSetup

    set opts [dict create  -readonly false    -embed    ""       ]
    if { [llength $args] == 1 } {
        # Old mode with optional boolean parameter readOnly
        dict set opts -readonly [lindex $args 0]
    } else {
        foreach { key value } $args {
            if { [dict exists $opts $key] } {
                if { $value eq "" } {
                    error "OpenDocument: No value specified for key \"$key\"."
                }
                dict set opts $key $value
            } else {
                error "OpenDocument: Unknown option \"$key\" specified."
            }
        }
    }

    set nativeName [file nativename [file normalize $fileName]]
    set docs [$appId Documents]
    set retVal [catch {[$docs Item [file tail $fileName]] Activate} d]
    if { $retVal == 0 } {
        set docId [$docs Item [file tail $fileName]]
    } else {
        # Open(FileName, [ConfirmConversions], [ReadOnly],
        # [AddToRecentFiles], [PasswordDocument], [PasswordTemplate],
        # [Revert], [WritePasswordDocument], [WritePasswordTemplate],
        # [Format], [Encoding], [Visible], [OpenAndRepair],
        # [DocumentDirection], [NoEncodingDialog], [XMLTransform])
        # As Document
        set docId [$docs -callnamedargs Open  FileName $nativeName  ConfirmConversions [Cawt TclBool false]  ReadOnly [Cawt TclInt [dict get $opts "-readonly"]]]
    }
    Cawt Destroy $docs
    set embedFrame [dict get $opts "-embed"]
    if { $embedFrame ne "" } {
        set docWindows [$docId Windows]
        $docWindows -iterate window {
            set windowHndl [$window Hwnd]
            set windowId   [list $windowHndl HWND]
            break
        }
        Cawt Destroy $docWindows
        Cawt EmbedApp $embedFrame -appid [Office GetApplicationId $docId] -window $windowId
    }
    return $docId
}

OpenNew [::Word]Top, Main, Index

Open a new Word instance.

OpenNew ?visible? ?width? ?height?
visibleIf set to true, show the application window. Otherwise hide the application window. Optional, default true.
widthWidth of the application window. If negative, open with last used width. Optional, default -1.
heightHeight of the application window. If negative, open with last used height. Optional, default -1.

Returns the identifier of the new Word application instance.

See also: Open, Quit, Visible

proc ::Word::OpenNew {{visible true} {width -1} {height -1}} {

            # Open a new Word instance.
            #
            # visible - If set to true, show the application window.
            #           Otherwise hide the application window.
            # width   - Width of the application window. If negative, open with last used width.
            # height  - Height of the application window. If negative, open with last used height.
            #
            # Returns the identifier of the new Word application instance.
            #
            # See also: Open Quit Visible

            variable wordAppName
    	variable wordVersion

            set appId [Cawt GetOrCreateApp $wordAppName false]
            set wordVersion [Word GetVersion $appId]
            Word Visible $appId $visible
            if { $width >= 0 } {
                $appId Width [expr $width]
            }
            if { $height >= 0 } {
                $appId Height [expr $height]
            }
            return $appId
}

PrintHeadingDict [::Word]Top, Main, Index

Print the contents of a heading dictionary onto stdout.

PrintHeadingDict headingDict
headingDictDictionary as returned by GetHeadingAsDict

Returns no value.

See also: GetHyperlinksAsDict, GetHeadingsAsDict

proc ::Word::PrintHeadingDict {headingDict} {

    # Print the contents of a heading dictionary onto stdout.
    #
    # headingDict - Dictionary as returned by GetHeadingAsDict
    #
    # Returns no value.
    #
    # See also: GetHyperlinksAsDict GetHeadingsAsDict

    dict for { id info } $headingDict {
        puts "Heading $id"
        dict with info {
            puts "  text : $text"
            puts "  level: $level"
            puts "  start: $start"
            puts "  end  : $end"
        }
    }
}

PrintHyperlinkDict [::Word]Top, Main, Index

Print the contents of a hyperlink dictionary onto stdout.

PrintHyperlinkDict hyperlinkDict
hyperlinkDictDictionary as returned by GetHyperlinksAsDict

Returns no value.

See also: GetHyperlinksAsDict, GetNumHyperlinks

proc ::Word::PrintHyperlinkDict {hyperlinkDict} {

    # Print the contents of a hyperlink dictionary onto stdout.
    #
    # hyperlinkDict - Dictionary as returned by GetHyperlinksAsDict
    #
    # Returns no value.
    #
    # See also: GetHyperlinksAsDict GetNumHyperlinks

    dict for { id info } $hyperlinkDict {
        puts "Hyperlink $id"
        dict with info {
            puts "  address   : $address"
            puts "  subaddress: $subaddress"
            puts "  text      : $text"
            puts "  type      : $type"
            puts "  start     : $start"
            puts "  end       : $end"
            puts "  valid     : $valid"
        }
    }
}

PrintRange [::Word]Top, Main, Index

Print the indices of a text range.

PrintRange rangeId ?msg?
rangeIdIdentifier of the text range.
msgString printed in front of the indices. Optional, default Range:.

The range identifiers are printed onto standard output.

Returns no value.

See also: GetRangeStartIndex, GetRangeEndIndex

proc ::Word::PrintRange {rangeId {msg {Range: }}} {

    # Print the indices of a text range.
    #
    # rangeId - Identifier of the text range.
    # msg     - String printed in front of the indices.
    #
    # The range identifiers are printed onto standard output.
    #
    # Returns no value.
    #
    # See also: GetRangeStartIndex GetRangeEndIndex

    puts [format "%s %d %d" $msg  [Word GetRangeStartIndex $rangeId] [Word GetRangeEndIndex $rangeId]]
}

Quit [::Word]Top, Main, Index

Quit a Word instance.

Quit appId ?showAlert?
appIdIdentifier of the Word instance.
showAlertIf set to true, show an alert window, if there are unsaved changes. Otherwise quit without saving any changes. Optional, default true.

Returns no value.

See also: Open, OpenNew

proc ::Word::Quit {appId {showAlert true}} {

    # Quit a Word instance.
    #
    # appId     - Identifier of the Word instance.
    # showAlert - If set to true, show an alert window, if there are unsaved changes.
    #             Otherwise quit without saving any changes.
    #
    # Returns no value.
    #
    # See also: Open OpenNew

    Word::ShowAlerts $appId $showAlert
    if { ! $showAlert } {
        set numDocs [Word::GetNumDocuments $appId]
        for { set i 1 } { $i <= $numDocs } { incr i } {
            set docId [Word::GetDocumentIdByIndex $appId $i]
            Word::Close $docId
            Cawt Destroy $docId
        }
    }
    $appId Quit
}

ReplaceByProc [::Word]Top, Main, Index

Replace a string in a text range. Procedural case.

ReplaceByProc rangeId str func ?args?
rangeIdIdentifier of the text range.
strSearch string.
funcReplacement procedure.
argsArguments for replacement procedure.

Search for string $str in the range $rangeId. For each occurence found, call procedure $func with the range of the found occurence and additional parameters specified in $args. The procedures which can be used for $func must therefore have the following signature:

proc SetRangeXYZ rangeId param1 param2 ...

See test script Word-04-Find.tcl for an example.

Returns no value.

See also: FindString, ReplaceString

proc ::Word::ReplaceByProc {rangeId str func args} {

    # Replace a string in a text range. Procedural case.
    #
    # rangeId - Identifier of the text range.
    # str     - Search string.
    # func    - Replacement procedure.
    # args    - Arguments for replacement procedure.
    #
    # Search for string $str in the range $rangeId. For each
    # occurence found, call procedure $func with the range of
    # the found occurence and additional parameters specified in
    # $args. The procedures which can be used for $func must
    # therefore have the following signature:
    #     proc SetRangeXYZ rangeId param1 param2 ...
    #
    # See test script Word-04-Find.tcl for an example.
    #
    # Returns no value.
    #
    # See also: FindString ReplaceString

    set myFind [$rangeId Find]
    set count 0
    while { 1 } {
        # See proc _FindOrReplace for a parameter list of the Execute command.
        set retVal [$myFind -callnamedargs Execute  FindText $str  MatchCase True  Forward True]
        if { ! $retVal } {
            break
        }
        eval $func $rangeId $args
        incr count
    }
    Cawt Destroy $myFind
}

ReplaceImage [::Word]Top, Main, Index

Replace an existing image.

ReplaceImage shapeId imgFileName ?args?
shapeIdIdentifier of the image InlineShape or Shape.
imgFileNameFile name of the new image (as absolute path).
argsOptions described below.
-keepsize <bool>Keep original image size. Default value is false.

See GetImageList for a description of InlineShapes and Shapes.

Note: Replacing Shape images does not work correctly yet. Images are replaced, but the layout is disturbed.

Returns the identifier of the new image.

See also: InsertImage, GetImageList, GetNumImages, SetImageName

proc ::Word::ReplaceImage {shapeId imgFileName args} {

    # Replace an existing image.
    #
    # shapeId     - Identifier of the image InlineShape or Shape.
    # imgFileName - File name of the new image (as absolute path).
    # args        - Options described below.
    #
    # -keepsize <bool> - Keep original image size. Default value is false.
    #
    # Returns the identifier of the new image.
    #
    # See [GetImageList] for a description of InlineShapes and Shapes.
    #
    # **Note:**
    # Replacing Shape images does not work correctly yet.
    # Images are replaced, but the layout is disturbed.
    #
    # See also: InsertImage GetImageList GetNumImages SetImageName

    set opts [dict create  -keepsize false  ]
    foreach { key value } $args {
        if { $value eq "" } {
            error "ReplaceImage: No value specified for key \"$key\""
        }
        if { [dict exists $opts $key] } {
            dict set opts $key $value
        } else {
            error "ReplaceImage: Unknown option \"$key\" specified"
        }
    }

    set width  [$shapeId Width]
    set height [$shapeId Height]
    set title  [$shapeId Title]

    set fileName [file nativename [file normalize $imgFileName]]

    if { [Word::IsInlineShape $shapeId] } {
        set rangeId [$shapeId Range]
        set newShapeId [$rangeId -with { InlineShapes } AddPicture $fileName]
    } else {
        $shapeId RelativeHorizontalPosition $::Word::wdRelativeHorizontalPositionPage
        $shapeId RelativeVerticalPosition   $::Word::wdRelativeVerticalPositionPage
        set width  [$shapeId Width]
        set height [$shapeId Height]
        set top  [$shapeId Top]
        set left [$shapeId Left]
        set docId [$shapeId Parent]
        set anchor [$shapeId -with { Anchor } Duplicate]
        set newShapeId [$docId -with { Shapes } AddPicture $fileName]
        Word::_AssignWrapFormat $shapeId $newShapeId
        $newShapeId Left [expr $left - [GetPageSetup $docId -left]]
        $newShapeId Top  [expr $top  - [GetPageSetup $docId -top]]
    }
    $shapeId Delete
    Cawt Destroy $shapeId

    $newShapeId Title $title

    if { [dict get $opts "-keepsize"] } {
        $newShapeId Width  $width
        $newShapeId Height $height
    }
    return $newShapeId
}

ReplaceString [::Word]Top, Main, Index

Replace a string in a text range or a document. Simple case.

ReplaceString rangeOrDocId searchStr replaceStr ?howMuch? ?matchCase? ?matchWildcards?
rangeOrDocIdIdentifier of a text range or a document identifier.
searchStrSearch string.
replaceStrReplacement string.
howMuchone to replace first occurence only. all to replace all occurences. Optional, default one.
matchCaseFlag indicating case sensitive search. Optional, default true.
matchWildcardsFlag indicating wildcard search. Optional, default false.

Returns zero, if string could not be found and replaced. Otherwise a positive integer.

See also: FindString, ReplaceByProc, Search

proc ::Word::ReplaceString {rangeOrDocId searchStr replaceStr {howMuch one} {matchCase true} {matchWildcards false}} {

    # Replace a string in a text range or a document. Simple case.
    #
    # rangeOrDocId   - Identifier of a text range or a document identifier.
    # searchStr      - Search string.
    # replaceStr     - Replacement string.
    # howMuch        - `one` to replace first occurence only. `all` to replace all occurences.
    # matchCase      - Flag indicating case sensitive search.
    # matchWildcards - Flag indicating wildcard search.
    #
    # Returns zero, if string could not be found and replaced. Otherwise a positive integer.
    #
    # See also: FindString ReplaceByProc Search

    set howMuchEnum $Word::wdReplaceOne
    if { $howMuch ne "one" } {
        set howMuchEnum $Word::wdReplaceAll
    }
    return [Word::Search $rangeOrDocId $searchStr  -matchcase $matchCase -matchwildcards $matchWildcards  -wrap $Word::wdFindStop -forward true  -replacewith $replaceStr -replace $howMuchEnum]
}

SaveAs [::Word]Top, Main, Index

Save a document to a Word file.

SaveAs docId fileName ?fmt?
docIdIdentifier of the document to save.
fileNameName of the Word file.
fmtValue of enumeration type Enum::WdSaveFormat. If not given or the empty string, the file is stored in the native format corresponding to the used Word version. Optional, default "".

Returns no value.

See also: SaveAsPdf

proc ::Word::SaveAs {docId fileName {fmt {}}} {

    # Save a document to a Word file.
    #
    # docId    - Identifier of the document to save.
    # fileName - Name of the Word file.
    # fmt      - Value of enumeration type [Enum::WdSaveFormat].
    #            If not given or the empty string, the file is stored in the native
    #            format corresponding to the used Word version.
    #
    # Returns no value.
    #
    # See also: SaveAsPdf

    variable wordVersion

    set fileName [file nativename [file normalize $fileName]]
    set appId [Office GetApplicationId $docId]
    Word::ShowAlerts $appId false
    if { $fmt eq "" } {
        if { $wordVersion >= 14.0 } {
            $docId SaveAs $fileName [expr $Word::wdFormatDocumentDefault]
        } else {
            $docId SaveAs $fileName
        }
    } else {
        $docId SaveAs $fileName [Word GetEnum $fmt]
    }
    Word::ShowAlerts $appId true
}

SaveAsPdf [::Word]Top, Main, Index

Save a document to a PDF file.

SaveAsPdf docId fileName
docIdIdentifier of the document to export.
fileNameName of the PDF file.

PDF export is supported since Word 2007. If your Word version is older an error is thrown.

Note: For Word 2007 you need the Microsoft Office Add-in Microsoft Save as PDF or XPS available from http://www.microsoft.com/en-us/download/details.aspx?id=7

Returns no value.

See also: SaveAs

proc ::Word::SaveAsPdf {docId fileName} {

    # Save a document to a PDF file.
    #
    # docId    - Identifier of the document to export.
    # fileName - Name of the PDF file.
    #
    # PDF export is supported since Word 2007.
    # If your Word version is older an error is thrown.
    #
    # **Note:**
    # For Word 2007 you need the Microsoft Office Add-in
    # `Microsoft Save as PDF or XPS` available from
    # <http://www.microsoft.com/en-us/download/details.aspx?id=7>
    #
    # Returns no value.
    #
    # See also: SaveAs

    variable wordVersion

    if { $wordVersion < 12.0 } {
        error "PDF export available only in Word 2007 or newer. Running [Word GetVersion $docId true]."
    }

    set fileName [file nativename [file normalize $fileName]]
    set appId [Office GetApplicationId $docId]

    Word::ShowAlerts $appId false
    $docId -callnamedargs ExportAsFixedFormat  OutputFileName $fileName  ExportFormat $Word::wdExportFormatPDF  OpenAfterExport [Cawt TclBool false]  OptimizeFor $Word::wdExportOptimizeForPrint  Range $Word::wdExportAllDocument  From [expr 1]  To [expr 1]  Item $Word::wdExportDocumentContent  IncludeDocProps [Cawt TclBool true]  KeepIRM [Cawt TclBool true]  CreateBookmarks $Word::wdExportCreateHeadingBookmarks  DocStructureTags [Cawt TclBool true]  BitmapMissingFonts [Cawt TclBool true]  UseISO19005_1 [Cawt TclBool false]
    Word::ShowAlerts $appId true
}

ScaleImage [::Word]Top, Main, Index

Scale an image.

ScaleImage shapeId scaleWidth scaleHeight
shapeIdIdentifier of the image InlineShape.
scaleWidthHorizontal scale factor.
scaleHeightVertical scale factor.

The scale factors are floating point values. 1.0 means no scaling.

See GetImageList for a description of InlineShapes and Shapes.

Returns no value.

See also: GetNumImages, InsertImage, ReplaceImage, CropImage

proc ::Word::ScaleImage {shapeId scaleWidth scaleHeight} {

    # Scale an image.
    #
    # shapeId     - Identifier of the image InlineShape.
    # scaleWidth  - Horizontal scale factor.
    # scaleHeight - Vertical scale factor.
    #
    # The scale factors are floating point values. 1.0 means no scaling.
    #
    # Returns no value.
    #
    # See [GetImageList] for a description of InlineShapes and Shapes.
    #
    # See also: GetNumImages InsertImage ReplaceImage CropImage

    $shapeId LockAspectRatio [Cawt TclInt false]
    $shapeId ScaleWidth  [expr { 100.0 * double($scaleWidth) }]
    $shapeId ScaleHeight [expr { 100.0 * double($scaleHeight) }]
}

ScreenUpdate [::Word]Top, Main, Index

Toggle the screen updating of a Word application window.

ScreenUpdate appId onOff
appIdIdentifier of the Word instance.
onOffIf set to true, update the application window. Otherwise do not update the application window.

Returns no value.

See also: Visible, IsVisible

proc ::Word::ScreenUpdate {appId onOff} {

    # Toggle the screen updating of a Word application window.
    #
    # appId - Identifier of the Word instance.
    # onOff - If set to true, update the application window.
    #         Otherwise do not update the application window.
    #
    # Returns no value.
    #
    # See also: Visible IsVisible

    $appId ScreenUpdating [Cawt TclBool $onOff]
}

Search [::Word]Top, Main, Index

Search or replace a string in a text range or a document. Generic case.

Search rangeOrDocId searchStr ?args?
rangeOrDocIdIdentifier of a text range or a document identifier.
searchStrSearch string.
argsOptions described below.
-format <bool>Search operation uses formatting in addition to the search string.
-forward <bool>Search towards end of document.
-ignorepunct <bool>Ignore all punctuation characters between words.
-ignorespace <bool>Ignore all white space between words.
-matchalefhamza <bool>Match text with matching alef hamzas in an Arabic-language document.
-matchallwordforms <bool>Search all forms of the search string.
-matchcase <bool>Search in case sensitive mode.
-matchcontrol <bool>Match text with matching bidirectional control characters in a right-to-left language document.
-matchdiacritics <bool>Match text with matching diacritics in a right-to-left language document.
-matchkashida <bool>Match text with matching kashidas in an Arabic-language document.
-matchphrase <bool>Ignores all white space and control characters between words.
-matchprefix <bool>Match words beginning with the search string.
-matchsoundslike <bool>Search for strings that sound similar.
-matchsuffix <bool>Match words ending with the search string.
-matchwholeword <bool>Search entire words only.
-matchwildcards <bool>Search with wild cards.
-replace <enum>Number of replacements. Value of enumeration type Enum::WdReplace. Typical values: wdReplaceNone, wdReplaceOne, wdReplaceAll.
-replacewith <string>Replacement text.
-wrap <enum>Search wrap mode. Value of enumeration type Enum::WdFindWrap. Typical values: wdFindAsk, wdFindContinue, wdFindStop.

See the Word reference documentation regarding Find.Execute at https://msdn.microsoft.com/en-us/library/office/ff193977.aspx for more details.

Returns zero, if string could not be found and replaced. Otherwise a positive integer.

See also: FindString, ReplaceString, ReplaceByProc

proc ::Word::Search {rangeOrDocId searchStr args} {

    # Search or replace a string in a text range or a document. Generic case.
    #
    # rangeOrDocId - Identifier of a text range or a document identifier.
    # searchStr    - Search string.
    # args         - Options described below.
    #
    # -matchcase <bool>         - Search in case sensitive mode.
    # -matchwholeword <bool>    - Search entire words only.
    # -matchwildcards <bool>    - Search with wild cards.
    # -matchsoundslike <bool>   - Search for strings that sound similar.
    # -matchallwordforms <bool> - Search all forms of the search string.
    # -forward <bool>           - Search towards end of document.
    # -wrap <enum>              - Search wrap mode.
    #                             Value of enumeration type [Enum::WdFindWrap].
    #                             Typical values: `wdFindAsk`, `wdFindContinue`, `wdFindStop`.
    # -format <bool>            - Search operation uses formatting in addition to the search string.
    # -replacewith <string>     - Replacement text.
    # -replace <enum>           - Number of replacements.
    #                             Value of enumeration type [Enum::WdReplace].
    #                             Typical values: `wdReplaceNone`, `wdReplaceOne`, `wdReplaceAll`.
    # -matchkashida <bool>      - Match text with matching kashidas in an Arabic-language document.
    # -matchdiacritics <bool>   - Match text with matching diacritics in a right-to-left language document.
    # -matchalefhamza <bool>    - Match text with matching alef hamzas in an Arabic-language document.
    # -matchcontrol <bool>      - Match text with matching bidirectional control characters in a
    #                             right-to-left language document.
    # -matchprefix <bool>       - Match words beginning with the search string.
    # -matchsuffix <bool>       - Match words ending with the search string.
    # -matchphrase <bool>       - Ignores all white space and control characters between words.
    # -ignorespace <bool>       - Ignore all white space between words.
    # -ignorepunct <bool>       - Ignore all punctuation characters between words.
    #
    # See the Word reference documentation regarding `Find.Execute` at
    # <https://msdn.microsoft.com/en-us/library/office/ff193977.aspx> for more details.
    #
    # Returns zero, if string could not be found and replaced. Otherwise a positive integer.
    #
    # See also: FindString ReplaceString ReplaceByProc

    set params [dict create FindText $searchStr]

    foreach { key value } $args {
        if { $value eq "" && $key ne "-replacewith" } {
            error "Search: No value specified for key \"$key\""
        }
        switch -exact -nocase -- $key {
            "-matchcase"         { dict append params MatchCase         [Cawt TclBool $value] }
            "-matchwholeword"    { dict append params MatchWholeWord    [Cawt TclBool $value] }
            "-matchwildcards"    { dict append params MatchWildcards    [Cawt TclBool $value] }
            "-matchsoundslike"   { dict append params MatchSoundsLike   [Cawt TclBool $value] }
            "-matchallwordforms" { dict append params MatchAllWordForms [Cawt TclBool $value] }
            "-forward"           { dict append params Forward           [Cawt TclBool $value] }
            "-wrap"              { dict append params Wrap              [Word GetEnum $value] }
            "-format"            { dict append params Format            [Cawt TclBool $value] }
            "-replacewith"       { dict append params ReplaceWith       $value }
            "-replace"           { dict append params Replace           [Word GetEnum $value] }
            "-matchkashida"      { dict append params MatchKashida      [Cawt TclBool $value] }
            "-matchdiacritics"   { dict append params MatchDiacritics   [Cawt TclBool $value] }
            "-matchalefhamza"    { dict append params MatchAlefHamza    [Cawt TclBool $value] }
            "-matchcontrol"      { dict append params MatchControl      [Cawt TclBool $value] }
            "-matchprefix"       { dict append params MatchPrefix       [Cawt TclBool $value] }
            "-matchsuffix"       { dict append params MatchSuffix       [Cawt TclBool $value] }
            "-matchphrase"       { dict append params MatchPhrase       [Cawt TclBool $value] }
            "-ignorespace"       { dict append params IgnoreSpace       [Cawt TclBool $value] }
            "-ignorepunct"       { dict append params IgnorePunct       [Cawt TclBool $value] }
            default              { error "Search: Unknown key \"$key\" specified" }
        }
    }
    return [Word::_IterateDocument $rangeOrDocId $params]
}

SelectRange [::Word]Top, Main, Index

Select a text range.

SelectRange rangeId
rangeIdIdentifier of the text range.

Returns no value.

See also: GetSelectionRange, GetRangeScreenPos

proc ::Word::SelectRange {rangeId} {

    # Select a text range.
    #
    # rangeId - Identifier of the text range.
    #
    # Returns no value.
    #
    # See also: GetSelectionRange GetRangeScreenPos

    $rangeId Select
}

SetCellValue [::Word]Top, Main, Index

Set the value of a Word table cell.

SetCellValue tableId row col val
tableIdIdentifier of the Word table.
rowRow number. Row numbering starts with 1.
colColumn number. Column numbering starts with 1.
valString value of the cell.

Returns no value.

See also: GetCellValue, SetRowValues, SetMatrixValues

proc ::Word::SetCellValue {tableId row col val} {

    # Set the value of a Word table cell.
    #
    # tableId - Identifier of the Word table.
    # row     - Row number. Row numbering starts with 1.
    # col     - Column number. Column numbering starts with 1.
    # val     - String value of the cell.
    #
    # Returns no value.
    #
    # See also: GetCellValue SetRowValues SetMatrixValues

    set rangeId [Word GetCellRange $tableId $row $col]
    $rangeId Text $val
    Cawt Destroy $rangeId
}

SetCellVerticalAlignment [::Word]Top, Main, Index

Set the vertical alignment of a Word table cell.

SetCellVerticalAlignment tableId row col align
tableIdIdentifier of the Word table.
rowRow number. Row numbering starts with 1.
colColumn number. Column numbering starts with 1.
alignValue of enumeration type Enum::WdCellVerticalAlignment or any of the following strings: top, bottom, center.

Returns no value.

See also: SetCellValue, SetRangeHorizontalAlignment

proc ::Word::SetCellVerticalAlignment {tableId row col align} {

    # Set the vertical alignment of a Word table cell.
    #
    # tableId - Identifier of the Word table.
    # row     - Row number. Row numbering starts with 1.
    # col     - Column number. Column numbering starts with 1.
    # align   - Value of enumeration type [Enum::WdCellVerticalAlignment]
    #           or any of the following strings: `top`, `bottom`, `center`.
    #
    # Returns no value.
    #
    # See also: SetCellValue SetRangeHorizontalAlignment

    if { $align eq "center" } {
        set alignEnum $Word::wdCellAlignVerticalCenter
    } elseif { $align eq "top" } {
        set alignEnum $Word::wdCellAlignVerticalTop
    } elseif { $align eq "bottom" } {
        set alignEnum $Word::wdCellAlignVerticalBottom
    } else {
        set alignEnum [Word GetEnum $align]
    }

    set cellId [$tableId Cell $row $col]
    $cellId VerticalAlignment $alignEnum
    Cawt Destroy $cellId
}

SetColumnsWidth [::Word]Top, Main, Index

Set the width of a range of table columns.

SetColumnsWidth tableId startCol endCol width
tableIdIdentifier of the Word table.
startColRange start column number. Column numbering starts with 1.
endColRange end column number. Column numbering starts with 1.
widthColumn width.

$width may be specified in a format acceptable by procedure ::Cawt::ValueToPoints, i.e. centimeters, inches or points. $width may also be specified in percent, ex. 50%.

Returns no value.

See also: SetColumnWidth

proc ::Word::SetColumnsWidth {tableId startCol endCol width} {

    # Set the width of a range of table columns.
    #
    # tableId  - Identifier of the Word table.
    # startCol - Range start column number. Column numbering starts with 1.
    # endCol   - Range end column number. Column numbering starts with 1.
    # width    - Column width.
    #
    # $width may be specified in a format acceptable by procedure
    # [::Cawt::ValueToPoints], i.e. centimeters, inches or points.
    # $width may also be specified in percent, ex. `50%`.
    #
    # Returns no value.
    #
    # See also: SetColumnWidth

    for { set c $startCol } { $c <= $endCol } { incr c } {
        SetColumnWidth $tableId $c $width
    }
}

SetColumnValues [::Word]Top, Main, Index

Insert column values into a Word table.

SetColumnValues tableId col valList ?startRow? ?numVals?
tableIdIdentifier of the Word table.
colColumn number. Column numbering starts with 1.
valListList of values to be inserted.
startRowRow number of insertion start. Row numbering starts with 1. Optional, default 1.
numValsIf negative or zero, all list values are inserted. If positive, $numVals rows are filled with the list values (starting at list index 0). Optional, default 0.

Returns no value.

See also: GetColumnValues, SetRowValues, SetCellValue

proc ::Word::SetColumnValues {tableId col valList {startRow 1} {numVals 0}} {

    # Insert column values into a Word table.
    #
    # tableId  - Identifier of the Word table.
    # col      - Column number. Column numbering starts with 1.
    # valList  - List of values to be inserted.
    # startRow - Row number of insertion start. Row numbering starts with 1.
    # numVals  - If negative or zero, all list values are inserted.
    #            If positive, $numVals rows are filled with the list values
    #            (starting at list index 0).
    #
    # Returns no value.
    #
    # See also: GetColumnValues SetRowValues SetCellValue

    set len [llength $valList]
    if { $numVals > 0 } {
        if { $numVals < $len } {
            set len $numVals
        }
    }
    set ind 0
    for { set r $startRow } { $r < [expr {$startRow + $len}] } { incr r } {
        SetCellValue $tableId $r $col [lindex $valList $ind]
        incr ind
    }
}

SetColumnWidth [::Word]Top, Main, Index

Set the width of a table column.

SetColumnWidth tableId col width
tableIdIdentifier of the Word table.
colColumn number. Column numbering starts with 1.
widthColumn width.

$width may be specified in a format acceptable by procedure ::Cawt::ValueToPoints, i.e. centimeters, inches or points. $width may also be specified in percent, ex. 50%.

Returns no value.

See also: SetColumnsWidth

proc ::Word::SetColumnWidth {tableId col width} {

    # Set the width of a table column.
    #
    # tableId - Identifier of the Word table.
    # col     - Column number. Column numbering starts with 1.
    # width   - Column width.
    #
    # $width may be specified in a format acceptable by procedure
    # [::Cawt::ValueToPoints], i.e. centimeters, inches or points.
    # $width may also be specified in percent, ex. `50%`.
    #
    # Returns no value.
    #
    # See also: SetColumnsWidth

    set colId [$tableId -with { Columns } Item $col]
    if { [string match "*%" $width] } {
        scan $width "%f" percent
        $colId PreferredWidthType $Word::wdPreferredWidthPercent
        $colId PreferredWidth $percent
    } else {
        $colId Width [Cawt ValueToPoints $width]
    }
    Cawt Destroy $colId
}

SetCompatibilityMode [::Word]Top, Main, Index

Set the compatibility mode of a document.

SetCompatibilityMode docId ?mode?
docIdIdentifier of the document.
modeCompatibility mode of the document. Value of enumeration type Enum::WdCompatibilityMode. Optional, default wdWord2010.

Available only for Word 2010 and up.

Returns no value.

See also: GetCompatibilityMode

proc ::Word::SetCompatibilityMode {docId {mode wdWord2010}} {

    # Set the compatibility mode of a document.
    #
    # docId - Identifier of the document.
    # mode  - Compatibility mode of the document.
    #         Value of enumeration type [Enum::WdCompatibilityMode].
    #
    # Available only for Word 2010 and up.
    #
    # Returns no value.
    #
    # See also: GetCompatibilityMode

    variable wordVersion

    if { $wordVersion >= 14.0 } {
        $docId SetCompatibilityMode [Word GetEnum $mode]
    }
}

SetContentControlDropdown [::Word]Top, Main, Index

Set the values for a content control dropdown list.

SetContentControlDropdown controlId placeholderText keyValueList
controlIdIdentifier of the content control.
placeholderTextText for the content control.
keyValueListList of key-value pairs.

Returns no value.

See also: AddContentControl, SetContentControlText

proc ::Word::SetContentControlDropdown {controlId placeholderText keyValueList} {

    # Set the values for a content control dropdown list.
    #
    # controlId       - Identifier of the content control.
    # placeholderText - Text for the content control.
    # keyValueList    - List of key-value pairs.
    #
    # Returns no value.
    #
    # See also: AddContentControl SetContentControlText

    if { $placeholderText ne "" } {
        $controlId SetPlaceholderText NULL NULL $placeholderText
    }
    $controlId -with { DropdownListEntries } Clear
    foreach { key val } $keyValueList {
        $controlId -with { DropdownListEntries } Add $key $val
    }
}

SetContentControlText [::Word]Top, Main, Index

Set the text of a content control.

SetContentControlText controlId placeholderText
controlIdIdentifier of the content control.
placeholderTextText for the content control.

Returns no value.

See also: AddContentControl, SetContentControlDropdown

proc ::Word::SetContentControlText {controlId placeholderText} {

    # Set the text of a content control.
    #
    # controlId       - Identifier of the content control.
    # placeholderText - Text for the content control.
    #
    # Returns no value.
    #
    # See also: AddContentControl SetContentControlDropdown

    if { $placeholderText ne "" } {
        $controlId SetPlaceholderText NULL NULL $placeholderText
    }
}

SetHeaderRow [::Word]Top, Main, Index

Insert row values into a Word table and format as a header row.

SetHeaderRow tableId headerList ?row? ?startCol?
tableIdIdentifier of the Word table.
headerListList of values to be inserted as header.
rowRow number. Row numbering starts with 1. Optional, default 1.
startColColumn number of insertion start. Column numbering starts with 1. Optional, default 1.

Returns no value. If headerList is an empty list, an error is thrown.

See also: SetRowValues, FormatHeaderRow, SetHeadingFormat

proc ::Word::SetHeaderRow {tableId headerList {row 1} {startCol 1}} {

    # Insert row values into a Word table and format as a header row.
    #
    # tableId    - Identifier of the Word table.
    # headerList - List of values to be inserted as header.
    # row        - Row number. Row numbering starts with 1.
    # startCol   - Column number of insertion start. Column numbering starts with 1.
    #
    # Returns no value. If headerList is an empty list, an error is thrown.
    #
    # See also: SetRowValues FormatHeaderRow SetHeadingFormat

    set len [llength $headerList]
    Word SetRowValues $tableId $row $headerList $startCol $len
    Word FormatHeaderRow $tableId $row $startCol [expr {$startCol + $len -1}]
}

SetHeadingFormat [::Word]Top, Main, Index

Set the HeadingFormat flag of table rows.

SetHeadingFormat tableId onOff ?args?
tableIdIdentifier of the Word table.
onOffHeading format flag.
argsList of row numbers for which the heading format flag should be set. Row numbering starts with 1. If no row numbers are specified, row number 1 is used.

If $onOff is set to true, the specified row is formatted as a table heading. Rows formatted as table headings are repeated when a table spans more than one page.

Returns no value.

See also: SetHeaderRow, FormatHeaderRow

proc ::Word::SetHeadingFormat {tableId onOff args} {

    # Set the HeadingFormat flag of table rows.
    #
    # tableId - Identifier of the Word table.
    # onOff   - Heading format flag.
    # args    - List of row numbers for which the heading format flag should be set.
    #           Row numbering starts with 1.
    #           If no row numbers are specified, row number 1 is used.
    #
    # If $onOff is set to true, the specified row is formatted as a table heading.
    # Rows formatted as table headings are repeated when a table spans more than one page.
    #
    # Returns no value.
    #
    # See also: SetHeaderRow FormatHeaderRow

    set numRows [Word GetNumRows $tableId]
    set flag 0
    if { $onOff } {
        # HeadingFormat is a Long and true must be specified as -1.
        set flag -1
    }
    if { [llength $args] == 0 } {
        set args [list 1]
    }
    foreach rowNum $args {
        if { [string is integer -strict $rowNum] && $rowNum >= 1 && $rowNum <= $numRows } {
            set rowId [$tableId -with { Rows } Item [expr int($rowNum)]]
            $rowId HeadingFormat $flag
            Cawt Destroy $rowId
        } else {
            error "SetHeadingFormat: Invalid row number $rowNum given."
        }
    }
}

SetHyperlink [::Word]Top, Main, Index

Insert an external hyperlink into a Word document.

SetHyperlink rangeId link ?textDisplay?
rangeIdIdentifier of the text range.
linkURL of the hyperlink.
textDisplayText to be displayed instead of the URL. Optional, default "".

URL's are specified as strings:

Returns no value.

See also: SetHyperlinkToFile, SetLinkToBookmark, SetInternalHyperlink

proc ::Word::SetHyperlink {rangeId link {textDisplay {}}} {

    # Insert an external hyperlink into a Word document.
    #
    # rangeId     - Identifier of the text range.
    # link        - URL of the hyperlink.
    # textDisplay - Text to be displayed instead of the URL.
    #
    # URL's are specified as strings:
    # * `file://myLinkedFile` specifies a link to a local file.
    # * `http://myLinkedWebpage` specifies a link to a web address.
    #
    # Returns no value.
    #
    # See also: SetHyperlinkToFile SetLinkToBookmark SetInternalHyperlink

    if { $textDisplay eq "" } {
        set textDisplay $link
    }

    set docId [Word GetDocumentId $rangeId]
    set hyperlinks [$docId Hyperlinks]
    # Add(Anchor As Object, [Address], [SubAddress], [ScreenTip],
    # [TextToDisplay], [Target]) As Hyperlink
    set hyperlink [$hyperlinks -callnamedargs Add  Anchor  $rangeId  Address $link  TextToDisplay $textDisplay]
    Cawt Destroy $hyperlink
    Cawt Destroy $hyperlinks
    Cawt Destroy $docId
}

SetHyperlinkToFile [::Word]Top, Main, Index

Insert a hyperlink to a file into a Word document.

SetHyperlinkToFile rangeId fileName ?textDisplay?
rangeIdIdentifier of the text range.
fileNamePath name of the linked file.
textDisplayText to be displayed instead of the file name. Optional, default "".

Returns no value.

See also: SetHyperlink, SetLinkToBookmark, SetInternalHyperlink

proc ::Word::SetHyperlinkToFile {rangeId fileName {textDisplay {}}} {

    # Insert a hyperlink to a file into a Word document.
    #
    # rangeId     - Identifier of the text range.
    # fileName    - Path name of the linked file.
    # textDisplay - Text to be displayed instead of the file name.
    #
    # Returns no value.
    #
    # See also: SetHyperlink SetLinkToBookmark SetInternalHyperlink

    if { [file pathtype $fileName] eq "relative" } {
        set address [format "file:./%s" [file nativename $fileName]]
    } else {
        set address [format "file://%s" [file nativename [file normalize $fileName]]]
        set appId [Office GetApplicationId $rangeId]
        $appId -with { DefaultWebOptions } UpdateLinksOnSave [Cawt TclBool false]
        Cawt Destroy $appId
    }
    SetHyperlink $rangeId $address $textDisplay
}

SetImageName [::Word]Top, Main, Index

Set the name of an image.

SetImageName shapeId name
shapeIdIdentifier of the image InlineShape or Shape.
nameNot documented.

Image names are supported since Word 2010. If your Word version is older, an error is thrown.

See GetImageList for a description of InlineShapes and Shapes.

Returns no value.

See also: GetNumImages, GetImageName, InsertImage, GetImageId, GetImageList

proc ::Word::SetImageName {shapeId name} {

    # Set the name of an image.
    #
    # shapeId - Identifier of the image InlineShape or Shape.
    #
    # Returns no value.
    #
    # Image names are supported since Word 2010.
    # If your Word version is older, an error is thrown.
    #
    # See [GetImageList] for a description of InlineShapes and Shapes.
    #
    # See also: GetNumImages GetImageName InsertImage GetImageId GetImageList

    variable wordVersion

    if { $wordVersion < 14.0 } {
        error "Image names available only in Word 2010 or newer. Running [Word GetVersion $shapeId true]."
    }
    $shapeId Title $name
}

SetInternalHyperlink [::Word]Top, Main, Index

Insert an internal hyperlink into a Word document.

SetInternalHyperlink rangeId subAddress ?textDisplay?
rangeIdIdentifier of the text range.
subAddressInternal reference.
textDisplayText to be displayed instead of the URL. Optional, default "".

Returns no value.

See also: SetLinkToBookmark, SetHyperlink, SetHyperlinkToFile

proc ::Word::SetInternalHyperlink {rangeId subAddress {textDisplay {}}} {

    # Insert an internal hyperlink into a Word document.
    #
    # rangeId     - Identifier of the text range.
    # subAddress  - Internal reference.
    # textDisplay - Text to be displayed instead of the URL.
    #
    # Returns no value.
    #
    # See also: SetLinkToBookmark SetHyperlink SetHyperlinkToFile

    if { $textDisplay eq "" } {
        set textDisplay $subAddress
    }

    set docId [Word GetDocumentId $rangeId]
    set hyperlinks [$docId Hyperlinks]
    # Add(Anchor As Object, [Address], [SubAddress], [ScreenTip],
    # [TextToDisplay], [Target]) As Hyperlink
    $hyperlinks -callnamedargs Add  Anchor  $rangeId  SubAddress $subAddress  TextToDisplay $textDisplay
    Cawt Destroy $hyperlinks
    Cawt Destroy $docId
}

SetLinkToBookmark [::Word]Top, Main, Index

Insert an internal link to a bookmark into a Word document.

SetLinkToBookmark rangeId bookmarkId ?textDisplay?
rangeIdIdentifier of the text range.
bookmarkIdIdentifier of the bookmark to link to.
textDisplayText to be displayed instead of the bookmark name. Optional, default "".

Returns no value.

See also: AddBookmark, GetBookmarkName, SetHyperlink, SetInternalHyperlink

proc ::Word::SetLinkToBookmark {rangeId bookmarkId {textDisplay {}}} {

    # Insert an internal link to a bookmark into a Word document.
    #
    # rangeId     - Identifier of the text range.
    # bookmarkId  - Identifier of the bookmark to link to.
    # textDisplay - Text to be displayed instead of the bookmark name.
    #
    # Returns no value.
    #
    # See also: AddBookmark GetBookmarkName SetHyperlink SetInternalHyperlink

    set bookmarkName [Word GetBookmarkName $bookmarkId]
    if { $textDisplay eq "" } {
        set textDisplay $bookmarkName
    }

    set docId [Word GetDocumentId $rangeId]
    set hyperlinks [$docId Hyperlinks]
    # Add(Anchor As Object, [Address], [SubAddress], [ScreenTip],
    # [TextToDisplay], [Target]) As Hyperlink
    $hyperlinks -callnamedargs Add  Anchor        $rangeId  Address       ""  SubAddress    $bookmarkName  TextToDisplay $textDisplay
    Cawt Destroy $hyperlinks
    Cawt Destroy $docId
}

SetMatrixValues [::Word]Top, Main, Index

Insert matrix values into a Word table.

SetMatrixValues tableId matrixList ?startRow? ?startCol?
tableIdIdentifier of the Word table.
matrixListMatrix with table data.
startRowRow number of insertion start. Row numbering starts with 1. Optional, default 1.
startColColumn number of insertion start. Column numbering starts with 1. Optional, default 1.

The matrix data must be stored as a list of lists. Each sub-list contains the values for the row values. The main (outer) list contains the rows of the matrix.

Example:

{ { R1_C1 R1_C2 R1_C3 } { R2_C1 R2_C2 R2_C3 } }

Returns no value.

See also: GetMatrixValues

proc ::Word::SetMatrixValues {tableId matrixList {startRow 1} {startCol 1}} {

    # Insert matrix values into a Word table.
    #
    # tableId    - Identifier of the Word table.
    # matrixList - Matrix with table data.
    # startRow   - Row number of insertion start. Row numbering starts with 1.
    # startCol   - Column number of insertion start. Column numbering starts with 1.
    #
    # The matrix data must be stored as a list of lists. Each sub-list contains
    # the values for the row values.
    # The main (outer) list contains the rows of the matrix.
    #
    # Example:
    #     { { R1_C1 R1_C2 R1_C3 } { R2_C1 R2_C2 R2_C3 } }
    #
    # Returns no value.
    #
    # See also: GetMatrixValues

    set curRow $startRow
    foreach rowList $matrixList {
        Word SetRowValues $tableId $curRow $rowList $startCol
        incr curRow
    }
}

SetPageSetup [::Word]Top, Main, Index

Set page setup values.

SetPageSetup docId ?args?
docIdIdentifier of the document.
argsOptions described below.
-bottom <size>Set the size of the bottom margin.
-footer <size>Set the size of the footer margin.
-header <size>Set the size of the header margin.
-height <size>Set the height of the page.
-left <size>Set the size of the left margin.
-right <size>Set the size of the right margin.
-top <size>Set the size of the top margin.
-width <size>Set the width of the page.

The size values may be specified in a format acceptable by procedure ::Cawt::ValueToPoints, i.e. centimeters, inches or points.

Returns no value.

See also: GetPageSetup, ::Cawt::PointsToCentiMeters, ::Cawt::PointsToInches

proc ::Word::SetPageSetup {docId args} {

    # Set page setup values.
    #
    # docId - Identifier of the document.
    # args  - Options described below.
    #
    # -top <size>    - Set the size of the top margin.
    # -bottom <size> - Set the size of the bottom margin.
    # -left <size>   - Set the size of the left margin.
    # -right <size>  - Set the size of the right margin.
    # -footer <size> - Set the size of the footer margin.
    # -header <size> - Set the size of the header margin.
    # -height <size> - Set the height of the page.
    # -width <size>  - Set the width of the page.
    #
    # The size values may be specified in a format acceptable by
    # procedure [::Cawt::ValueToPoints], i.e. centimeters, inches or points.
    #
    # Returns no value.
    #
    # See also: GetPageSetup ::Cawt::PointsToCentiMeters ::Cawt::PointsToInches

    set pageSetup [$docId PageSetup]
    foreach { key value } $args {
        if { $value eq "" } {
            error "SetPageSetup: No value specified for key \"$key\""
        }
        set pointValue [Cawt ValueToPoints $value]
        switch -exact -nocase -- $key {
            "-top"    { $pageSetup TopMargin      $pointValue }
            "-bottom" { $pageSetup BottomMargin   $pointValue }
            "-left"   { $pageSetup LeftMargin     $pointValue }
            "-right"  { $pageSetup RightMargin    $pointValue }
            "-header" { $pageSetup HeaderDistance $pointValue }
            "-footer" { $pageSetup FooterDistance $pointValue }
            "-height" { $pageSetup PageHeight     $pointValue }
            "-width"  { $pageSetup PageWidth      $pointValue }
            default   { error "SetPageSetup: Unknown key \"$key\" specified" }
        }
    }
    Cawt Destroy $pageSetup
}

SetRangeBackgroundColor [::Word]Top, Main, Index

Set the background color of a table cell range.

SetRangeBackgroundColor rangeId ?args?
rangeIdIdentifier of the cell range.
argsBackground color.

Color value may be specified in a format acceptable by procedure ::Cawt::GetColor, i.e. color name, hexadecimal string, Office color number or a list of 3 integer RGB values.

Note: This functionality is very slow with large tables ( > 100 rows).

Returns no value.

See also: SetRangeBackgroundColorByEnum, SetRangeHighlightColorByEnum

proc ::Word::SetRangeBackgroundColor {rangeId args} {

    # Set the background color of a table cell range.
    #
    # rangeId - Identifier of the cell range.
    # args    - Background color.
    #
    # Color value may be specified in a format acceptable by procedure [::Cawt::GetColor],
    # i.e. color name, hexadecimal string, Office color number or a list of 3 integer RGB values.
    #
    # **Note:** This functionality is very slow with large tables ( > 100 rows).
    #
    # Returns no value.
    #
    # See also: SetRangeBackgroundColorByEnum SetRangeHighlightColorByEnum

    $rangeId -with { Cells Shading } BackgroundPatternColor [Cawt GetColor {*}$args]
}

SetRangeBackgroundColorByEnum [::Word]Top, Main, Index

Set the background color of a table cell range.

SetRangeBackgroundColorByEnum rangeId colorEnum
rangeIdIdentifier of the cell range.
colorEnumValue of enumeration type Enum::WdColor.

Note: This functionality is very slow with large tables ( > 100 rows).

Returns no value.

See also: SetRangeBackgroundColor, SetRangeHighlightColorByEnum

proc ::Word::SetRangeBackgroundColorByEnum {rangeId colorEnum} {

    # Set the background color of a table cell range.
    #
    # rangeId   - Identifier of the cell range.
    # colorEnum - Value of enumeration type [Enum::WdColor].
    #
    # **Note:** This functionality is very slow with large tables ( > 100 rows).
    #
    # Returns no value.
    #
    # See also: SetRangeBackgroundColor SetRangeHighlightColorByEnum

    $rangeId -with { Cells Shading } BackgroundPatternColor [Word GetEnum $colorEnum]
}

SetRangeEndIndex [::Word]Top, Main, Index

Set the end index of a text range.

SetRangeEndIndex rangeId index
rangeIdIdentifier of the text range.
indexIndex for the range end.

Index is either an integer value or string end to use the end of the document.

Returns no value.

See also: SetRangeStartIndex, GetRangeEndIndex

proc ::Word::SetRangeEndIndex {rangeId index} {

    # Set the end index of a text range.
    #
    # rangeId - Identifier of the text range.
    # index   - Index for the range end.
    #
    # Index is either an integer value or string `end` to
    # use the end of the document.
    #
    # Returns no value.
    #
    # See also: SetRangeStartIndex GetRangeEndIndex

    if { $index eq "end" } {
        set docId [Word GetDocumentId $rangeId]
        set index [GetRangeEndIndex [GetEndRange $docId]]
        Cawt Destroy $docId
    }
    $rangeId End $index
}

SetRangeFont [::Word]Top, Main, Index

Set font specific parameters.

SetRangeFont rangeId ?args?
rangeIdIdentifier of the text range.
argsOptions described below.
-background <int>Set the background color of the text range. Value is an Office color number.
-bold <bool>Set the bold font style flag of the text range.
-color <enum>Set the text color of the text range. Enumeration of type Enum::WdColorIndex.
-italic <bool>Set the italic font style flag of the text range.
-name <string>Set the font name of the text range.
-size <float>Set the font size of the text range in points.
-sizec <float>Set the font size of the text range in centimeters.
-sizei <float>Set the font size of the text range in inches.
-underline <bool>Set the underline font style flag of the text range.
-underlinecolor <enum>Set the underline color of the text range. Enumeration of type Enum::WdColor.

Returns no value.

See also: GetRangeFont, ::Cawt::GetColor

proc ::Word::SetRangeFont {rangeId args} {

    # Set font specific parameters.
    #
    # rangeId - Identifier of the text range.
    # args    - Options described below.
    #
    # -name <string>         - Set the font name of the text range.
    # -size <float>          - Set the font size of the text range in points.
    # -sizei <float>         - Set the font size of the text range in inches.
    # -sizec <float>         - Set the font size of the text range in centimeters.
    # -bold <bool>           - Set the bold font style flag of the text range.
    # -italic <bool>         - Set the italic font style flag of the text range.
    # -underline <bool>      - Set the underline font style flag of the text range.
    # -underlinecolor <enum> - Set the underline color of the text range.
    #                          Enumeration of type [Enum::WdColor].
    # -background <int>      - Set the background color of the text range.
    #                          Value is an Office color number.
    # -color <enum>          - Set the text color of the text range.
    #                          Enumeration of type [Enum::WdColorIndex].
    #
    # Returns no value.
    #
    # See also: GetRangeFont [::Cawt::GetColor]

    set font [$rangeId Font]
    foreach { key value } $args {
        if { $value eq "" } {
            error "SetRangeFont: No value specified for key \"$key\""
        }
        switch -exact -nocase -- $key {
            "-name"           { $font Name $value }
            "-size"           { $font Size $value }
            "-sizei"          { $font Size [Cawt InchesToPoints $value] }
            "-sizec"          { $font Size [Cawt CentiMetersToPoints $value] }
            "-bold"           { $font Bold [Cawt TclInt $value] }
            "-italic"         { $font Italic [Cawt TclInt $value] }
            "-underline"      { $font Underline [Cawt TclInt $value] }
            "-underlinecolor" { $font UnderlineColor [Word GetEnum $value] }
            "-background"     { $font -with { Shading } BackgroundPatternColor $value }
            "-color"          { $font ColorIndex [Word GetEnum $value] }
            default           { error "SetRangeFont: Unknown key \"$key\" specified" }
        }
    }
    Cawt Destroy $font
}

SetRangeFontBackgroundColor [::Word]Top, Main, Index

Set the background color of a text range.

SetRangeFontBackgroundColor rangeId ?args?
rangeIdIdentifier of the text range.
argsBackground color.

Color value may be specified in a format acceptable by procedure ::Cawt::GetColor, i.e. color name, hexadecimal string, Office color number or a list of 3 integer RGB values.

Returns no value.

See also: SetRangeFont, GetRangeFont

proc ::Word::SetRangeFontBackgroundColor {rangeId args} {

    # Set the background color of a text range.
    #
    # rangeId - Identifier of the text range.
    # args    - Background color.
    #
    # Color value may be specified in a format acceptable by procedure [::Cawt::GetColor],
    # i.e. color name, hexadecimal string, Office color number or a list of 3 integer
    # RGB values.
    #
    # Returns no value.
    #
    # See also: SetRangeFont GetRangeFont

    $rangeId -with { Font Shading } BackgroundPatternColor [Cawt GetColor {*}$args]
}

SetRangeFontBold [::Word]Top, Main, Index

Toggle the bold font style of a text range.

SetRangeFontBold rangeId ?onOff?
rangeIdIdentifier of the text range.
onOffIf set to true, set bold style on. Otherwise set bold style off. Optional, default true.

Returns no value.

See also: SetRangeFont, GetRangeFont

proc ::Word::SetRangeFontBold {rangeId {onOff true}} {

    # Toggle the bold font style of a text range.
    #
    # rangeId - Identifier of the text range.
    # onOff   - If set to true, set bold style on.
    #           Otherwise set bold style off.
    #
    # Returns no value.
    #
    # See also: SetRangeFont GetRangeFont

    $rangeId -with { Font } Bold [Cawt TclInt $onOff]
}

SetRangeFontColor [::Word]Top, Main, Index

Set the text color of a text range.

SetRangeFontColor rangeId color
rangeIdIdentifier of the text range.
colorValue of enumeration type Enum::WdColorIndex.

Returns no value.

See also: SetRangeFont, GetRangeFont

proc ::Word::SetRangeFontColor {rangeId color} {

    # Set the text color of a text range.
    #
    # rangeId - Identifier of the text range.
    # color   - Value of enumeration type [Enum::WdColorIndex].
    #
    # Returns no value.
    #
    # See also: SetRangeFont GetRangeFont

    $rangeId -with { Font } ColorIndex [Word GetEnum $color]
}

SetRangeFontItalic [::Word]Top, Main, Index

Toggle the italic font style of a text range.

SetRangeFontItalic rangeId ?onOff?
rangeIdIdentifier of the text range.
onOffIf set to true, set italic style on. Otherwise set italic style off. Optional, default true.

Returns no value.

See also: SetRangeFont, GetRangeFont

proc ::Word::SetRangeFontItalic {rangeId {onOff true}} {

    # Toggle the italic font style of a text range.
    #
    # rangeId - Identifier of the text range.
    # onOff   - If set to true, set italic style on.
    #           Otherwise set italic style off.
    #
    # Returns no value.
    #
    # See also: SetRangeFont GetRangeFont

    $rangeId -with { Font } Italic [Cawt TclInt $onOff]
}

SetRangeFontName [::Word]Top, Main, Index

Set the font name of a text range.

SetRangeFontName rangeId fontName
rangeIdIdentifier of the text range.
fontNameFont name.

Returns no value.

See also: SetRangeFont, GetRangeFont

proc ::Word::SetRangeFontName {rangeId fontName} {

    # Set the font name of a text range.
    #
    # rangeId  - Identifier of the text range.
    # fontName - Font name.
    #
    # Returns no value.
    #
    # See also: SetRangeFont GetRangeFont

    $rangeId -with { Font } Name $fontName
}

SetRangeFontSize [::Word]Top, Main, Index

Set the font size of a text range.

SetRangeFontSize rangeId fontSize
rangeIdIdentifier of the text range.
fontSizeFont size.

The size value may be specified in a format acceptable by procedure ::Cawt::ValueToPoints, i.e. centimeters, inches or points.

Returns no value.

See also: SetRangeFont, GetRangeFont

proc ::Word::SetRangeFontSize {rangeId fontSize} {

    # Set the font size of a text range.
    #
    # rangeId  - Identifier of the text range.
    # fontSize - Font size.
    #
    # The size value may be specified in a format acceptable by
    # procedure [::Cawt::ValueToPoints], i.e. centimeters, inches or points.
    #
    # Returns no value.
    #
    # See also: SetRangeFont GetRangeFont

    $rangeId -with { Font } Size [Cawt ValueToPoints $fontSize]
}

SetRangeFontUnderline [::Word]Top, Main, Index

Toggle the underline font style of a text range.

SetRangeFontUnderline rangeId ?onOff? ?color?
rangeIdIdentifier of the text range.
onOffIf set to true, set underline style on. Otherwise set underline style off. Optional, default true.
colorValue of enumeration type Enum::WdColor. Optional, default wdColorAutomatic.

Returns no value.

See also: SetRangeFont, GetRangeFont

proc ::Word::SetRangeFontUnderline {rangeId {onOff true} {color wdColorAutomatic}} {

    # Toggle the underline font style of a text range.
    #
    # rangeId - Identifier of the text range.
    # onOff   - If set to true, set underline style on.
    #           Otherwise set underline style off.
    # color   - Value of enumeration type [Enum::WdColor].
    #
    # Returns no value.
    #
    # See also: SetRangeFont GetRangeFont

    $rangeId -with { Font } Underline [Cawt TclInt $onOff]
    if { $onOff } {
        $rangeId -with { Font } UnderlineColor [Word GetEnum $color]
    }
}

SetRangeHighlightColorByEnum [::Word]Top, Main, Index

Set the highlight color of a text range.

SetRangeHighlightColorByEnum rangeId colorEnum
rangeIdIdentifier of the text range.
colorEnumValue of enumeration type Enum::WdColorIndex.

Returns no value.

See also: SetRangeBackgroundColorByEnum

proc ::Word::SetRangeHighlightColorByEnum {rangeId colorEnum} {

    # Set the highlight color of a text range.
    #
    # rangeId   - Identifier of the text range.
    # colorEnum - Value of enumeration type [Enum::WdColorIndex].
    #
    # Returns no value.
    #
    # See also: SetRangeBackgroundColorByEnum

    $rangeId HighlightColorIndex [Word GetEnum $colorEnum]
}

SetRangeHorizontalAlignment [::Word]Top, Main, Index

Set the horizontal alignment of a text range.

SetRangeHorizontalAlignment rangeId align
rangeIdIdentifier of the text range.
alignValue of enumeration type Enum::WdParagraphAlignment or any of the following strings: left, right, center.

Returns no value.

See also: SetCellVerticalAlignment, SetRangeHighlightColorByEnum

proc ::Word::SetRangeHorizontalAlignment {rangeId align} {

    # Set the horizontal alignment of a text range.
    #
    # rangeId - Identifier of the text range.
    # align   - Value of enumeration type [Enum::WdParagraphAlignment]
    #           or any of the following strings: `left`, `right`, `center`.
    #
    # Returns no value.
    #
    # See also: SetCellVerticalAlignment SetRangeHighlightColorByEnum

    if { $align eq "center" } {
        set alignEnum $Word::wdAlignParagraphCenter
    } elseif { $align eq "left" } {
        set alignEnum $Word::wdAlignParagraphLeft
    } elseif { $align eq "right" } {
        set alignEnum $Word::wdAlignParagraphRight
    } else {
        set alignEnum [Word GetEnum $align]
    }

    $rangeId -with { ParagraphFormat } Alignment $alignEnum
}

SetRangeMergeCells [::Word]Top, Main, Index

Merge a range of cells.

SetRangeMergeCells rangeId
rangeIdIdentifier of the cell range.

Returns no value.

See also: SetRangeHorizontalAlignment, SelectRange

proc ::Word::SetRangeMergeCells {rangeId} {

    # Merge a range of cells.
    #
    # rangeId - Identifier of the cell range.
    #
    # Returns no value.
    #
    # See also: SetRangeHorizontalAlignment SelectRange

    set appId [Office GetApplicationId $rangeId]
    Word::ShowAlerts $appId false
    $rangeId -with { Cells } Merge
    Word::ShowAlerts $appId true
    Cawt Destroy $appId
}

SetRangeStartIndex [::Word]Top, Main, Index

Set the start index of a text range.

SetRangeStartIndex rangeId index
rangeIdIdentifier of the text range.
indexIndex for the range start.

Index is either an integer value or string begin to use the start of the document.

Returns no value.

See also: SetRangeEndIndex, GetRangeStartIndex

proc ::Word::SetRangeStartIndex {rangeId index} {

    # Set the start index of a text range.
    #
    # rangeId - Identifier of the text range.
    # index   - Index for the range start.
    #
    # Index is either an integer value or string `begin` to
    # use the start of the document.
    #
    # Returns no value.
    #
    # See also: SetRangeEndIndex GetRangeStartIndex

    if { $index eq "begin" } {
        set index 0
    }
    $rangeId Start $index
}

SetRangeStyle [::Word]Top, Main, Index

Set the style of a text range.

SetRangeStyle rangeId style
rangeIdIdentifier of the text range.
styleValue of enumeration type Enum::WdBuiltinStyle. Often used values: wdStyleHeading1, wdStyleNormal.

Returns no value.

See also: SetRangeFontSize, SetRangeFontName

proc ::Word::SetRangeStyle {rangeId style} {

    # Set the style of a text range.
    #
    # rangeId - Identifier of the text range.
    # style   - Value of enumeration type [Enum::WdBuiltinStyle].
    #           Often used values: `wdStyleHeading1`, `wdStyleNormal`.
    #
    # Returns no value.
    #
    # See also: SetRangeFontSize SetRangeFontName

    set docId [Word GetDocumentId $rangeId]
    set styleId [$docId -with { Styles } Item [Word GetEnum $style]]
    $rangeId Style $styleId
    Cawt Destroy $styleId
    Cawt Destroy $docId
}

SetRowHeight [::Word]Top, Main, Index

Set the height of a table row.

SetRowHeight tableId row ?height?
tableIdIdentifier of the Word table.
rowRow number. Row numbering starts with 1.
heightA positive value specifies the row's height. A value of zero specifies that the rows's height fits automatically the height of all elements in the row. Optional, default 0.

The height value may be specified in a format acceptable by procedure ::Cawt::ValueToPoints, i.e. centimeters, inches or points.

Returns no value.

See also: SetRowValues

proc ::Word::SetRowHeight {tableId row {height 0}} {

    # Set the height of a table row.
    #
    # tableId - Identifier of the Word table.
    # row     - Row number. Row numbering starts with 1.
    # height  - A positive value specifies the row's height.
    #           A value of zero specifies that the rows's height
    #           fits automatically the height of all elements in the row.
    #
    # The height value may be specified in a format acceptable by
    # procedure [::Cawt::ValueToPoints], i.e. centimeters, inches or points.
    #
    # Returns no value.
    #
    # See also: SetRowValues

    set rowId [Word GetRowId $tableId $row]
    set height [Cawt ValueToPoints $height]
    if { $height == 0 } {
        $rowId HeightRule $::Word::wdRowHeightAuto
    } else {
        $rowId HeightRule $::Word::wdRowHeightExactly
        $rowId Height $height
    }
    Cawt Destroy $rowId
}

SetRowValues [::Word]Top, Main, Index

Insert row values from a Tcl list.

SetRowValues tableId row valList ?startCol? ?numVals?
tableIdIdentifier of the Word table.
rowRow number. Row numbering starts with 1.
valListList of values to be inserted.
startColColumn number of insertion start. Column numbering starts with 1. Optional, default 1.
numValsIf negative or zero, all list values are inserted. If positive, $numVals columns are filled with the list values (starting at list index 0). Optional, default 0.

Returns no value. If $valList is an empty list, an error is thrown.

See also: GetRowValues, SetColumnValues, SetCellValue

proc ::Word::SetRowValues {tableId row valList {startCol 1} {numVals 0}} {

    # Insert row values from a Tcl list.
    #
    # tableId  - Identifier of the Word table.
    # row      - Row number. Row numbering starts with 1.
    # valList  - List of values to be inserted.
    # startCol - Column number of insertion start. Column numbering starts with 1.
    # numVals  - If negative or zero, all list values are inserted.
    #            If positive, $numVals columns are filled with the list values
    #            (starting at list index 0).
    #
    # Returns no value. If $valList is an empty list, an error is thrown.
    #
    # See also: GetRowValues SetColumnValues SetCellValue

    set len [llength $valList]
    if { $numVals > 0 } {
        if { $numVals < $len } {
            set len $numVals
        }
    }
    set ind 0
    for { set c $startCol } { $c < [expr {$startCol + $len}] } { incr c } {
        SetCellValue $tableId $row $c [lindex $valList $ind]
        incr ind
    }
}

SetTableAlignment [::Word]Top, Main, Index

Set the alignment of a Word table.

SetTableAlignment tableId align
tableIdIdentifier of the Word table.
alignValue of enumeration type Enum::WdRowAlignment or any of the following strings: left, right, center.

Returns no value.

See also: AddTable, SetTableName, SetTableBorderLineStyle

proc ::Word::SetTableAlignment {tableId align} {

    # Set the alignment of a Word table.
    #
    # tableId - Identifier of the Word table.
    # align   - Value of enumeration type [Enum::WdRowAlignment]
    #           or any of the following strings: `left`, `right`, `center`.
    #
    # Returns no value.
    #
    # See also: AddTable SetTableName SetTableBorderLineStyle

    if { $align eq "center" } {
        set alignEnum $Word::wdAlignRowCenter
    } elseif { $align eq "left" } {
        set alignEnum $Word::wdAlignRowLeft
    } elseif { $align eq "right" } {
        set alignEnum $Word::wdAlignRowRight
    } else {
        set alignEnum [Word GetEnum $align]
    }
    $tableId -with { Rows } Alignment $alignEnum
}

SetTableBorderLineStyle [::Word]Top, Main, Index

Set the border line styles of a Word table or cell range.

SetTableBorderLineStyle tableOrRangeId ?outsideLineStyle? ?insideLineStyle?
tableOrRangeIdIdentifier of the Word table or cell range.
outsideLineStyleOutside border style. Optional, default wdLineStyleSingle.
insideLineStyleInside border style. Optional, default wdLineStyleSingle.

The values of $outsideLineStyle and $insideLineStyle must be of enumeration type Enum::WdLineStyle (see WordConst.tcl).

Returns no value.

See also: AddTable, SetTableBorderLineWidth, GetCellRange

proc ::Word::SetTableBorderLineStyle {tableOrRangeId {outsideLineStyle wdLineStyleSingle} {insideLineStyle wdLineStyleSingle}} {

    # Set the border line styles of a Word table or cell range.
    #
    # tableOrRangeId   - Identifier of the Word table or cell range.
    # outsideLineStyle - Outside border style.
    # insideLineStyle  - Inside border style.
    #
    # Returns no value.
    #
    # The values of $outsideLineStyle and $insideLineStyle must
    # be of enumeration type [Enum::WdLineStyle] (see WordConst.tcl).
    #
    # See also: AddTable SetTableBorderLineWidth GetCellRange

    set border [$tableOrRangeId Borders]
    $border OutsideLineStyle [Word GetEnum $outsideLineStyle]
    $border InsideLineStyle  [Word GetEnum $insideLineStyle]
    Cawt Destroy $border
}

SetTableBorderLineWidth [::Word]Top, Main, Index

Set the border line widths of a Word table or cell range.

SetTableBorderLineWidth tableOrRangeId ?outsideLineWidth? ?insideLineWidth?
tableOrRangeIdIdentifier of the Word table or cell range.
outsideLineWidthOutside border line width. Optional, default wdLineWidth050pt.
insideLineWidthInside border line width. Optional, default wdLineWidth050pt.

The values of $outsideLineWidth and $insideLineWidth must be of enumeration type Enum::WdLineWidth (see WordConst.tcl).

Returns no value.

See also: AddTable, SetTableBorderLineStyle, GetCellRange

proc ::Word::SetTableBorderLineWidth {tableOrRangeId {outsideLineWidth wdLineWidth050pt} {insideLineWidth wdLineWidth050pt}} {

    # Set the border line widths of a Word table or cell range.
    #
    # tableOrRangeId   - Identifier of the Word table or cell range.
    # outsideLineWidth - Outside border line width.
    # insideLineWidth  - Inside border line width.
    #
    # Returns no value.
    #
    # The values of $outsideLineWidth and $insideLineWidth must
    # be of enumeration type [Enum::WdLineWidth] (see WordConst.tcl).
    #
    # See also: AddTable SetTableBorderLineStyle GetCellRange

    set border [$tableOrRangeId Borders]
    $border OutsideLineWidth [Word GetEnum $outsideLineWidth]
    $border InsideLineWidth  [Word GetEnum $insideLineWidth]
    Cawt Destroy $border
}

SetTableName [::Word]Top, Main, Index

Set the name of a table.

SetTableName tableId name
tableIdIdentifier of the Word table.
nameName of the table.

Note: Table names are supported since Word 2010. If your Word version is older, an error is thrown. Setting the table name also does not work, if using a Word version greater than 2010, but working with a document in old .doc format.

Returns no value.

See also: GetTableName, GetNumTables, AddTable

proc ::Word::SetTableName {tableId name} {

    # Set the name of a table.
    #
    # tableId - Identifier of the Word table.
    # name    - Name of the table.
    #
    # Returns no value.
    #
    # **Note:**
    # Table names are supported since Word 2010.
    # If your Word version is older, an error is thrown.
    # Setting the table name also does not work, if using
    # a Word version greater than 2010, but working with a
    # document in old `.doc` format.
    #
    # See also: GetTableName GetNumTables AddTable

    variable wordVersion

    if { $wordVersion < 14.0 } {
        error "Table names available only in Word 2010 or newer. Running [Word GetVersion $tableId true]."
    }
    $tableId Title $name
}

SetTableOptions [::Word]Top, Main, Index

Set miscellaneous table options.

SetTableOptions tableId ?args?
tableIdIdentifier of the Word table.
argsOptions described below.
-autofit <bool>Allow Word to automatically resize cells in a table to fit their contents.
-bottom <size>Set the amount of space to add below the contents of a single cell or all the cells in a table.
-left <size>Set the amount of space to add to the left of the contents of all the cells in a table.
-right <size>Set the amount of space to add to the right of the contents of all the cells in a table.
-spacing <size>Set the spacing between the cells in a table.
-top <size>Set the amount of space to add above the contents of all the cells in a table.
-width <size>Set the preferred width of a table. The width can also be specified in percent, ex. 50%.

The size values may be specified in a format acceptable by procedure ::Cawt::ValueToPoints, i.e. centimeters, inches or points.

If both -autofit and -width are specified, the last specified option takes precedence.

Returns no value.

See also: SetTableName, SetTableAlignment

proc ::Word::SetTableOptions {tableId args} {

    # Set miscellaneous table options.
    #
    # tableId - Identifier of the Word table.
    # args    - Options described below.
    #
    # -bottom <size>  - Set the amount of space to add below the contents of a
    #                   single cell or all the cells in a table.
    # -left <size>    - Set the amount of space to add to the left of the
    #                   contents of all the cells in a table.
    # -right <size>   - Set the amount of space to add to the right of the
    #                   contents of all the cells in a table.
    # -top <size>     - Set the amount of space to add above the contents
    #                   of all the cells in a table.
    # -spacing <size> - Set the spacing between the cells in a table.
    # -autofit <bool> - Allow Word to automatically resize cells in a table
    #                   to fit their contents.
    # -width <size>   - Set the preferred width of a table.
    #                   The width can also be specified in percent, ex. `50%`.
    #
    # The size values may be specified in a format acceptable by
    # procedure [::Cawt::ValueToPoints], i.e. centimeters, inches or points.
    #
    # If both `-autofit` and `-width` are specified, the last specified
    # option takes precedence.
    #
    # Returns no value.
    #
    # See also: SetTableName SetTableAlignment

    foreach { key value } $args {
        if { $value eq "" } {
            error "SetTableOptions: No value specified for key \"$key\""
        }
        switch -exact -nocase -- $key {
            "-bottom"  { $tableId BottomPadding [Cawt ValueToPoints $value] }
            "-left"    { $tableId LeftPadding   [Cawt ValueToPoints $value] }
            "-right"   { $tableId RightPadding  [Cawt ValueToPoints $value] }
            "-top"     { $tableId TopPadding    [Cawt ValueToPoints $value] }
            "-spacing" { $tableId Spacing       [Cawt ValueToPoints $value] }
            "-autofit" {
                         if { $value } {
                             $tableId -with { Columns } AutoFit
                         }
                       }
            "-width"   {
                           if { [string match "*%" $value] } {
                               scan $value "%f" percent
                               $tableId PreferredWidthType $Word::wdPreferredWidthPercent
                               $tableId PreferredWidth $percent
                           } else {
                               $tableId PreferredWidthType $Word::wdPreferredWidthPoints
                               $tableId PreferredWidth [Cawt ValueToPoints $value]
                           }
                       }
            default    { error "SetTableOptions: Unknown key \"$key\" specified" }
        }
    }
}

SetTableVerticalAlignment [::Word]Top, Main, Index

Set the vertical alignment of all Word table cells.

SetTableVerticalAlignment tableId align
tableIdIdentifier of the Word table.
alignValue of enumeration type Enum::WdCellVerticalAlignment or any of the following strings: top, bottom, center.

Returns no value.

See also: SetTableOptions, SetCellVerticalAlignment

proc ::Word::SetTableVerticalAlignment {tableId align} {

    # Set the vertical alignment of all Word table cells.
    #
    # tableId - Identifier of the Word table.
    # align   - Value of enumeration type [Enum::WdCellVerticalAlignment]
    #           or any of the following strings: `top`, `bottom`, `center`.
    #
    # Returns no value.
    #
    # See also: SetTableOptions SetCellVerticalAlignment

    if { $align eq "center" } {
        set alignEnum $Word::wdCellAlignVerticalCenter
    } elseif { $align eq "top" } {
        set alignEnum $Word::wdCellAlignVerticalTop
    } elseif { $align eq "bottom" } {
        set alignEnum $Word::wdCellAlignVerticalBottom
    } else {
        set alignEnum [Word GetEnum $align]
    }

    $tableId Select
    set selectId [$tableId -with { Application } Selection]
    $selectId -with { Cells } VerticalAlignment $alignEnum
    Cawt Destroy $selectId
}

SetViewParameters [::Word]Top, Main, Index

Set view parameters of a document.

SetViewParameters docId ?args?
docIdIdentifier of the document.
argsOptions described below.
-pagefit <enum>Set the page fit parameter. Value of enumeration type Enum::WdPageFit.

Returns no value.

See also: OpenDocument, SetPageSetup

proc ::Word::SetViewParameters {docId args} {

    # Set view parameters of a document.
    #
    # docId - Identifier of the document.
    # args  - Options described below.
    #
    # -pagefit <enum> - Set the page fit parameter.
    #                   Value of enumeration type [Enum::WdPageFit].
    #
    # Returns no value.
    #
    # See also: OpenDocument SetPageSetup

    foreach { key value } $args {
        if { $value eq "" } {
            error "SetViewParameters: No value specified for key \"$key\""
        }
        switch -exact -nocase -- $key {
            "-pagefit" {
                $docId -with { ActiveWindow ActivePane View Zoom }  PageFit [Word GetEnum $value]
            }
            default {
                error "SetViewParameters: Unknown key \"$key\" specified"
            }
        }
    }
}

ShowAlerts [::Word]Top, Main, Index

Toggle the display of Word application alerts.

ShowAlerts appId onOff
appIdThe application identifier.
onOffSwitch the alerts on or off.

Returns no value.

proc ::Word::ShowAlerts {appId onOff} {

    # Toggle the display of Word application alerts.
    #
    # appId - The application identifier.
    # onOff - Switch the alerts on or off.
    #
    # Returns no value.

    if { $onOff } {
        set alertLevel [expr $Word::wdAlertsAll]
    } else {
        set alertLevel [expr $Word::wdAlertsNone]
    }
    $appId DisplayAlerts $alertLevel
}

ToggleSpellCheck [::Word]Top, Main, Index

Toggle checking of grammatical and spelling errors.

ToggleSpellCheck appId onOff
appIdIdentifier of the Word instance.
onOffSwitch spell checking on or off.

Returns no value.

See also: Open

proc ::Word::ToggleSpellCheck {appId onOff} {

    # Toggle checking of grammatical and spelling errors.
    #
    # appId - Identifier of the Word instance.
    # onOff - Switch spell checking on or off.
    #
    # Returns no value.
    #
    # See also: Open

    $appId -with { ActiveDocument } ShowGrammaticalErrors [Cawt TclBool $onOff]
    $appId -with { ActiveDocument } ShowSpellingErrors    [Cawt TclBool $onOff]
}

TrimString [::Word]Top, Main, Index

Trim a string.

TrimString str
strString to be trimmed.

The string is trimmed from the left and right side. Trimmed characters are whitespaces. Additionally the following control characters are converted: 0xD to "\n", 0x7 to " ".

Returns the trimmed string.

See also: GetCellValue

proc ::Word::TrimString {str} {

    # Trim a string.
    #
    # str - String to be trimmed.
    #
    # The string is trimmed from the left and right side.
    # Trimmed characters are whitespaces.
    # Additionally the following control characters are converted:
    # `0xD` to `"\n"`, `0x7` to `" "`.
    #
    # Returns the trimmed string.
    #
    # See also: GetCellValue

    set str [string map [list [format %c 0xD] \n  [format %c 0x7] " "] $str]
    return [string trim $str]
}

UpdateFields [::Word]Top, Main, Index

Update all fields as well as tables of content and figures of a document.

UpdateFields docId
docIdIdentifier of the document.

Returns no value.

See also: SaveAs

proc ::Word::UpdateFields {docId} {

    # Update all fields as well as tables of content and figures of a document.
    #
    # docId - Identifier of the document.
    #
    # Returns no value.
    #
    # See also: SaveAs

    set stories [$docId StoryRanges]
    $stories -iterate story {
        lappend storyList $story
        $story -with { Fields } Update
        set nextStory [$story NextStoryRange]
        while { [Cawt IsComObject $nextStory] } {
            lappend storyList $nextStory
            $nextStory -with { Fields } Update
            set nextStory [$nextStory NextStoryRange]
        }
    }
    foreach story $storyList {
        Cawt Destroy $story
    }
    Cawt Destroy $stories

    set tocs [$docId TablesOfContents]
    $tocs -iterate toc {
        $toc Update
        Cawt Destroy $toc
    }
    Cawt Destroy $tocs

    set tofs [$docId TablesOfFigures]
    $tofs -iterate tof {
        $tof Update
        Cawt Destroy $tof
    }
    Cawt Destroy $tofs
}

Visible [::Word]Top, Main, Index

Toggle the visibility of a Word application window.

Visible appId visible
appIdIdentifier of the Word instance.
visibleIf set to true, show the application window. Otherwise hide the application window.

Returns no value.

See also: Open, OpenNew, IsVisible

proc ::Word::Visible {appId visible} {

    # Toggle the visibility of a Word application window.
    #
    # appId   - Identifier of the Word instance.
    # visible - If set to true, show the application window.
    #           Otherwise hide the application window.
    #
    # Returns no value.
    #
    # See also: Open OpenNew IsVisible

    $appId Visible [Cawt TclInt $visible]
}