Git для документов word

Внимание! Статья переведена автопереводчиком и предназначена для собственных нужд. Если есть интерес, рекомендую читать оригинал (ссылка в конце статьи).

Одним из основных проблем в процессе написания журнальной статьи — это отслеживание версий: создание, прогресс и изменения, сделанные вашими сотрудниками.

Для большинства ученых Microsoft Word пишет по умолчанию инструмент, и это как очень хороший и очень плохо в этом.

Очень хорошо, потому что особенность изменения дает это легко увидеть, что изменилось с момента последней версии, а кто сделал изменения.

Очень плохо, потому что эта функция строится вокруг одного документа Word, так что только один человек может работать на над рукописью в то время.

Это, как правило, означает отправку рукописи по электронной почте, и нужно быть очень осторожным, чтобы не  путать разные версии документа, которая требует творчества .

Подходы к преодолению этих проблем предлагают:

  1. интегрировать документы Word, в инструменты для совместной работы, такие как Sharepoint и Office 365, или документ, файлообменников, таких как Dropbox и Google Docs (если вы используете его для этого), или
  2. использует различные авторинга инструмент в целом.
  3. Если ни один из этих подходов работает для вас, у вас есть третий вариант: использовать систему контроля версий Git .

Git является программным обеспечением, которое помогает отслеживать изменения в файлах, так что вы можете вспомнить конкретные версии позже.

Git, как правило, используется для отслеживания изменений исходного кода программного обеспечения (и был первоначально разработан Linus Torvalds для разработки ядра Linux в 2005 году), но на самом деле он может быть использован для любого файла, в котором мы хотите отслеживать версии с течением времени.

Git — это программное обеспечение с открытым исходным кодом, которая работает на локальном компьютере, поэтому, поэтому есть все основания попробовать  и начать отслеживать изменения в ваших рукописях (или других сложных документах) с Git.

Каждый раз, когда вы хотите сохранить версию, не Git совершить с небольшим описанием и дополнительной метки.

Такой подход не является идеальным, так как Git был написан с исходным кодом в текстовом формате в виду, и, например, не понимает, что изменилось между двумя ревизиями документа Word.

Некоторые люди скажут вам, чтобы никогда не надо хранить двоичные файлы в системе контроля версий, но не следует слушать их.

Вместо этого нужно дать Git инструмент для преобразования документов Word в обычный текст и Git будет счастливо сказать вам, что изменилось между версиями.

Некоторые инструменты могут сделать это, но, поскольку ранее в этом месяце Pandoc может читать документы Word в DOCX формате.

Сделайте следующее, чтобы Pandoc конвертировал документы Word и сравнить изменения от слова, а не от линии (что делает больше смысла):

# .gitattributes file in root folder of your git project
*.docx diff=pandoc
# .gitconfig file in your home folder
[diff "pandoc"]
  textconv=pandoc --to=markdown
  prompt = false
[alias]
  wdiff = diff --word-diff=color --unified=1

Вы можете использовать Git wdiff important_file.docx чтобы увидеть изменения (с ударениями в красном цвете  и вставок в зеленом), или Git войти -p —word дифференциала = цвет important_file.docx , чтобы увидеть все изменения с течением времени.

Хотя теперь вы можете отслеживать изменения документа Word, и увидеть изменения, вы также хотите, чтобы иметь возможность объединить различные версии документа Word, вместе с тем, что вы и ваши сотрудники могут работать над рукописью параллельно.

Git не может объединить двоичные файлы вместе, так что сначала необходимо преобразовать документ Word в формат, который Git понимает.

Так же, как и в предыдущем примере, можно использовать для Pandoc. Это также будет работать с HTML, но простота уценки делает это лучше подходит для управления версиями, которые не знают о разметке из этих форматов.

Одна из причин, почему Git стал настолько популярным является то, что это распределенная система контроля версий, а не централизованная система, как, например, Subversion.

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

