Jump to content

Insert a comment with custom presets

From The Document Foundation Wiki


Description

This tutorial covers how to write a macro for Writer that inserts a custom comment at the cursor position (in order to for example preset the Author and/or Date fields).

We use com.sun.star.text.XTextViewCursor[1] and com.sun.star.text.textfield.Annotation services[2] as well as the com.sun.star.util.DateTime structure[3] to obtain a time-stamp from the time of execution.

Code

The following macro, which could for instance be linked with a keyboard shortcut, inserts a custom comment at the current cursor position:

Option Explicit

Sub InsertComment
    '''Insert a comment at position of cursor'''

    Dim oCurs As Object ' com.sun.star.text.text.XTextViewCursor
    Dim oAnnot As Object ' com.sun.star.text.textfield.Annotation
    Dim oDateTime As New com.sun.star.util.DateTime

    oCurs = ThisComponent.CurrentController.getViewCursor()
    oAnnot = ThisComponent.createInstance( _
        "com.sun.star.text.textfield.Annotation")

    With oDateTime ' com.sun.star.util.DateTime
        .Minutes = 20
        .Hours = 12
        .Day = 20
        .Month = 12
        .Year = 2012
    End With
   
    With oAnnot ' com.sun.star.text.textfield.Annotation
        .Author = "Author of the comment"
        .Content = "Content of the comment"
        .DateTimeValue = oDateTime
    End With

    oAnnot.attach(oCurs.Start) ' Insert at cursor start

End Sub ' InsertComment

Using Python:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import uno

def InsertComment():
    """Insert a comment at position of cursor
    
    curs    com.sun.star.text.text.XTextViewCursor
    annot   com.sun.star.text.textfield.Annotation
    """
    dt = uno.createUnoStruct("com.sun.star.util.DateTime")

    thisComponent = XSCRIPTCONTEXT.getDocument()
    curs = thisComponent.CurrentController.getViewCursor()
    annot = thisComponent.createInstance(
        "com.sun.star.text.textfield.Annotation")

    dt.Minutes = 20
    dt.Hours = 12
    dt.Day = 20
    dt.Month = 12
    dt.Year = 2012

    annot.Author = "Author of the Comment"
    annot.Content = 'Content of the comment'
    annot.DateTimeValue = dt

    annot.attach(curs.Start)  # Insert at cursor start

Time-stamp calculation is not performed in these examples.

Notes