Testing scripts

You know, of course, about the Scripting Plugin for OmegaT. If you’re a member of OmegaT Yahoo user group, you may know Yu Tang who provided a bunch of nice scripts to open various files and folders of the currently active OmegaT project. His scripts have been included in the most recent version of the Scripting Plugin. The only problem with them was that one needed to edit them if they were used on OS’es other than MS Windows. Generally not a problem, as many OmegaT users are quite computer savvy, but it would be nicer if they could work everywhere “out of box”.

Yu Tang has updated the scripts so now they check which OS they are running on. If you’re willing to test them out and report any possible problems, please do.

The scripts are listed here and posted on the Pastebin.com with the link to each individual script right before the respective listing.

  1. open_current_file.groovy
    /*
    * Open current file
    *
    * @author Yu Tang
    * @date 2013-05-23
    * @version 0.2
    */
    
    import static javax.swing.JOptionPane.*
    import static org.omegat.util.Platform.*
    
    // abort if a project is not opened yet
    def prop = project.projectProperties
    if (!prop) {
    final def title = 'open current file'
    final def msg = 'Please try again after you open a project.'
    showMessageDialog null, msg, title, INFORMATION_MESSAGE
    return
    }
    
    // get command GString to open a file
    def file = prop.sourceRoot + editor.currentFile
    def command
    switch (osType) {
    case [OsType.WIN64, OsType.WIN32]:
    command = "cmd /c start \"\" \"$file\"" // for WinNT
    // command = "command /c start \"\" \"$file\"" // for Win9x or WinME
    break
    case [OsType.MAC64, OsType.MAC32]:
    command = "open \"$file\""
    break
    default: // for Linux or others
    command = ['xdg-open', file]
    break
    }
    
    // open it
    command.execute()
    
  2. open_folder.groovy
    /*
     *  Open project folder
     *
     * @author  Yu Tang
     * @date    2013-05-23
     * @version 0.2
     */
    
    import static javax.swing.JOptionPane.*
    import static org.omegat.util.Platform.*
    
    // abort if a project is not opened yet
    def prop = project.projectProperties
    if (!prop) {
      final def title = 'open project folder'
      final def msg   = 'Please try again after you open a project.'
      showMessageDialog null, msg, title, INFORMATION_MESSAGE
      return
    }
    
    // get command GString to open a folder
    def folder = prop.projectRoot
    def command
    switch (osType) {
      case [OsType.WIN64, OsType.WIN32]:
        command = "explorer.exe \"$folder\""
        break
      case [OsType.MAC64, OsType.MAC32]:
        command = "open \"$folder\""
        break
      default:  // for Linux or others
        command = ['xdg-open', folder]
        break
    }
    
    // open it
    command.execute()
    
  3. open_glossary.groovy
    /*
     *  Open the writeable glossary in an editor
     *
     * @author  Yu Tang
     * @date    2013-05-23
     * @version 0.2
     */
    
    import static javax.swing.JOptionPane.*
    import static org.omegat.util.Platform.*
    
    /**
     * Uncomment the next line if you want to set a default text editor
     * that will open glossary file
     */
    // def textEditor = /path to your editor/
    // E.g., /TextMate/
    // /C:\Program Files (x86)\editor\editor.exe/
    // ['x-terminal-emulator', '-e', 'vi']
    
    // make a Closure to show message dialog
    def showMessage = { msg -> showMessageDialog null, msg, 'Open glossary', INFORMATION_MESSAGE }
    
    // abort if a project is not opened yet
    def prop = project.projectProperties
    if (!prop) {
      showMessage 'Please try again after you open a project.'
      return
    }
    
    // exit if file not found
    def file = prop.writeableGlossary
    if (! new File(file).exists()) {
      showMessage 'Glossary file not found.'
      return
    }
    
    // get command GString list to open a file
    def command
    switch (osType) {
      case [OsType.WIN64, OsType.WIN32]:
        command = "cmd /c start \"\" \"$file\""  // default
        try { command = textEditor instanceof List ? [*textEditor, file] : "\"$textEditor\" \"$file\"" } catch (ignore) {}
        break
      case [OsType.MAC64, OsType.MAC32]:
        command = "open \"$file\""  // default
        try { command = textEditor instanceof List ? [*textEditor, file] : "open -a \"$textEditor\" \"$file\"" } catch (ignore) {}
        break
      default:  // for Linux or others
        command = ['xdg-open', file] // default
        try { command = textEditor instanceof List ? [*textEditor, file] : [textEditor, file] } catch (ignore) {}
        break
    }
    
    // open it
    console.println "command: $command"
    command.execute()
    
  4. open_project_save.groovy
    /*
     *  Open project_save.tmx in an editor
     *
     * @author  Yu Tang
     * @date    2013-05-23
     * @version 0.2
     */
    
    import static javax.swing.JOptionPane.*
    import static org.omegat.util.Platform.*
    
    /**
     * Uncomment the next line if you want to set a default text editor
     * that will open project_save.tmx
     */
    // def textEditor = /path to your editor/
    // E.g., /TextMate/
    // /C:\Program Files (x86)\editor\editor.exe/
    // ['x-terminal-emulator', '-e', 'vi']
    // "x-terminal-emulator -e vi".split()
    
    // abort if a project is not opened yet
    def prop = project.projectProperties
    if (!prop) {
      final def title = 'open project_save.tmx'
      final def msg   = 'Please try again after you open a project.'
      showMessageDialog null, msg, title, INFORMATION_MESSAGE
      return
    }
    
    // get command GString list to open a file
    def file = "${prop.projectInternal}project_save.tmx" 
    def command
    switch (osType) {
      case [OsType.WIN64, OsType.WIN32]:
        command = "cmd /c start \"\" \"$file\""  // default
        try { command = textEditor instanceof List ? [*textEditor, file] : "\"$textEditor\" \"$file\"" } catch (ignore) {}
        break
      case [OsType.MAC64, OsType.MAC32]:
        command = "open \"$file\""  // default
        try { command = textEditor instanceof List ? [*textEditor, file] : "open -a \"$textEditor\" \"$file\"" } catch (ignore) {}
        break
      default:  // for Linux or others
        command = ['xdg-open', file] // default
        try { command = textEditor instanceof List ? [*textEditor, file] : [textEditor, file] } catch (ignore) {}
        break
    }
    
    // open it
    console.println "command: $command"
    command.execute()
    
  5. open_tm_folder.groovy
    /*
     *  Open the /tm folder
     *
     * @author  Yu Tang
     * @date    2013-05-23
     * @version 0.2
     */
    
    import static javax.swing.JOptionPane.*
    import static org.omegat.util.Platform.*
    
    // abort if a project is not opened yet
    def prop = project.projectProperties
    if (!prop) {
      final def title = 'open TM folder'
      final def msg   = 'Please try again after you open a project.'
      showMessageDialog null, msg, title, INFORMATION_MESSAGE
      return
    }
    
    // get command GString to open a folder
    def folder = prop.TMRoot
    def command
    switch (osType) {
      case [OsType.WIN64, OsType.WIN32]:
        command = "explorer.exe \"$folder\""
        break
      case [OsType.MAC64, OsType.MAC32]:
        command = "open \"$folder\""
        break
      default:  // for Linux or others
        command = ['xdg-open', folder]
        break
    }
    
    // open it
    command.execute()
    

To test, put the scripts to other scripts that come with the Scripting Plugin and run them on a real or testing OmegaT projects. Among the things to check are: ability to run at all, ability to run when the filenames or path to the projects contain spaces and “special” characters.
You can post your findings in comments, or, if you’re so inclined, here (clickable)


UPDATE

Thanks to all who participated in testing, now shiny new scripts got included in a new release of the Scripting Plugin for OmegaT 2.6, and as an integral part of new OmegaT 3.0. Pretty cool, yeah?

Новая версия OmegaT 3.0.0

Уважаемое сообщество!
Состоялся выпуск последней версии (3.0.0) программы OmegaT. Для работы программы требуется Java версии 6 или выше, при этом требованием для стандартной версии 2.6.3 является Java 5 или выше.

В новой версии была изменена лицензия. Ранее OmegaT выпускалась под лицензией GPLv2, однако OmegaT 3 выпущена под лицензией GPLv3: http://www.gnu.org/licenses/gpl-3.0.en.html
По сравнению с версией 2.6.3 в версии 3.0.0 содержится 27 улучшений и 5 исправлений ошибок.

Благодаря переходу на новую лицензию непосредственно в саму программу были включены токенайзеры (с автоматическим определением необходимых анализаторов для загруженного проекта — теперь не нужно указывать токенайзеры в параметрах запуска) и LanguageTool (средство для проверки грамматики). В предыдущих версиях OmegaT этот функционал был реализован только в виде плагинов. Данное изменение позволило включить эти две функции и в версию Java WebStart.

Для работы OmegaT 3 ранее установленные плагины токенайзеров и LanguageTool должны быть удалены.

Улучшения коснулись трех важных аспектов работы OmegaT.

Улучшенная работа с тегами.
Теги теперь защищены от изменений (такое поведение можно отключить). Кроме того, OmegaT теперь умеет правильно работать с защищенными тегами (которые обычно не могут быть изменены) в фильтре XLIFF.

Теги обрабатываются так же, как слова, благодаря чему их стало легче выделять и перемещать.

Новые параметры позволяют вставлять недостающие теги в текущем сегменте. В окне проверки тегов более четко показываются проблемы, появилась возможность автоматического исправления ошибок тегов. Помимо этого, проверка тегов может производиться после каждого сегмента. Есть возможность запретить создание переведенных документов при наличии ошибок тегов.

Для фильтров XML OmegaT появляется всплывающая подсказка, в которой отображается полное содержание тега при наведении на него указателя мыши.

Улучшения взаимного соответствия между XLIFF и TMX

Для обеспечения лучшего соответствия между XLIFF и TMX был полностью изменен способ вычисления тегов в фильтре XLIFF. Содержимое с тегами теперь должно давать теперь одинаковые сокращение тегов как в файле XLIFF, так и в файле TMX. Поскольку фильтр XLIFF был значительно переработан, то в него был добавлен параметр «совместимость с версией 2.6», которая позволяет использовать новую версию без необходимости проверки тегов в существующих переводах.

Помимо упомянутого выше, несколько глобальных параметров файловых фильтров позволяют добиться большего соответствия: теперь появилась возможность выбрать, будут ли удаляться начальные и конечные теги, будут ли удалятся начальные и конечные пробелы в несегментированных проектах (удобно при работе с предварительно сегментированным содержанием), а также будут ли сохраняться пробелы во всех тегах. Эти параметры применимы и к фильтрам OmegaT для файлов XML и HTML.

Новые параметры поиска
Теперь есть возможность искать в памяти, в файлах памяти переводов и в глоссариях одновременно или по отдельности, а также производить поиск только в переведенных сегментах

OmegaT теперь может работать с системой машинного перевода MyMemory.

Список последних изменений сейчас можно прочитать непосредственно в OmegaT, в меню Помощь > Последние изменения

Для версии 3.0.0 былы обновлены локализации на баскском, португальском (Бразилия), голландском, русском и турецком языках.

Новую версию программы можно загрузить, следуя инструкциям относительно последней версии по адресу: http://www.omegat.org/en/downloads.html.

Пожертвования приветствуются: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=9UB6Y2BBF99LL
С наилучшими пожеланиями

Didier Briel
перевод Кос(ть) Иванцов