Github является популярным сервисом, который облегчает эту синхронизацию и добавляет некоторые полезные функции.

Один из способов сотрудничать с вашими соавторами состоит в том, чтобы создать хранилище GitHub (государственный или частный) для вашей рукописи, а также хранить эталонную версию рукописи в формате уценки.

Вместо того чтобы работать на мастер-версии непосредственно, вы должны использовать Pandoc для конвертирования туда и обратно между этой главной версией в формате уценки и ваш документ Word, и будет продолжать использовать слово как инструмент разработки.

Rakali является Pandoc инструмент, который я выпустил на прошлой неделе которые могут помочь автоматизировать этот преобразования документов.

Github имеет много особенностей, чтобы облегчить сотрудничество, которое может быть использовано здесь, например, вопросы GitHub для обсуждения и управления задачами.

Есть еще несколько грубых краев в рабочем процессе, описанном выше (например, только частичной поддержке отслеживания изменений Word), но это интересный подход к сотрудничеству с помощью Microsoft Word и Git.

И этот рабочий, конечно, могут быть улучшены также включать авторов, которые пишут в LaTeX или один из других форматов, которые поддерживает Pandoc.

Один хороший побочный эффект использования уценки в том, что Github автоматически создает веб-страницу для документа (которая не будет делать для HTML без дополнительных усилий).

Оригинал статьи: http://blog.martinfenner.org/2014/08/25/using-microsoft-word-with-git/

WordGit

A tool that allows you to diff and merge Word (.docx) files with git. Currently
Mac only.

Setup

  1. Clone this repository somewhere.
  2. Add the following to ~/.gitconfig:
[difftool "Word"]
  cmd = <PATH TO WORDGIT>/diff.js "$LOCAL" "$REMOTE"
[mergetool "Word"]
  cmd = <PATH TO WORDGIT>/merge.js "$BASE" "$LOCAL" "$REMOTE" "$MERGED"

Usage

Diff

  1. In your repository, run git difftool -T Word with any arguments that you
    would normally pass to git diff.
  2. On your first run, Word may prompt you to open some files so that Word can
    access them through its sandbox. Do as it says. (If you don’t see the diff
    after doing this step, rerun the command in step 1 and it should work)
  3. Your diff should open in a new document.

Merge

  1. In your repository run git merge, then, if there are conflicts,
    git mergetool -T Word <path to docx file with conflicts>.
  2. On your first run, Word may prompt you to open some files so that Word can
    access them through its sandbox. Do as it says.
  3. A new Word doc should open with the changes on both branches added as
    tracked changes. Merge any differences.
  4. Click the Done button. (On your first run, you may get another sandbox
    prompt.)
  5. Merge any other files and commit your merge as normal.

FAQ

Will it run on Windows?

No, this is implemented using Apple’s scripting support. However, you may be
able to use TortoiseGit’s Windows implementation of the same feature.

How it works

This whole thing is a careful dance around a bunch of Word bugs, but it seems
to work pretty well.

Diff

git difftool runs diff.js as a shebang script, evaluated by osascript
(AppleScript). diff.js copies the diffed files to /tmp/word_git (we copy them
because Git gives us paths that Word’s sandboxing workaround doesn’t seem to
like). Then we open and close doc2 (Word’s sandboxing workaround doesn’t seem
to trigger when you open a document for diffing, but opening and closing it
first sloves that). Finally, we open doc1, run the diff, and close doc1.

Merge

Similar to diff. There’s some closing and reopening because for some reason
Word doesn’t merge properly if we don’t.

One of the major challenges of writing a journal article is to keep track of versions — both the different versions you create as the document progresses, and to merge in the changes made by your collaborators. For most academics Microsoft Word is the default writing tool, and it is both very good and very bad in this. Very good because the track changes feature makes it easy to see what has changed since the last version and who made the changes. Very bad because this feature is built around keeping everything in a single Word document, so that only one person can work on on a manuscript at a time. This usually means sending manuscripts around by email, and being very careful about not confusing different versions of the document, which requires creativity.

