private void CheckCombinationsAreColor (Hunk hunk, ColorAssertion assertion)
		{
			assertion (GetColor (hunk, true, true));
			assertion (GetColor (hunk, true, false));
			assertion (GetColor (hunk, false, true));
			assertion (GetColor (hunk, false, false));
		}
Example #2
0
 public override bool MergeHunk(ref Hunk hunk)
 {
     if (IsClosed) throw new ApplicationException("Cannot merged into a closed hunk!");
     if (Hunks.Count != 1) throw new ApplicationException("Insertion hunks can only be merged if they have not been transformed!");
     Hunk current = (InsertionHunk)Hunks.First();
     Hunk result;
     if (current.MergeSubsequent(ref hunk, out result))
     {
         Hunks.Remove(current);
         current.Destroy();
         Hunks.Add(result);
         return true;
     }
     else
     {
         return false;
     }
 }
Example #3
0
		protected override void UndoChange (MonoTextEditor fromEditor, MonoTextEditor toEditor, Hunk hunk)
		{
			base.UndoChange (fromEditor, toEditor, hunk);
			int i = leftConflicts.IndexOf (hunk);
			if (i < 0)
				i = rightConflicts.IndexOf (hunk);
			// no conflicting change
			if (i < 0)
				return;
			currentConflicts.RemoveAt (i);
/*			var startLine = MainEditor.Document.GetLineByOffset (hunk.InsertStart);
			var endline   = MainEditor.Document.GetLineByOffset (hunk.InsertStart + hunk.Inserted);
			
			currentConflicts[i].StartSegment.Offset = startLine.EndOffset;
			currentConflicts[i].EndSegment.Offset = endline.EndOffset;
						 */
			UpdateDiff ();
		}
			public bool GetButtonPosition (Hunk hunk, double y1, double y2, double z1, double z2, out double x, out double y, out double w, out double h)
			{
				if (hunk.Removed > 0) {
					var b1 = z1;
					var b2 = z2;
					x = useLeft ? 0 : Allocation.Width - buttonSize;
					y = b1;
					w = buttonSize;
					h = b2 - b1;
					return hunk.Inserted > 0;
				} else {
					var b1 = y1;
					var b2 = y2;

					x = useLeft ? Allocation.Width - buttonSize : 0;
					y = b1;
					w = buttonSize;
					h = b2 - b1;
					return  hunk.Removed > 0;
				}
			}
			protected override bool OnMotionNotifyEvent (EventMotion evnt)
			{
				bool hideButton = widget.MainEditor.Document.ReadOnly;
				Hunk selectedHunk = Hunk.Empty;
				if (!hideButton) {
					int delta = widget.MainEditor.Allocation.Y - Allocation.Y;
					if (Diff != null) {
						foreach (var hunk in Diff) {
							double z1 = delta + fromEditor.LineToY (hunk.RemoveStart) - fromEditor.VAdjustment.Value;
							double z2 = delta + fromEditor.LineToY (hunk.RemoveStart + hunk.Removed) - fromEditor.VAdjustment.Value;
							if (z1 == z2)
								z2 = z1 + 1;
	
							double y1 = delta + toEditor.LineToY (hunk.InsertStart) - toEditor.VAdjustment.Value;
							double y2 = delta + toEditor.LineToY (hunk.InsertStart + hunk.Inserted) - toEditor.VAdjustment.Value;
	
							if (y1 == y2)
								y2 = y1 + 1;
							double x, y, w, h;
							GetButtonPosition (hunk, y1, y2, z1, z2, out x, out y, out w, out h);
	
							if (evnt.X >= x && evnt.X < x + w && evnt.Y >= y && evnt.Y < y + h) {
								selectedHunk = hunk;
								TooltipText = GettextCatalog.GetString ("Revert this change");
								QueueDrawArea ((int)x, (int)y, (int)w, (int)h);
								break;
							}
						}
					}
				} else {
					selectedHunk = Hunk.Empty;
				}

				if (selectedHunk.IsEmpty)
					TooltipText = null;

				if (this.selectedHunk != selectedHunk) {
					this.selectedHunk = selectedHunk;
					QueueDraw ();
				}
				return base.OnMotionNotifyEvent (evnt);
			}
		public static Cairo.Color GetColor (Hunk hunk, bool removeSide, bool dark, double alpha)
		{
			Cairo.Color result;
			if (hunk.Removed > 0 && hunk.Inserted > 0) {
				result = dark ? darkBlue : lightBlue;
			} else if (removeSide) {
				if (hunk.Removed > 0) {
					result = dark ? darkRed : lightRed;
				} else {
					result = dark ? darkGreen : lightGreen;
				}
			} else {
				if (hunk.Inserted > 0) {
					result = dark ? darkGreen : lightGreen;
				} else {
					result = dark ? darkRed : lightRed;
				}
			}
			result.A = alpha;
			return result;
		}
		private void CheckDarkColoursAreDarker (Hunk hunk)
		{
			Color dark = GetColor (hunk, true, true);
			Color light = GetColor (hunk, true, false);
			Assert.Less (dark.R, light.R);
			Assert.Less (dark.B, light.B);
			Assert.Less (dark.G, light.G);
		}
        // @@\s*\-(?<start1>\d+),\s*(?<length1>\d+)\s*\+(?<start2>\d+),\s*(?<length2>\d+)\s*@@\\n(?<line>.*?(\\n|$))+

        //@@\s*\-(?<start1>\d+),\s*(?<length1>\d+)\s*\+(?<start2>\d+),\s*(?<length2>\d+)\s*@@.*?\\n

        //.*?(?<!\\)\\n  negaive lookbehind
        //.*?((?<!\\)\\n|$) - raw line
        // .*?[^\\](\\n|$) - using not but wont work for empty lines

        //@@\s*\-\d+,\s*\d+\s*\+\d+,\s*\d+\s*@@

        //(?<=(\\n)|^)@@\s*\-(?<start1>\d+),\s*(?<length1>\d+)\s*\+(?<start2>\d+),\s*(?<length2>\d+)\s*@@   - positive lookbehind

        //(?<=(\\n)|^)@@\s*\-(?<start1>\d+),\s*(?<length1>\d+)\s*\+(?<start2>\d+),\s*(?<length2>\d+)\s*@@.*?((?<!\\)\\n|$)

        //(?<=(\\n)|^)@@\s*\-(?<start1>\d+),\s*(?<length1>\d+)\s*\+(?<start2>\d+),\s*(?<length2>\d+)\s*@@.*?((?<!\\)\\n|$)

        public static Hunk[] ParseHunks(string diff, out Gap[] gaps)
        {
            //var rawLineMatches = Regex.Matches(diff, rawLinePattern);
            //var rawLines = rawLineMatches.Cast<Match>().Select(m => m.Value).ToArray();
            var  rawLines           = diff.Split('\n').ToArray();
            Hunk currentHunk        = null;
            Hunk previousHunk       = null;
            var  numberInChanges    = 0;
            var  numberInSourceFile = 0;
            var  numberInTargetFile = 0;
            var  hunks    = new List <Hunk>();
            var  gapsList = new List <Gap>();

            foreach (var rawLine in rawLines)
            {
                var hunkMatch = Regex.Match(rawLine, hunkHeaderPattern);
                if (hunkMatch.Success)
                {
                    previousHunk = currentHunk;
                    currentHunk  = new Hunk();

                    var start1  = hunkMatch.Groups["start1"].Value;
                    var lenght1 = hunkMatch.Groups["length1"].Value;
                    var start2  = hunkMatch.Groups["start2"].Value;
                    var lenght2 = hunkMatch.Groups["length2"].Value;

                    currentHunk.StartInTargetFile  = int.Parse(start1);
                    currentHunk.LengthInTargetFile = int.Parse(lenght1);
                    currentHunk.StartInSourceFile  = int.Parse(start2);
                    currentHunk.LengthInSourceFile = int.Parse(lenght2);

                    if (previousHunk == null)
                    {
                        currentHunk.StartInChanges = currentHunk.StartInSourceFile;
                        if (currentHunk.StartInSourceFile > 1)
                        {
                            var gap = new Gap();
                            gap.StartInSourceFile = 1;
                            gap.StartInTargetFile = 1;
                            gap.StartInChanges    = 1;
                            gap.Length            = currentHunk.StartInSourceFile - 1;
                            gapsList.Add(gap);
                        }
                    }
                    else
                    {
                        var gapLength = currentHunk.StartInSourceFile - previousHunk.EndInSourceFile - 1;
                        currentHunk.StartInChanges = previousHunk.EndInChanges + gapLength + 1;
                        var gap = new Gap();
                        gap.Length            = gapLength;
                        gap.StartInSourceFile = previousHunk.EndInSourceFile + 1;
                        gap.StartInTargetFile = previousHunk.EndInTargetFile + 1;
                        gap.StartInChanges    = previousHunk.EndInChanges + 1;
                        gapsList.Add(gap);
                    }

                    hunks.Add(currentHunk);
                    numberInChanges    = currentHunk.StartInChanges;
                    numberInSourceFile = currentHunk.StartInSourceFile;
                    numberInTargetFile = currentHunk.StartInTargetFile;
                    continue;
                }

                if (currentHunk == null)
                {
                    continue;
                }

                var line = new HunkLine();
                line.Text            = rawLine;
                line.NumberInChanges = numberInChanges;
                if (rawLine.StartsWith("-"))
                {
                    line.NumberInTargetFile = numberInTargetFile;
                    numberInTargetFile++;
                }
                else if (rawLine.StartsWith("+"))
                {
                    line.NumberInSourceFile = numberInSourceFile;
                    numberInSourceFile++;
                }
                else
                {
                    line.NumberInSourceFile = numberInSourceFile;
                    line.NumberInTargetFile = numberInTargetFile;
                    numberInTargetFile++;
                    numberInSourceFile++;
                }

                numberInChanges++;
                currentHunk.Lines.Add(line);
            }

            gaps = gapsList.ToArray();
            return(hunks.ToArray());
        }
		protected virtual void UndoChange (TextEditor fromEditor, TextEditor toEditor, Hunk hunk)
		{
			toEditor.Document.BeginAtomicUndo ();
			var start = toEditor.Document.GetLine (hunk.InsertStart);
			int toOffset = start != null ? start.Offset : toEditor.Document.Length;
			if (start != null && hunk.Inserted > 0) {
				int line = Math.Min (hunk.InsertStart + hunk.Inserted - 1, toEditor.Document.LineCount);
				var end = toEditor.Document.GetLine (line);
				toEditor.Remove (start.Offset, end.EndOffset - start.Offset);
			}

			if (hunk.Removed > 0) {
				start = fromEditor.Document.GetLine (Math.Min (hunk.RemoveStart, fromEditor.Document.LineCount));
				int line = Math.Min (hunk.RemoveStart + hunk.Removed - 1, fromEditor.Document.LineCount);
				var end = fromEditor.Document.GetLine (line);
				toEditor.Insert (toOffset, start.Offset == end.EndOffset ? toEditor.EolMarker : fromEditor.Document.GetTextBetween (start.Offset, end.EndOffset));
			}

			toEditor.Document.EndAtomicUndo ();
		}
        public HgDiff Diff(string a, string b)
        {
            var al = a.Split('\n').Select(l => l.TrimEnd('\n', '\r') + "\n").ToArray();
            var bl = b.Split('\n').Select(l => l.TrimEnd('\n', '\r') + "\n").ToArray();

            var diff = BDiff.GetBlocks(Encoding.UTF8.GetBytes(a), Encoding.UTF8.GetBytes(b)).
                Select(block => new Hunk(block.StartSource, block.EndSource, block.StartDestination, block.EndDestination)).
                ToList();

            var lines = new List<HgDiffLineFragment>();

            Hunk prev = new Hunk();
            int oa = 0, ob = 0, idx = 0;
            for(var i = 0; i < diff.Count; ++i)
            {
                prev = i == 0 ? new Hunk() : diff[i - 1];
                var d = diff[i];
                int na = d.start_a, nb = d.start_b;

                lines.AddRange(al.Segment(oa, na).Select((l, il) => new HgDiffLineFragment(HgDiffFragmentType.Removed, l.TrimEnd('\n'), idx++, oa++, -1)));
                lines.AddRange(bl.Segment(ob, nb).Select((l, il) => new HgDiffLineFragment(HgDiffFragmentType.Added, l.TrimEnd('\n'), idx++, -1, ob++)));
                lines.AddRange(al.Segment(d.start_a, d.end_a).Select((l, il) => new HgDiffLineFragment(HgDiffFragmentType.Unchanged, l.TrimEnd('\n'), idx++, oa++, ob++)));


                oa = d.end_a;
                ob = d.end_b;
            }

            return new HgDiff(lines);
        }
