SearchAndReplace.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright (c) 2017 Ghostkeeper
  2. # The PostProcessingPlugin is released under the terms of the AGPLv3 or higher.
  3. import re #To perform the search and replace.
  4. from ..Script import Script
  5. class SearchAndReplace(Script):
  6. """Performs a search-and-replace on all g-code.
  7. Due to technical limitations, the search can't cross the border between
  8. layers.
  9. """
  10. def getSettingDataString(self):
  11. return """{
  12. "name": "Search and Replace",
  13. "key": "SearchAndReplace",
  14. "metadata": {},
  15. "version": 2,
  16. "settings":
  17. {
  18. "search":
  19. {
  20. "label": "Search",
  21. "description": "All occurrences of this text will get replaced by the replacement text.",
  22. "type": "str",
  23. "default_value": ""
  24. },
  25. "replace":
  26. {
  27. "label": "Replace",
  28. "description": "The search text will get replaced by this text.",
  29. "type": "str",
  30. "default_value": ""
  31. },
  32. "is_regex":
  33. {
  34. "label": "Use Regular Expressions",
  35. "description": "When enabled, the search text will be interpreted as a regular expression.",
  36. "type": "bool",
  37. "default_value": false
  38. }
  39. }
  40. }"""
  41. def execute(self, data):
  42. search_string = self.getSettingValueByKey("search")
  43. if not self.getSettingValueByKey("is_regex"):
  44. search_string = re.escape(search_string) #Need to search for the actual string, not as a regex.
  45. search_regex = re.compile(search_string)
  46. replace_string = self.getSettingValueByKey("replace")
  47. for layer_number, layer in enumerate(data):
  48. data[layer_number] = re.sub(search_regex, replace_string, layer) #Replace all.
  49. return data