Approaches to overcome these challenges are to a) integrate the Word documents into collaboration tools such as Sharepoint and Office 365, or document sharing services such as Dropbox and Google Docs (if you use it just for that), or b) use a different authoring tool altogether. If neither of these approaches works for you, you have a third option: use the version control system git.

Git is software that helps with tracking changes to files so that you can recall specific versions later. Git is typically used to track changes of software source code (and was originally developed by Linus Torvalds for Linux kernel development in 2005), but in fact git can be used for any file where we need to keep track of versions over time. Git is open source software that runs locally on your computer, so please go ahead and start tracking changes to your manuscripts (or other complex documents) with git. Any time you want to store a version, do a git commit with a little description and an optional tag.

This approach is not ideal, as git was written with source code in text format in mind and for example doesn’t understand what has changed between two revisions of a Word document. Some people will tell you to never store binary files in a version control system, but don’t listen to them. Instead give git a tool to convert Word documents into plain text, and git will then happily tell you what has changed between revisions. Several tools can do this, but since earlier this month Pandoc can read Word documents in docx format. Do the following to have Pandoc convert Word documents into markdown, and to compare the revisions by word and not by line (which makes more sense):

# .gitattributes file in root folder of your git project
*.docx diff=pandoc
# .gitconfig file in your home folder
[diff "pandoc"]
  textconv=pandoc --to=markdown
  prompt = false
[alias]
  wdiff = diff --word-diff=color --unified=1

You can then use git wdiff important_file.docx to see the changes (with deletions in red and insertions in green), or git log -p --word-diff=color important_file.docx to see all changes over time.

While you can now track revisions of a Word document and see the changes, you also want to be able to merge different versions of a Word document together so that you and your collaborators can work on the manuscript in parallel. Git can’t merge binary files together, so you need to first convert the Word document into a format that git understands. Just as in the previous example we can use Pandoc for that, with markdown as the textual format. This would also work with HTML or LaTeX, but the simplicity of markdown makes it better suited for version control which doesn’t know about the markup of these formats.

One of the reasons that git became so popular with software developers is that it is a distributed version control system instead of a centralized system such as Subversion. This means that you can track all revisions locally on your computer, but can still synchronize your revisions with another user. Github is a popular service that facilitates this synchronization and adds some nice features on top. One way to collaborate with your co-authors is therefore to set up a Github repository (public or private) for your manuscript, and store the master version of the manuscript in markdown format. Instead of working on the master version directly, you would use Pandoc to convert back and forth between this master version in markdown format and your Word document, and would continue to use Word as authoring tool. Rakali is a Pandoc tool that I released last week that can help automate this document conversion. Github has a a number of features to facilitate collaboration that can be used here, e.g. Github issues for discussion and task management.

There are still a few rough edges in the workflow described above (e.g. only partial support of Word track changes), but it is an interesting approach to collaborate using Microsoft Word and git. And this workflow can of course be enhanced to also include authors that write in LaTeX or one of the other formats that Pandoc supports. One nice side effect of using markdown is that Github will automatically render a webpage for the document (which it will not do for HTML without extra effort).

For some time now, I have been using Git to keep track of my work — both source code and otherwise. Even when you’re not using it for code, Git is perfect — easy backups to a Git server in the cloud along with the possibility of maintaining multiple working versions of my papers and writing projects is just great.

Except — Git treats my Word files as binaries. Different versions can be accessed just fine, but I have no access to diff functionality because Git doesn’t understand what has changed between two versions. Not to mention, most programmers will flinch uncontrollably at my mention of storing binaries in version control — even if it’s only the stupid play I’m writing.

The solution is to use something that Git can understand out of the box — like Markdown — or find a way to help Git interpret .docx files, which you know deep (deep) down are text files. Choosing not to give up the flexibility of Word (and mostly out of habit), I started looking at ways to implement the latter.