Example #11
0
 public static Tuple <Hunk <string>, Hunk <string> > DefaultStringSelector(Segment seg, Hunk <string> hunk)
 {
     return(DefaultSelector <string>(seg, hunk, (x, y, z) => x.Substring(y.Start, y.Length)));
 }
Example #12
0
 public override bool MergeHunk(ref Hunk hunk)
 {
     return false;
 }
Example #13
0
 public HunkStateMachine(Hunk hunk)
 {
     this.hunk    = hunk;
     currentState = new HunkMoveState(hunk);
     player       = GameObject.FindGameObjectWithTag("Player");
 }
Example #14
0
 internal void ReceiveHunks(Document document, User user, int clientUpdateStamp, int serverUpdateStamp, Hunk[] hunks)
 {
     DocumentEditStateCollection documentEditStates = DataStoreClient.Get();
     DocumentEditState documentEditState = documentEditStates[document];
 }
Example #15
0
        /// <summary>
        /// This method creates a unified diff file.
        /// </summary>
        /// <param name="oldInfo">Provides the information for the old file (optional).</param>
        /// <param name="newInfo">Provides the information for the new file (optional).</param>
        /// <param name="streamOut">Stream where the diff file is written.</param>
        /// <param name="contextLines">Number of context lines around hunks.</param>
        /// <returns></returns>
        public static bool Create(UnifiedDiffInfo oldInfo, UnifiedDiffInfo newInfo, Stream streamOut, int contextLines)
        {
            if (streamOut == null)
            {
                throw new ArgumentException("streamOut must not be null");
            }
            if (contextLines < 0)
            {
                throw new ArgumentException("contextLines cannot be negative");
            }

            StreamReader    streamReader1 = new StreamReader(oldInfo != null && oldInfo.Stream != null ? oldInfo.Stream : new MemoryStream());
            StreamReader    streamReader2 = new StreamReader(newInfo != null && newInfo.Stream != null ? newInfo.Stream : new MemoryStream());
            StreamWriter    streamWriter = new StreamWriter(streamOut);
            List <DiffLine> lines1 = new List <DiffLine>();
            List <DiffLine> lines2 = new List <DiffLine>();
            string          line1, line2;
            int             start = 0, end = 0, firstLine = 0;

            // Read text stream into a list. If the beginning of the file matches, this only keeps the
            // the last contextLines number of lines in memory for the unified context of the
            // first hunk.  Diff.CreateDiff() actually would do this for us too, but we don't need
            // to waste a lot of memory if we're not going to use it anyway.

            do
            {
                line1 = streamReader1.ReadLine();
                line2 = streamReader2.ReadLine();

                if (line1 != null && line2 != null && string.Equals(line1, line2))
                {
                    lines1.Add(new DiffLine(firstLine, line1));
                    lines2.Add(new DiffLine(firstLine, line2));

                    if (start == contextLines)
                    {
                        lines1.RemoveAt(0);
                        lines2.RemoveAt(0);
                        firstLine++;
                    }
                    else
                    {
                        start++;
                    }
                    continue;
                }

                while (line1 != null)
                {
                    lines1.Add(new DiffLine(firstLine + lines1.Count, line1));
                    line1 = streamReader1.ReadLine();
                }

                while (line2 != null)
                {
                    lines2.Add(new DiffLine(firstLine + lines2.Count, line2));
                    line2 = streamReader2.ReadLine();
                }
            } while (line1 != null || line2 != null);

            // Also get rid of the last lines of the file if they are equal
            int endCnt    = Math.Min(lines1.Count, lines2.Count) - start;
            int removeEnd = 0;

            for (int i = 0; i < endCnt; i++)
            {
                if (string.Equals(lines1[lines1.Count - i - 1].line, lines2[lines2.Count - i - 1].line))
                {
                    if (end == contextLines)
                    {
                        removeEnd++;
                    }
                    else
                    {
                        end++;
                    }
                }
                else
                {
                    break;
                }
            }

            if (removeEnd > 0)
            {
                lines1.RemoveRange(lines1.Count - removeEnd, removeEnd);
                lines2.RemoveRange(lines2.Count - removeEnd, removeEnd);
            }

            // Now we've got a list of lines to compare.  The list context contains start
            // lines before the first difference, and end lines after the last difference.
            List <DiffEntry <DiffLine> > diffEntries = Diff.CreateDiff <DiffLine>(lines1, lines2, start, end);

            // Create a list of hunks and their lines including the context lines
            List <Hunk> hunks = new List <Hunk>();
            Hunk        hunk  = null;

            int l1 = firstLine, l2 = firstLine;

            for (int i = 0; i < diffEntries.Count; i++)
            {
                DiffEntry <DiffLine> entry = diffEntries[i];

                if (hunk == null)
                {
                    if (entry.EntryType == DiffEntry <DiffLine> .DiffEntryType.Equal)
                    {
                        int cnt = Math.Min(entry.Count, contextLines);
                        hunk = new Hunk(l1 + entry.Count - cnt, l2 + entry.Count - cnt);
                        for (int j = cnt; j > 0; j--)
                        {
                            hunk.AddContext(lines1[l1 + entry.Count - j - firstLine].line);
                        }
                        hunks.Add(hunk);
                        l1 += entry.Count;
                        l2 += entry.Count;
                        continue;
                    }

                    hunk = new Hunk(l1, l2);
                    hunks.Add(hunk);
                }

                switch (entry.EntryType)
                {
                case DiffEntry <DiffLine> .DiffEntryType.Add:
                    hunk.AddNew(lines2[l2 - firstLine].line);
                    l2++;
                    break;

                case DiffEntry <DiffLine> .DiffEntryType.Remove:
                    hunk.AddRemove(lines1[l1 - firstLine].line);
                    l1++;
                    break;

                case DiffEntry <DiffLine> .DiffEntryType.Equal:
                    if (i == diffEntries.Count - 1)
                    {
                        int cnt = Math.Min(contextLines, entry.Count);
                        for (int j = 0; j < cnt; j++)
                        {
                            hunk.AddContext(lines1[l1 + j - firstLine].line);
                        }
                    }
                    else
                    {
                        if (entry.Count > 2 * contextLines)
                        {
                            for (int j = 0; j < contextLines; j++)
                            {
                                hunk.AddContext(lines1[l1 + j - firstLine].line);
                            }
                            l1 += entry.Count;
                            l2 += entry.Count;

                            hunk = new Hunk(l1 - contextLines, l2 - contextLines);
                            for (int j = contextLines; j > 0; j--)
                            {
                                hunk.AddContext(lines1[l1 - j - firstLine].line);
                            }
                            hunks.Add(hunk);
                        }
                        else
                        {
                            for (int j = 0; j < entry.Count; j++)
                            {
                                hunk.AddContext(lines1[l1 + j - firstLine].line);
                            }
                            l1 += entry.Count;
                            l2 += entry.Count;
                        }
                    }
                    break;
                }
            }

            if (hunks.Count > 0)
            {
                // Write the hunks to the output stream
                if (oldInfo != null && !string.IsNullOrEmpty(oldInfo.Label))
                {
                    streamWriter.WriteLine(string.Format("--- {0}", oldInfo.Label));
                }
                if (newInfo != null && !string.IsNullOrEmpty(newInfo.Label))
                {
                    streamWriter.WriteLine(string.Format("+++ {0}", newInfo.Label));
                }

                foreach (var hk in hunks)
                {
                    hk.Write(streamWriter);
                }

                streamWriter.WriteLine();
                streamWriter.Flush();
                return(true);
            }

            return(false);
        }
        Tuple <List <Cairo.Rectangle>, List <Cairo.Rectangle> > GetDiffPaths(List <Hunk> diff, MonoTextEditor editor, Hunk hunk)
        {
            if (!diffCache.ContainsKey(diff))
            {
                diffCache[diff] = new Dictionary <Hunk, Tuple <List <Cairo.Rectangle>, List <Cairo.Rectangle> > > ();
            }
            var pathCache = diffCache[diff];

            Tuple <List <Cairo.Rectangle>, List <Cairo.Rectangle> > result;

            if (pathCache.TryGetValue(hunk, out result))
            {
                return(result);
            }

            var words    = BreakTextInWords(editor, hunk.RemoveStart, hunk.Removed);
            var cmpWords = BreakTextInWords(MainEditor, hunk.InsertStart, hunk.Inserted);

            var wordDiff = new List <Hunk> (Diff.GetDiff(words.Select(editor.GetTextAt).ToArray(),
                                                         cmpWords.Select(MainEditor.GetTextAt).ToArray()));

            result = Tuple.Create(CalculateChunkPath(editor, wordDiff, words, true),
                                  CalculateChunkPath(MainEditor, wordDiff, cmpWords, false));

            pathCache[hunk] = result;
            return(result);
        }
        private IEnumerable<string> yield_hunk(Hunk hunk, List<string> header, List<string> l1, List<string> delta)
        {
            if(header != null && header.Count > 0)
                foreach(var h in header) yield return h;

            delta = hunk.delta.ToList();
            int astart = hunk.start_a, a2 = hunk.end_a, bstart = hunk.start_b, b2 = hunk.end_b;
            var aend = context_end(a2, l1.Count);
            var alen = aend - astart;
            var blen = b2 - bstart + aend - a2;

            yield return string.Format("@@ -{0},{1} +{2},{3} @@", astart + 1, alen, bstart + 1, blen);

            foreach(var d in delta) yield return d;

            for(var i = a2; i < aend - 1L; ++i)
                yield return l1[i];

        }
