Как я могу показать различия между двумя программами? - PullRequest
2 голосов
/ 28 мая 2019

Я веду лекцию по программированию.Вместо того, чтобы использовать слайды, я представляю последовательность постепенно увеличивающихся программ, хранящихся в именах файлов 0001.py, 0002.py и т. Д.

Код в каждой программе вводит только одну или несколько строк кода в видемодификация к предыдущему.

Я намерен представить исключительно с использованием emacs.Я знаком с ediff, но было бы немного неудобно использовать его вживую во время разговора (поскольку существует около 50 небольших программ, по одной минуте для введения каждого приращения).

Есть лисуществует пакет emacs, который позволил бы мне разбить окно и выделить то, что на самом деле отличается между (n) .py и (n + 1) .py.(Я использую .py для конкретности, но, надеюсь, решение подойдет для любого текстового файла.)

Я спрашиваю здесь, а не на https://emacs.stackexchange.com, потому что я буду доволен решениемиспользуя emacs, git или любую комбинацию, которую я могу связать вместе, чтобы получить живую демонстрацию, особенно с возможностью изменять код в реальном времени, отвечая на вопросы.

Обновление

Как подсказывает phils, M-x compare-windows почти решает эту проблему, но:

  1. Было бы неплохо, если бы он работал правильно независимо от текущей позиции курсора в двух буферах.
  2. Было бы хорошо, если бы все изменения появлялись в одном представлении, а не итерировали по diff s.Смысл в том, чтобы сказать: «Посмотрите, в программе справа я добавил только эту строку и эту строку, и посмотрите на все, что может сделать программа по сравнению с предыдущей».

Обновление 2

Другими словами, как мне сгенерировать то, что делается вручную в приведенном ниже HTML-коде, чтобы показать различия бок о бок?

.myflex {
  display: flex;
  flex-direction: row;
}

.before,
.after {
  border: 1px solid black;
  padding: 20px;
  margin: 20px;
  border-radius: 2px;
}

.pink {
  background-color: pink;
}

.green {
  background-color: PaleGreen;
}

  
    
And so without particularly analyzing all the contiguous sections of a
cone and of the ranks of an army, or the ranks and positions in any
while the less their direct participation in the action itself, the more
they command and the fewer of them there are; rising in this way from
the lowest ranks to the man at the top, who takes the least direct share
in the action and directs his activity chiefly to commanding.
        
<span class='green'>We see a law by which men, to take associated action, combine</span>
<span class='green'>in such relations that the more directly they participate in performing</span>
<span class='green'>the action the less they can command and the more numerous they are,</span>
while the less their direct participation in the action itself, the more
they command and the fewer of them there are; rising in this way from
the lowest ranks to the man at the top, who takes the least direct share
in the action and directs his activity chiefly to commanding.
        

1 Ответ

2 голосов
/ 29 мая 2019

Я подозреваю, что некоторые существующие функции diff могут сделать это, и поэтому будет лучший ответ, но я взломал следующее вместе, используя compare-windows.

(defun my-compare-windows-complete (&optional ignore-whitespace)
  "Highlight all differences between two windows.

With a prefix argument, do not highlight whitespace-only differences.
\(This does not prevent the highlighting of whitespace that is part of
a difference which includes non-whitespace characters.)

To remove the highlighting, use \\[compare-windows-dehighlight]."
  (interactive "P")
  (require 'cl-lib)
  (require 'compare-w)
  (compare-windows-dehighlight)
  (let ((w1 (get-buffer-window))
        (w2 (funcall compare-windows-get-window-function)))
    (cl-letf ((w1p (point))
              (w2p (window-point w2))
              (compare-windows-highlight 'persistent)
              ((symbol-function 'compare-windows-dehighlight) #'ignore)
              ((symbol-function 'ding) (lambda () (error "done"))))
      (goto-char (point-min))
      (with-selected-window w2
        (goto-char (point-min)))
      (ignore-errors
        (while (compare-windows ignore-whitespace)))
      (set-window-point w1 w1p)
      (set-window-point w2 w2p))))

Вы можете использовать M-x compare-windows-dehighlight впоследствии для удаления выделения.

Грани, используемые для выделения:

  • compare-windows-removed (наследование от diff-removed)
  • compare-windows-added (наследование от diff-added)
...