Martin Fenner has a very informative post on one way of doing this. He uses pandoc to convert docx files to markdown that git can then use to compare two versions of the same file. However, I ran into problems when using pandoc to convert files, and had to use a different implementation. I’m including both methods below, so feel free to try either.

§Using Pandoc to interpret Word Documents

Martin recommends the following steps:

Before you begin, install pandoc. On a Mac, if you have HomeBrew or MacPorts, this is as simple as typing brew install pandoc or port install pandoc. For a PC, you can find an installer on the downloads page. If you use LaTex, there’s a good chance you already have it.

  • Create a .gitattributes file in your project directory (if you don’t have one already) and add the following:
*.docx diff=pandoc

This will let git know what to do when it encounters files with a .docx extension.

  • Append the following to the .gitconfig file (On Mac, this should be ~/.gitignore. For Windows, this will depend on your installation, but for default settings, it should be in your home folder — or %HOMEDRIVE%%HOMEPATH%) —
[diff "pandoc"]
  textconv=pandoc --to=markdown
  prompt = false
[alias]
  wdiff = diff --word-diff=color --unified=1

We’re adding pandoc to the config, along with creating an alias for a specific diff call.

  • Once this is done, you can make sure everything works by commiting a Word file, and running the following command:
git wdiff <your_file>.docx

Unfortunately, this didn’t work for me. For every file I tried, pandoc failed with a ‘UTF-8’ error. Some Googling showed that this was a common error with pandoc and some versions of Word. There were a few fixes, but none solved my problem. Not wanting to trawl the manpage for answers, I moved on to door number two.

If pandoc worked for you, then this is really unnecessary and you can move on to actual work. But it didn’t work for me, so I started looking for docx to markdown converters. There are a few online that are pretty good. There’s a Ruby Gem that does it pretty well. There’s even a Visual Basic Script that does it, if you’re looking for integration into Word itself. For Mac, the included textutil does docx conversions pretty easily. It comes pre-installed, and is pretty light-weight. Unfortunately, it doesn’t support markdown, but if you really need to track stylistic changes, there is a Ruby Gem that uses textutil for docx to markdown conversion that shouldn’t be hard to use. Just install it and replace the direct calls to textutil in the directions.
Converting to plain text was simple enough for me. I’m mostly using Terminal to track changes to my work, so textutil’s txt conversion seemed enough (at least for the time being). It also meant that I didn’t have to install new software on all my workstations.

To implement textutil-based tracking, do the following:

  • Create and add the following to .gitattributes in your project directory (same as before):
*.docx diff=textutil
  • Add these lines to ~/.gitconfig:
[diff "textutil"]
  textconv=textutil -convert txt -stdout
  prompt = false
[alias]
  wdiff = diff --word-diff=color --unified=1

The -convert txt switch lets us convert the file to plain text, and the -stdout switch makes sure we’re printing to standard out instead of to file.

  • Once this is done, you can run git wdiff <filename>.docx to see the results.

screenshot

It should now be easy to modify Git to work with complex file formats, now that you know how.

me

Hrishi Olickel

25 Oct 2015

Git is a fantastic tool for version control of code, and functionality like branching and pull requests mean that multiple people can work on the code at the same time without overwriting each others work.

All of these features make Git a great collaboration tool, but unfortunately out of the box it doesn’t work with Microsoft Word documents, meaning you’re not going to be able to use Git for document collaboration without a whole lot of extra work converting files between Docx and plain text each time you want to write something.

There is however, a tool that has all features and functionality of Git you’d need (including versioning, commentings, diffs, merging, branching, pull requests and more) and it directly integrates with Microsoft Word. That tool is Simul Docs.

In this article, we’ll outline how you can use Simul to collaborate on Word Documents in the same way you would use Git to collaborate on code.

Понравилась статья? Поделить с друзьями:
  • Girls using а word
  • Get cell row vba excel
  • Girls saying а word
  • Get cell name in excel vba
  • Girls run the word