Example #18
0
 public HunkHurtState(Hunk hunk)
 {
     this.hunk = hunk;
     stateName = "hurt";
 }
Example #19
0
 public bool Equals(Hunk <T> other)
 {
     return(base.Equals(other));
 }
Example #20
0
        internal override void UndoChange(MonoTextEditor fromEditor, MonoTextEditor toEditor, Hunk hunk)
        {
            base.UndoChange(fromEditor, toEditor, hunk);
            int i = leftConflicts.IndexOf(hunk);

            if (i < 0)
            {
                i = rightConflicts.IndexOf(hunk);
            }
            // no conflicting change
            if (i < 0)
            {
                return;
            }
            currentConflicts.RemoveAt(i);

/*			var startLine = MainEditor.Document.GetLineByOffset (hunk.InsertStart);
 *                      var endline   = MainEditor.Document.GetLineByOffset (hunk.InsertStart + hunk.Inserted);
 *
 *                      currentConflicts[i].StartSegment.Offset = startLine.EndOffset;
 *                      currentConflicts[i].EndSegment.Offset = endline.EndOffset;
 */
            UpdateDiff();
        }
Example #21
0
        private static Tuple <Hunk <T>, Hunk <T> > CompatibilitySelector(Segment seg, Hunk <T> hunk, TypedShakeSelector <T> selector)
        {
            var r = selector(new TypedSegment(seg, string.Empty), new Token <T>(hunk));

            return(new Tuple <Hunk <T>, Hunk <T> >(r.Item1, r.Item2));
        }
 private Color GetColor(Hunk hunk, bool removeSide, bool dark)
 {
     return(EditorCompareWidgetBase.GetColor(hunk, removeSide, dark, 1.0));
 }
		private Color GetColor (Hunk hunk, bool removeSide, bool dark)
		{
			return EditorCompareWidgetBase.GetColor (hunk, removeSide, dark, 1.0);
		}
Example #24
0
        public void AppendHunk(Hunk hunk, User user)
        {
            foreach (EditOperation editOperation in GetUsersOpenEditOperations(user).OrderByDescending(lambdaEditOperation => lambdaEditOperation.Hunks.Min(lambdaHunk => lambdaHunk.StartIndex)))
            {
                editOperation.MergeHunk(ref hunk);
                if (hunk == null) break;
            }
            if (hunk is InsertionHunk)
            {
                var operation = new InsertOperation();
                GetUsersChangeSubset(user).EditOperations.Add(operation);

                operation.Hunks.Add(hunk);
            }
            else if (hunk is DeletionHunk)
            {
                var operation = new DeleteOperation();
                GetUsersChangeSubset(user).EditOperations.Add(operation);
                operation.Hunks.Add(hunk);
            }
            else throw new InvalidOperationException("Cannot create No-Operation operation");
        }
			static void IncPos (Hunk h, ref int pos)
			{
				pos += System.Math.Max (h.Inserted, h.Removed);
			}
Example #26
0
        protected virtual void UndoChange(TextEditor fromEditor, TextEditor toEditor, Hunk hunk)
        {
            using (var undo = toEditor.OpenUndoGroup()) {
                var start    = toEditor.Document.GetLine(hunk.InsertStart);
                int toOffset = start != null ? start.Offset : toEditor.Document.Length;
                if (start != null && hunk.Inserted > 0)
                {
                    int line = Math.Min(hunk.InsertStart + hunk.Inserted - 1, toEditor.Document.LineCount);
                    var end  = toEditor.Document.GetLine(line);
                    toEditor.Remove(start.Offset, end.EndOffset - start.Offset);
                }

                if (hunk.Removed > 0)
                {
                    start = fromEditor.Document.GetLine(Math.Min(hunk.RemoveStart, fromEditor.Document.LineCount));
                    int line = Math.Min(hunk.RemoveStart + hunk.Removed - 1, fromEditor.Document.LineCount);
                    var end  = fromEditor.Document.GetLine(line);
                    toEditor.Insert(toOffset, start.Offset == end.EndOffset ? toEditor.EolMarker : fromEditor.Document.GetTextBetween(start.Offset, end.EndOffset));
                }
            }
        }
		protected virtual void UndoChange (MonoTextEditor fromEditor, MonoTextEditor toEditor, Hunk hunk)
		{
			using (var undo = toEditor.OpenUndoGroup ()) {
				var start = toEditor.Document.GetLine (hunk.InsertStart);
				int toOffset = start != null ? start.Offset : toEditor.Document.TextLength;

				int replaceLength = 0;
				if (start != null && hunk.Inserted > 0) {
					int line = Math.Min (hunk.InsertStart + hunk.Inserted - 1, toEditor.Document.LineCount);
					var end = toEditor.Document.GetLine (line);
					replaceLength = end.EndOffsetIncludingDelimiter - start.Offset;
				}
	
				if (hunk.Removed > 0) {
					start = fromEditor.Document.GetLine (Math.Min (hunk.RemoveStart, fromEditor.Document.LineCount));
					int line = Math.Min (hunk.RemoveStart + hunk.Removed - 1, fromEditor.Document.LineCount);
					var end = fromEditor.Document.GetLine (line);
					toEditor.Replace (
						toOffset,
						replaceLength,
						fromEditor.Document.GetTextBetween (start.Offset, end.EndOffsetIncludingDelimiter)
					);
				} else if (replaceLength > 0) {
					toEditor.Remove (toOffset, replaceLength);
				}
			}
		}
		public static Cairo.Color GetColor (Hunk hunk, bool removeSide, bool border, double alpha)
		{
			Xwt.Drawing.Color result;
			if (hunk.Removed > 0 && hunk.Inserted > 0) {
				result = border ? Styles.DiffView.MergeBackgroundColor : Styles.DiffView.MergeBorderColor;
			} else if (removeSide) {
				if (hunk.Removed > 0) {
					result = border ? Styles.DiffView.RemoveBackgroundColor : Styles.DiffView.RemoveBorderColor;
				} else {
					result = border ? Styles.DiffView.AddBackgroundColor : Styles.DiffView.AddBorderColor;
				}
			} else {
				if (hunk.Inserted > 0) {
					result = border ? Styles.DiffView.AddBackgroundColor : Styles.DiffView.AddBorderColor;
				} else {
					result = border ? Styles.DiffView.RemoveBackgroundColor : Styles.DiffView.RemoveBorderColor;
				}
			}
			result.Alpha = alpha;
			return result.ToCairoColor ();
		}
			protected override bool OnLeaveNotifyEvent (EventCrossing evnt)
			{
				selectedHunk = Hunk.Empty;
				TooltipText = null;
				QueueDraw ();
				return base.OnLeaveNotifyEvent (evnt);
			}
Example #30
0
        protected override void UndoChange(TextEditor fromEditor, TextEditor toEditor, Hunk hunk)
        {
            base.UndoChange(fromEditor, toEditor, hunk);
            int i = leftConflicts.IndexOf(hunk);

            if (i < 0)
            {
                i = rightConflicts.IndexOf(hunk);
            }

            // no conflicting change
            if (i < 0)
            {
                return;
            }

            var startLine = MainEditor.Document.GetLineByOffset(hunk.InsertStart);
            var endline   = MainEditor.Document.GetLineByOffset(hunk.InsertStart + hunk.Inserted);

            currentConflicts[i].StartSegment.Offset = startLine.EndOffset;
            currentConflicts[i].EndSegment.Offset   = endline.EndOffset;

            UpdateDiff();
        }
 static void IncPos(Hunk h, ref int pos)
 {
     pos += System.Math.Max(h.Inserted, h.Removed);
 }
Example #32
0
 public HunkMoveState(Hunk hunk)
 {
     this.hunk = hunk;
     stateName = "move";
 }
        internal virtual void UndoChange(MonoTextEditor fromEditor, MonoTextEditor toEditor, Hunk hunk)
        {
            using (var undo = toEditor.OpenUndoGroup()) {
                var start    = toEditor.Document.GetLine(hunk.InsertStart);
                int toOffset = start != null ? start.Offset : toEditor.Document.Length;

                int replaceLength = 0;
                if (start != null && hunk.Inserted > 0)
                {
                    int line = Math.Min(hunk.InsertStart + hunk.Inserted - 1, toEditor.Document.LineCount);
                    var end  = toEditor.Document.GetLine(line);
                    replaceLength = end.EndOffsetIncludingDelimiter - start.Offset;
                }

                if (hunk.Removed > 0)
                {
                    start = fromEditor.Document.GetLine(Math.Min(hunk.RemoveStart, fromEditor.Document.LineCount));
                    int line = Math.Min(hunk.RemoveStart + hunk.Removed - 1, fromEditor.Document.LineCount);
                    var end  = fromEditor.Document.GetLine(line);
                    toEditor.Replace(
                        toOffset,
                        replaceLength,
                        fromEditor.Document.GetTextBetween(start.Offset, end.EndOffsetIncludingDelimiter)
                        );
                }
                else if (replaceLength > 0)
                {
                    toEditor.Remove(toOffset, replaceLength);
                }
            }
        }
