InsertText.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Example python script for the scripting framework
  2. #
  3. # This file is part of the LibreOffice project.
  4. #
  5. # This Source Code Form is subject to the terms of the Mozilla Public
  6. # License, v. 2.0. If a copy of the MPL was not distributed with this
  7. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  8. #
  9. # This file incorporates work covered by the following license notice:
  10. #
  11. # Licensed to the Apache Software Foundation (ASF) under one or more
  12. # contributor license agreements. See the NOTICE file distributed
  13. # with this work for additional information regarding copyright
  14. # ownership. The ASF licenses this file to you under the Apache
  15. # License, Version 2.0 (the "License"); you may not use this file
  16. # except in compliance with the License. You may obtain a copy of
  17. # the License at http://www.apache.org/licenses/LICENSE-2.0 .
  18. #
  19. def InsertText(text):
  20. """Inserts the argument string into the current document.
  21. If there is a selection, the selection is replaced by it.
  22. """
  23. # Get the doc from the scripting context which is made available to
  24. # all scripts.
  25. desktop = XSCRIPTCONTEXT.getDesktop()
  26. model = desktop.getCurrentComponent()
  27. # Check whether there's already an opened document.
  28. if not hasattr(model, "Text"):
  29. return
  30. # The context variable is of type XScriptContext and is available to
  31. # all BeanShell scripts executed by the Script Framework
  32. xModel = XSCRIPTCONTEXT.getDocument()
  33. # The writer controller impl supports the css.view.XSelectionSupplier
  34. # interface.
  35. xSelectionSupplier = xModel.getCurrentController()
  36. # See section 7.5.1 of developers' guide
  37. xIndexAccess = xSelectionSupplier.getSelection()
  38. count = xIndexAccess.getCount()
  39. if count >= 1: # ie we have a selection
  40. i = 0
  41. while i < count:
  42. xTextRange = xIndexAccess.getByIndex(i)
  43. theString = xTextRange.getString()
  44. if not len(theString):
  45. # Nothing really selected, just insert.
  46. xText = xTextRange.getText()
  47. xWordCursor = xText.createTextCursorByRange(xTextRange)
  48. xWordCursor.setString(text)
  49. xSelectionSupplier.select(xWordCursor)
  50. else:
  51. # Replace the selection.
  52. xTextRange.setString(text)
  53. xSelectionSupplier.select(xTextRange)
  54. i += 1
  55. def InsertHello(event=None):
  56. # Calls the InsertText function to insert the "Hello" string
  57. InsertText("Hello")
  58. # Make InsertHello visible by the Macro Selector
  59. g_exportedScripts = (InsertHello, )