Sublime text сравнить два файла
Sublime Text includes a built-in diff functionality that tracks changes to files being edited. The diff calculation is incremental, tracking each buffer modification as it is performed. It does not require the file be stored in a version control system, such as Git.
The exact location of each addition, modification and deletion is tracked. This is used to display markers in the gutter, allow navigation between each change, display inline diffs and allow for reverting changes.
Diffs are calculated against the version of the file on disk, but Git repositories can be configured to diff against HEAD, and the API allows files to be diffed against any content.
Settings
If the incremental diff functionality should be enabled. Valid values include:
- true – always enable incremental diff
- " auto " – enable incremental diff for files in a Git repository
- false – disable incremental diff
Controls the behavior of incremental diff for files in a Git repository. Valid values include:
У меня есть два клонированных репозитория двух очень похожих проектов с открытым исходным кодом, над которыми я работал в разных случаях в Sublime Text 2, чтобы достичь желаемого результата. Был использован код из обоих этих проектов. Я использую Git в качестве контроля версий для своего проекта, но не включил оригинальные проекты. Таким образом, я хотел бы иметь возможность быстро сравнить содержимое двух файлов оригинального проекта и сравнить различия между ними и моей проект.
Я надеялся, что Sublime Text 2 будет иметь функцию "сравнить файл", но я не могу найти ничего, связанного с ним в настройках или в интернете. Сторонний пакет ST2 для выполнения этой задачи также будет хорошо работать. возможна ли такая задача в текстовом редакторе ST2?
вы можете сравнить файлы изначально прямо в Sublime Text.
- перейдите в папку, содержащую их, через " открыть папку. " или в проекте
- выберите два файла (т. е., удерживая Ctrl on Windows или ⌘ на macOS) вы хотите сравнить в боковой панели
- щелкните правой кнопкой мыши и выберите .
Сравнить Бок-О-Бок похоже, самый удобный для меня, хотя это не самый популярный:
UPD: мне нужно добавить, что этот плагин может заморозить ST при сравнении больших файлов. Это, конечно, не лучшее решение, если вы собираетесь сравнивать большие тексты.
есть несколько diff Плагины доступный через Управление пакета. Я использовал Sublimerge Pro, который работал достаточно хорошо, но это коммерческий продукт (с неограниченным пробным периодом) и с закрытым исходным кодом, поэтому вы не можете настроить его, если хотите что-то изменить или просто посмотреть на его внутренности. FileDiffs довольно популярен, судя по количеству установок, поэтому вы можете попробовать это.
обновление
(учитывая upvotes, я чувствую, что есть необходимость в полном пошаговом объяснении. )
- в строке меню нажмите на кнопку File -> Open Folder.
- выберите папку (папки не имеет значения, этот шаг просто сделать FOLDERS боковая панель имеется)
- если боковая панель еще не показана, сделайте это через View -> Side Bar -> Show Side Bar
- использовать FOLDERS - титулованная боковая панель чтобы перейти к первому файлу, который вы хотите сравнить.
- выберите его (нажмите на него), удерживайте нажатой клавишу ctrl и выберите второй файл.
- выбрав два файла, щелкните правой кнопкой мыши на одном из них и выберите Diff Files.
теперь должна быть новая вкладка, показывающая сравнение.
оригинальный короткий ответ:
Обратите внимание, что:
"Diff файлы" отображается только с боковой панелью "папки" (чтобы открыть папку: File - >Open Folder), а не с боковой панелью "open files".
ОБНОВЛЕНИЕ ЯНВАРЯ 2018 - специально для Sublime / Mac
Я использую Sublime Text 3 (build 3143) на Mac и уже около 30 минут пытаюсь найти эту функцию сравнения файлов. Я использовал его раньше на Sublime / Mac без каких-либо проблем, но на этот раз все было сложнее. Но я, наконец, понял.
формат файла не должен быть UTF-8. Я успешно сравнил файлы, которые являются UTF-8, ISO-8559-1 и Windows-1252.
нет файла > открыть папки на Sublime / Mac. Многие инструкции выше начинаются с "выберите Файл > Открыть папки", но это не существует на Sublime/Mac.
file compare работает на основе проекта. Если вы хотите сравнить два файла, они должны быть сохранены на диск и частью текущего проекта.
способы открытия проекта
- если Sublime/Mac не работает или если он работает, но окна не открыты, перетащите папку в приложение Sublime.
- если Sublime / Mac запущен, выберите " Файл > Открыть", перейдите в нужную папку, не выберите файл или папку и нажать "Открыть".
Добавить папку в проект. Если файлы, которые вы хотите сравнить, не являются частью одной иерархии, сначала откройте папку, содержащую один из файлов. Затем выберите "проект > Добавить папку в проект", перейдите в нужную папку и нажмите"Открыть". Теперь вы увидите две папки корневого уровня в боковая панель.
боковая панель должна быть видна. Вы можете либо "вид > боковая панель > показать боковую панель", либо использовать ярлык, Command-K, Command-B.
файлы должны быть закрыты (т. е. сохраняется), чтобы сравнить. Один щелчок по файлу в боковой панели делает не откройте файл, но он отображает его. Вы можете сказать, открыт ли файл, если он указан в разделе" Открытые файлы " вверху бокового бара. Двойной щелчок по файлу или внесение изменений в файл автоматически изменит статус файла на "Открыть". В этом случае обязательно закройте его, прежде чем пытаться сравнить.
Выберите файлы из иерархии папок. Стандартный Mac shorcut здесь, (один) щелкните первый файл, затем команду-щелкните второй файл. При выборе первого файла вы увидите его содержимое, но он не открыт. Тогда, когда ты Команда-нажмите второй файл, вы увидите его содержание, но опять же, ни один из них не открыт. Вы заметите только одну вкладку на панели редактирования.
Control-click не то же самое, что щелкните правой кнопкой мыши. Это было то, что достало меня. Я использую трекпад и часто прибегаю к щелчку правой кнопкой мыши или вторичному щелчку. Это не работает для меня. Однако, поскольку я настроил трекпад в Системных настройках для использования в правом нижнем углу моего трекпада как щелчок правой кнопкой мыши, который работал, отображая контекстное меню, с "удалить", "показать в Finder", и. "Файлы Diff. "
вуаля! Надеюсь, это кому-то поможет.
ОБНОВЛЕНИЕ ОКТЯБРЬ 2017 Я никогда не знал, что эта функция существует в Sublime Text, но интерфейс, похоже, немного изменился по сравнению с предыдущим ответом - по крайней мере, на OS X. Вот подробные шаги, которые я выполнил:
- в строке меню выберите Файл -> Открыть.
- перейдите к папке, содержащей файлы для сравнения и с выбранной папкой, нажмите кнопку Открыть, это делает боковую панель папки появляются
- в папках боковая панель, нажмите на первый файл для сравнения
- удерживайте Ctrl на Windows или ⌘ на OS X и нажмите второй файл
- при выборе обоих файлов щелкните правой кнопкой мыши на одном из них и выберите Diff Files.
откроется новая вкладка, показывающая сравнение. Первый файл красным, второй зеленым.
никто не говорит о Linux, но все вышеперечисленные ответы будут работать. Просто используйте Ctrl, чтобы выбрать несколько файлов. Если вы хотите сравнить бок о бок, объединить прекрасная.
I have two cloned repositories of two very similar open-source projects, which I have been working on in different instances in Sublime Text 2 to arrive at my desired result. Code from both of these projects was used. I have been using Git as version control for my project, but have not included the original projects. Thus, I would like to be able to quickly compare the contents of two files of the original project and compare the differences between them and my project.
I was hoping that Sublime Text 2 would have a "Compare File" feature, but I can't seem to find anything related to it in the settings or online. A third-party ST2 package to accomplish this task would also work well. Is such a task possible to do within the ST2 text editor?
Add permanent highlighting for file types
By default all files in Sublime are opened as Plain text. It's rather annoying to open files from some association files and manually select the highlighting. If you know the file type association and the related highlighting then you can set it up in Sublime editor by:
- View
- Syntax
- Open all with current extension as .
- Select language - for example HTML ( in my case I have files .hbs which are related to HTML)
- Left click of the mouse
e
Now every time when you open file from this file type you will have this association.
In order to restore the default value you can:
Inline Diffs
In addition to tracking which lines have been modified, the incremental diff also tracks the exact changes. This allows displaying the original version of the text.
Продвинутое
Плагин Sublimerge 3, инструкция по установке в конце страницы. Он Freemium, но если не желаете отдавать деньги, придётся только иногда (достаточно нечасто) терпеть всплывающее окно с предложением его купить. Пример работы:
Из преимуществ отметил бы возможность интеграции с системами контроля версий SVN, Git и Mercurial (Bazaar пока не поддерживается). Например, чтобы сравнить файл в локальном хранилище с любой из его версий на удалённом репозитории, необходимо кликнуть где-нибудь в тексте этого файла правой кнопкой мыши, в появляющемся контекстном меню Sublimerge → Compare to revision. → выбираем требуемую версию для сравнения.
Sublime Text has incorporated file comparison - Diff files - which is not easy to be seen at least for Linux and MacOS. In order to make it work you need to follow this steps(steps tested on Sublime 3 and Ubuntu):
- Go to File
- Open Folder
- Navigate to the directory which contains the files to be compared(select this folder)
- Open
- Folders sidebar should appear - if you don't see the sidebar you need to go to ( View -> Sidebar - Show Sidebar)
- In the sidebar select the files for comparison(with pressing CTRL (Linux and Windows) or ⌘ (on OS X)
- Diff Files.
Using plugin Compare Side-By-Side
A better and easier way to compare files in Sublime text editor is by using a plugin:
How to install Compare Side-By-Side(check below how to install package control):
- Go to Preferences
- Package control CTRL + SHIFT + P
- Install Package
- Search for Compare Side-By-Side
- Left click with the mouse
In order to compare you need to:
- Select the first file for comparison to be active
- Go to the second one with right click of the mouse
- Compare with active tab
or you can use: Compare with.
In order to remove this plugin:
Install package control
In order to install package control you can visit this page and follow the instructions: Sublime Install package control
- Preferences
- Browse Packages…
- Browse up a folder and then into the Installed Packages/ folder
- Download Package Control.sublime-package
- copy the file into the Installed Packages/ directory
- Restart Sublime Text
Решения для Sublime Text 3
Быстрое
Плагин FileDiffs, документация там же, по ссылке.
Выделяются сами различия между файлами и приводятся номера строк — лично мне этого вполне хватает.
Reverting
A modification may be reverted to the original text by the keyboard shortcut:
Alternatively, the menu Edit Text Revert Modification may be used.
Toggling
When right-clicking on a modified region of a file, a menu entry Show Diff Hunk will be available. This menu item will display the previous content inline beneath the current content. Right-clicking again will show a menu item Hide Diff Hunk to hide the inline diff.
Toggling an inline diff may be performed via the Edit Text Toggle Hunk Diff menu.
In addition to menu-based activation, diffs may also be toggled via keyboard shortcut:
To toggle the diff for a region, while hiding all other diffs, press:
Diff Markers
The following is an example of diff markers displayed when using the Mariana color scheme:
27 | |
28 | A line that was added |
29 | |
30 | A modified line |
31 | followed by another modified line |
32 | |
33 | The line before this was deleted |
34 |
See the color schemes documentation for information on customizing the colors and width of the diff markers.
Search with regular expressions in Sublime Text editor
If you want to perform are regex searches in Sublime you need to enable the regex search by:
Navigation
Users can jump to the next or previous modification using the following methods:
The keyboard shortcuts tend to be a very natural way to jump around a file being edited.
10 Answers 10
You can actually compare files natively right in Sublime Text.
- Navigate to the folder containing them through Open Folder. or in a project
- Select the two files (ie, by holding Ctrl on Windows or ⌘ on macOS) you want to compare in the sidebar
- Right click and select the Diff files. option.
@Derek: using select able to select but not able to find the diff file option on right click, only got the close option on right click.
@MohamedHussain There are really two different sidebars and you need to be in the right one for this to work. If you go to File>Open Folder. Select the folder your files are in, then select View>Side Bar>Show Side Bar, you will get the one you need. You get the other by selecting View>Side Bar>Show Open Files, but this one will not let you use the Diff Files. option.
This unfortunately does not seem to work anymore in sublime build 3103 on mac. As soon as I right click the second file gets deselected,
Not working for me in Build 3144 on OSX. I can select two files in the file interface, but when I Ctrl-click only one becomes selected and the diff option isn't there.
Compare Side-By-Side looks like the most convenient to me though it's not the most popular:
UPD: I need to add that this plugin can freeze ST while comparing big files. It is certainly not the best decision if you are going to compare large texts.
Works well and can compare files from different locations which I haven't managed to do with the native compare.
There are a number of diff plugins available via Package Control. I've used Sublimerge Pro, which worked well enough, but it's a commercial product (with an unlimited trial period) and closed-source, so you can't tweak it if you want to change something, or just look at its internals. FileDiffs is quite popular, judging by the number of installs, so you might want to try that one out.
Well I cannot figure it out how to use FileDiffs. Can you shortly describe how I can compare two files with it.
@LanceLafontaine I wouldn't normally do this, but would you mind changing the accepted answer to Derek 朕會功夫's answer below? Neither of us really need the points, but I didn't know there was a built-in diff at the time. I now use it all of the time when in Sublime. The only time I don't is when I need the extended features of an external tool.
Which of those plugins is able to detect the movement of whole blocks of text? And not just tell some lines are missing here and appear there but also show with arrows how they moved?
Thanks to this answer, I installed FileDiffs and added commad to use TortoiseMerge.exe for comparison. It was a huge improvement for my every day use of sublime code comparison. Thanks!
UPDATE
(Given the upvotes, I feel there is a need for a complete step-by-step explanation. )
- In the Menu bar click on File -> Open Folder.
- Select a folder (the actual folder does not really matter, this step is just to make the FOLDERS sidebar available)
- If there is no Side Bar shown yet, make it appear via View -> Side Bar -> Show Side Bar
- Use this FOLDERS -titled Side Bar to navigate to the first file you want to compare.
- Select it (click on it), hold down ctrl and select the second file.
- Having two files selected, right click on one of the two and select Diff Files.
There should be a new Tab now showing the comparison.
Original short answer:
Note that:
The "Diff files" only appears with the "folders" sidebar (to open a folder: File->Open Folder) , not with "open files" sidebar.
What do you mean by select? Highlight them and e.g. copy them? Or extracting them? Thanks for the clarification!
Since the missing lines are prefixed with '- ' I selected one and then matched all of them, selected the full line and copied. A built in way would just be more fluff to forget.
I think it is worth explaining that both files can't be hard opened. If you doubled clicked on both so they are both opened, then you can't highlight both files in the sidebar using the ctrl button. You have to make sure one of them is closed before you can select both files. I found this out because I already had both files open and wanted to use diff files.
UPDATE JAN 2018 - especially for Sublime/Mac
(This is very similar to Marty F's reply, but addresses some issues from previous responses, combines several different suggestions and discusses the critical distinction that gave me problems at first.)
I'm using Sublime Text 3 (build 3143) on Mac and have been trying for about 30 minutes to find this File Compare feature. I had used it before on Sublime/Mac without any problems, but this time, it was trickier. But, I finally figured it out.
The file format does not need to be UTF-8. I have successfully compared files that are UTF-8, ISO-8559-1, and Windows-1252.
There is no File > Open Folders on Sublime/Mac. Many instructions above start with "Select File > Open Folders," but that doesn't exist on Sublime/Mac.
File compare works on a Project basis. If you want to compare two files, they must be saved to disk and part of the current project.
Ways to open a project
- If Sublime/Mac is not running or if it's running but no windows are open, drag a folder onto the Sublime app.
- If Sublime/Mac is running, select "File > Open", navigate to the desired folder, don't select a file or folder and click "Open".
Add a folder to a project. If the files you want to compare are not part of the same hierarchy, first open the folder containing one of the files. Then, select "Project > Add Folder to Project", navigate to the folder you want and click "Open". You will now see two root-level folders in your sidebar.
The Sidebar must be visible. You can either "View > Side Bar > Show Side Bar" or use the shortcut, Command-K, Command-B.
Files must be closed (ie, saved) to compare. Single-clicking a file in the Side Bar does not open the file, but it does display it. You can tell if a file is open if it's listed in the "Open Files" section at the top of the Side Bar. Double-clicking a file or making a modification to a file will automatically change a file's status to "Open". In this case, be sure to close it before trying to compare.
Select files from the folder hierarchy. Standard Mac shorcut here, (single) click the first file, then Command-click the second file. When you select the first file, you'll see its contents, but it's not open. Then, when you Command-click the second file, you'll see its contents, but again, neither are open. You'll notice only one tab in the editing panel.
Control-click is not the same as right-click. This was the one that got me. I use my trackpad and often resort to Control-click as a right-click or secondary-click. This does not work for me. However, since I configured my trackpad in System Preferences to use the bottom-right corner of my trackpad as a right-click, that worked, displaying the contextual menu, with "Delete", "Reveal in Finder", and. "Diff Files. "
Хотите улучшить этот вопрос? Обновите вопрос так, чтобы он вписывался в тематику Stack Overflow на русском.
Закрыт 5 лет назад .
Какие есть программы для быстрого сравнения двух файлов JavaScript, HTML, CSS, аналогично VCS-системам? То есть, передаёшь два файла, а программа показывает, чем они отличаются, и в каких строках. Но для любых локальных файлов, без какой-то централизованной системы и установки.
Быстрее и удобнее сразу сравнивать файлы в том же текстовом редакторе/IDE, которым Вы пользуетесь, без установки дополнительных программ. В Sublime Text 3 мне пока не доводилось наблюдать сбоев в работе служащего для этой цели плагина SublimeFileDiffs. Спасибо.
Если под Linux, то идеально подходит встроенная утилита diff.
Советую посмотреть в сторону Winmerge
1) Софт только для Windows (ув-мый ТС не указал свою ОС). // 2) Разработка прекратилась, см. неутешительную статистику багтрекера.
- Когда просите посоветовать программу, всегда указывайте свою операционную систему.
- Здесь подобные вопросы закрываются, специально для них служит сайт Software Reccomendations.
Быстрее и удобнее не открывать лишний раз сторонние программы, а когда всё и сразу совершается в одном редакторе/IDE.
Styling
The styles used for displaying inline diffs are automatically generated for color schemes that have not created their own rules. For custom styles, add rules with the following selectors:
Generally each rule will set the background and foreground_adjust properties.
Читайте также: