Paste unformatted text from the clipboard without linebreaks or styling

From The Document Foundation Wiki
< Macros‎ | Writer
Jump to navigation Jump to search
Other languages:
English • ‎español • ‎français • ‎italiano


This macro pastes content from the clipboard as unformatted texts after removing the linebreaks and styling. To use this macro in an efficient way, you can add a keyboard short cut for the sub InsertClipboardTextInWriter() at Extras ▸ Customize: keyboard.

To paste only unformatted text from the clipboard you can use the general macro getClipboardText().


' Copyright (c) 2011 Frieder Delor, Mailto:
'    This program is free software: you can redistribute it and/or modify
'    it under the terms of the GNU General Public License as published by
'    the Free Software Foundation, either version 3 of the License, or
'    (at your option) any later version.
'    This program is distributed in the hope that it will be useful,
'    but WITHOUT ANY WARRANTY; without even the implied warranty of
'    GNU General Public License for more details.
'    You should have received a copy of the GNU General Public License
'    along with this program.  If not, see <>.

Option Explicit

Sub InsertClipboardTextInWriter()
    Dim sText As String
    sText= (getClipboardText)
    sText = Replace (sText,Chr(10)," ") ' Replace line breaks with white spaces
    sText = Replace (sText,Chr(13)," ") ' Replace paragraph breaks with white spaces
    WriteCursorPosition(sText) ' Paste in Writer
End Sub ' InsertClipboardTextInWriter

Sub WriteCursorPosition(sText as String)
    '''This sub is taken from'''
    '''Paste text in Writer at the position of the cursor'''

    Dim oViewCursor As Object '
    Dim oText As Object
    oViewCursor = ThisComponent.GetCurrentController.ViewCursor
    If IsEmpty(oViewCursor.Cell) Then
        oText = ThisComponent.text
        oText = oViewCursor.Cell.Text
    End If
    oText.insertString(oViewCursor, sText, false)

End Sub ' WriteCursorPosition

Function getClipboardText() As String
    '''Returns a string of the current clipboard text'''

    Dim oClip As Object '
    Dim oConverter As Object '
    Dim oClipContents As Object
    Dim oTypes As Object
    Dim i%

    oClip = createUnoService("")
    oConverter = createUnoService("")
    On Error Resume Next
    oClipContents = oClip.getContents
    oTypes = oClipContents.getTransferDataFlavors

    For i = LBound(oTypes) To UBound(oTypes)
        If oTypes(i).MimeType = "text/plain;charset=utf-16" Then
            Exit For
        End If

    If (i >= 0) Then
        On Error Resume Next
        getClipboardText = oConverter.convertToSimpleType _
    End If

End Function ' getClipboardText

ODT file to test macro