Example #34
0
			public OverviewRenderer(ScrolledWindow scroller, Hunk[] hunks, bool sidebyside) {
				this.scroller = scroller;
				this.ButtonPressEvent += ButtonPressHandler;
				Add(new OverviewRenderer2(scroller, hunks, sidebyside));
			}
		Tuple<List<Cairo.Rectangle>, List<Cairo.Rectangle>> GetDiffPaths (List<Mono.TextEditor.Utils.Hunk> diff, TextEditor editor, Hunk hunk)
		{
			if (!diffCache.ContainsKey (diff))
				diffCache[diff] = new Dictionary<Hunk, Tuple<List<Cairo.Rectangle>, List<Cairo.Rectangle>>> ();
			var pathCache = diffCache[diff];
			
			Tuple<List<Cairo.Rectangle>, List<Cairo.Rectangle>> result;
			if (pathCache.TryGetValue (hunk, out result))
				return result;
			
			var words = BreakTextInWords (editor, hunk.RemoveStart, hunk.Removed);
			var cmpWords = BreakTextInWords (MainEditor, hunk.InsertStart, hunk.Inserted);
			
			var wordDiff = new List<Hunk> (Diff.GetDiff (words.Select (w => editor.GetTextAt (w)).ToArray (),
				cmpWords.Select (w => MainEditor.GetTextAt (w)).ToArray ()));
			
			result = Tuple.Create (CalculateChunkPath (editor, wordDiff, words, true), 
				CalculateChunkPath (MainEditor, wordDiff, cmpWords, false));
			
			pathCache[hunk] = result;
			return result;
		}
Example #36
0
			public OverviewRenderer2(ScrolledWindow scroller, Hunk[] hunks, bool sidebyside) {
				this.hunks = hunks;
				this.scroller = scroller;
				this.sidebyside = sidebyside;
				this.ExposeEvent += OnExposed;
				scroller.ExposeEvent += OnScroll;
				WidthRequest = 50;
			}
Example #37
0
 public Token(Hunk <T> hunk)
     : this(hunk.Value, string.Empty, hunk.Length, hunk.Start, hunk.IsBig)
 {
 }
Example #38
0
			private void IncPos(Hunk h, ref int pos) {
				if (sidebyside)
					pos += h.MaxLines();
				else if (h.Same)
					pos += h.Original().Count;
				else {
					pos += h.Original().Count;
					for (int i = 0; i < h.ChangedLists; i++)
						pos += h.Changes(i).Count;
				}
			}
Example #39
0
        /// <summary>
        /// This method creates a unified diff file.
        /// </summary>
        /// <param name="oldInfo">Provides the information for the old file (optional).</param>
        /// <param name="newInfo">Provides the information for the new file (optional).</param>
        /// <param name="streamOut">Stream where the diff file is written.</param>
        /// <param name="contextLines">Number of context lines around hunks.</param>
        /// <returns></returns>
        public static bool Create(UnifiedDiffInfo oldInfo, UnifiedDiffInfo newInfo, Stream streamOut, int contextLines)
        {
            if (streamOut == null)
                throw new ArgumentException("streamOut must not be null");
            if (contextLines < 0)
                throw new ArgumentException("contextLines cannot be negative");

            StreamReader streamReader1 = new StreamReader(oldInfo != null && oldInfo.Stream != null ? oldInfo.Stream : new MemoryStream());
            StreamReader streamReader2 = new StreamReader(newInfo != null && newInfo.Stream != null ? newInfo.Stream : new MemoryStream());
            StreamWriter streamWriter = new StreamWriter(streamOut);
            List<DiffLine> lines1 = new List<DiffLine>();
            List<DiffLine> lines2 = new List<DiffLine>();
            string line1, line2;
            int start = 0, end = 0, firstLine = 0;

            // Read text stream into a list. If the beginning of the file matches, this only keeps the
            // the last contextLines number of lines in memory for the unified context of the
            // first hunk.  Diff.CreateDiff() actually would do this for us too, but we don't need
            // to waste a lot of memory if we're not going to use it anyway.

            do
            {
                line1 = streamReader1.ReadLine();
                line2 = streamReader2.ReadLine();

                if (line1 != null && line2 != null && string.Equals(line1, line2))
                {
                    lines1.Add(new DiffLine(firstLine, line1));
                    lines2.Add(new DiffLine(firstLine, line2));

                    if (start == contextLines)
                    {
                        lines1.RemoveAt(0);
                        lines2.RemoveAt(0);
                        firstLine++;
                    }
                    else
                        start++;
                    continue;
                }

                while (line1 != null)
                {
                    lines1.Add(new DiffLine(firstLine + lines1.Count, line1));
                    line1 = streamReader1.ReadLine();
                }

                while (line2 != null)
                {
                    lines2.Add(new DiffLine(firstLine + lines2.Count, line2));
                    line2 = streamReader2.ReadLine();
                }

            } while (line1 != null || line2 != null);

            // Also get rid of the last lines of the file if they are equal
            int endCnt = Math.Min(lines1.Count, lines2.Count) - start;
            int removeEnd = 0;
            for (int i = 0; i < endCnt; i++)
            {
                if (string.Equals(lines1[lines1.Count - i - 1].line, lines2[lines2.Count - i - 1].line))
                {
                    if (end == contextLines)
                        removeEnd++;
                    else
                        end++;
                }
                else
                    break;
            }

            if (removeEnd > 0)
            {
                lines1.RemoveRange(lines1.Count - removeEnd, removeEnd);
                lines2.RemoveRange(lines2.Count - removeEnd, removeEnd);
            }

            // Now we've got a list of lines to compare.  The list context contains start
            // lines before the first difference, and end lines after the last difference.
            List<DiffEntry<DiffLine>> diffEntries = Diff.CreateDiff<DiffLine>(lines1, lines2, start, end);

            // Create a list of hunks and their lines including the context lines
            List<Hunk> hunks = new List<Hunk>();
            Hunk hunk = null;

            int l1 = firstLine, l2 = firstLine;
            for (int i = 0; i < diffEntries.Count; i++)
            {
                DiffEntry<DiffLine> entry = diffEntries[i];

                if (hunk == null)
                {
                    if (entry.EntryType == DiffEntry<DiffLine>.DiffEntryType.Equal)
                    {
                        int cnt = Math.Min(entry.Count, contextLines);
                        hunk = new Hunk(l1 + entry.Count - cnt, l2 + entry.Count - cnt);
                        for (int j = cnt; j > 0; j--)
                            hunk.AddContext(lines1[l1 + entry.Count - j - firstLine].line);
                        hunks.Add(hunk);
                        l1 += entry.Count;
                        l2 += entry.Count;
                        continue;
                    }

                    hunk = new Hunk(l1, l2);
                    hunks.Add(hunk);
                }

                switch (entry.EntryType)
                {
                    case DiffEntry<DiffLine>.DiffEntryType.Add:
                        hunk.AddNew(lines2[l2 - firstLine].line);
                        l2++;
                        break;
                    case DiffEntry<DiffLine>.DiffEntryType.Remove:
                        hunk.AddRemove(lines1[l1 - firstLine].line);
                        l1++;
                        break;
                    case DiffEntry<DiffLine>.DiffEntryType.Equal:
                        if (i == diffEntries.Count - 1)
                        {
                            int cnt = Math.Min(contextLines, entry.Count);
                            for (int j = 0; j < cnt; j++)
                                hunk.AddContext(lines1[l1 + j - firstLine].line);
                        }
                        else
                        {
                            if (entry.Count > 2 * contextLines)
                            {
                                for (int j = 0; j < contextLines; j++)
                                    hunk.AddContext(lines1[l1 + j - firstLine].line);
                                l1 += entry.Count;
                                l2 += entry.Count;

                                hunk = new Hunk(l1 - contextLines, l2 - contextLines);
                                for (int j = contextLines; j > 0; j--)
                                    hunk.AddContext(lines1[l1 - j - firstLine].line);
                                hunks.Add(hunk);
                            }
                            else
                            {
                                for (int j = 0; j < entry.Count; j++)
                                    hunk.AddContext(lines1[l1 + j - firstLine].line);
                                l1 += entry.Count;
                                l2 += entry.Count;
                            }
                        }
                        break;
                }
            }

            if (hunks.Count > 0)
            {
                // Write the hunks to the output stream
                if (oldInfo != null && !string.IsNullOrEmpty(oldInfo.Label))
                    streamWriter.WriteLine(string.Format("--- {0}", oldInfo.Label));
                if (newInfo != null && !string.IsNullOrEmpty(newInfo.Label))
                    streamWriter.WriteLine(string.Format("+++ {0}", newInfo.Label));

                foreach (var hk in hunks)
                    hk.Write(streamWriter);

                streamWriter.WriteLine();
                streamWriter.Flush();
                return true;
            }

            return false;
        }
Example #40
0
		private DiffWidget(Hunk[] hunks, Options options) : base(false, 0) {
			if (hunks == null || hunks.Length == 0 || options == null)
				throw new ArgumentException();
			
			if (options.SideBySide && options.LeftName != null && options.RightName != null) {
				HBox filetitles = new HBox(true, 2);
				PackStart(filetitles, false, false, 2);
				Label leftlabel = new Label(options.LeftName);
				Label rightlabel = new Label(options.RightName);
				filetitles.PackStart(leftlabel);
				filetitles.PackStart(rightlabel);
			}
			
			HBox centerpanel = new HBox(false, 0);
			PackStart(centerpanel);

			scroller = new ScrolledWindow();
			
			centerpanel.PackStart(new OverviewRenderer(scroller, hunks, options.SideBySide), false, false, 0);
			
			Viewport textviewport = new Viewport();
			
			centerpanel.PackStart(scroller);
			scroller.Add(textviewport);
			
			int nRows = 0;
			foreach (Hunk hunk in hunks) {
				if (options.SideBySide) {
					nRows += hunk.MaxLines();
				} else {
					if (hunk.Same) {
						nRows += hunk.Original().Count;
					} else {
						for (int i = 0; i < hunk.ChangedLists; i++)
							nRows += hunk.Changes(i).Count;
					}
				}
			}
			
			uint nCols = 1 + (uint)hunks[0].ChangedLists;
			if (options.SideBySide) nCols += 2;
			if (options.LineNumbers) nCols++;
			
			VBox tablecontainer = new VBox(false, 0);
			textviewport.Add(tablecontainer);
			
			Table difftable = new Table((uint)nRows, (uint)nCols, false);
			tablecontainer.PackStart(difftable, false, false, 0);	
			
			uint row = 0;
			
			Pango.FontDescription font = null;
			if (options.Font != null)
				font = Pango.FontDescription.FromString(options.Font);
			
			foreach (Hunk hunk in hunks) {
				char leftmode = hunk.Same ? ' ' : (hunk.ChangedLists == 1 && hunk.Changes(0).Count == 0) ? '-' : 'C';
				uint inc = 0;
				
				if (options.SideBySide) {
					ComposeLines(hunk.Original(), leftmode, -1, difftable, row, false, 0, options.LineWrap, font, options.LineNumbers);
					inc = (uint)hunk.Original().Count;
				} else { 
					if (leftmode == 'C') leftmode = '-';
					int altlines = -1;
					if (hunk.ChangedLists == 1 && hunk.Same)
						altlines = hunk.Changes(0).Start;
					ComposeLines(hunk.Original(), leftmode, altlines, difftable, row, true, 0, options.LineWrap, font, options.LineNumbers);
					row += (uint)hunk.Original().Count;
				}

				for (int i = 0; i < hunk.ChangedLists; i++) {
					char rightmode = hunk.Same ? ' ' : hunk.Original().Count == 0 ? '+' : 'C';
					
					if (options.SideBySide) {
						int colsper = 1 + (options.LineNumbers ? 1 : 0);			
						ComposeLines(hunk.Changes(i), rightmode, -1, difftable, row, false, (uint)((i+1)*colsper), options.LineWrap, font, options.LineNumbers);
						if (hunk.Changes(i).Count > inc)
							inc = (uint)hunk.Changes(i).Count;
					} else {
						if (rightmode == 'C') rightmode = '+';
		
						if (!hunk.Same) 
							ComposeLines(hunk.Changes(i), rightmode, -1, difftable, row, true, 0, options.LineWrap, font, options.LineNumbers);
						
						if (!hunk.Same) row += (uint)hunk.Changes(i).Count;
					}
				}
				
				if (options.SideBySide)
					row += inc;
			}
		}
Example #41
0
        internal override void UndoChange(MonoTextEditor fromEditor, MonoTextEditor toEditor, Hunk hunk)
        {
            base.UndoChange(fromEditor, toEditor, hunk);

            for (int i = 0; i < currentConflicts.Count; i++)
            {
                if (currentConflicts [i].LeftHunk == hunk || currentConflicts [i].RightHunk == hunk)
                {
                    currentConflicts.RemoveAt(i);
                    UpdateDiff();
                    break;
                }
            }
        }
Example #42
0
 public IEnumerable <Token <T> > TypedShake(Hunk <T> input, IEnumerable <TypedShakeCondition <T> > conds)
 {
     return(TypedShake(new Token <T>(input), conds));
 }