diff --git a/acedoc.go b/acedoc.go index 2de1e4e..3f4811b 100644 --- a/acedoc.go +++ b/acedoc.go @@ -74,8 +74,11 @@ func (d Delta) rows() int { } func (d Delta) cols() int { - r := int(d.End.Column) - int(d.Start.Column) - return r + if d.Start.Row == d.End.Row { + return int(d.End.Column) - int(d.Start.Column) + } else { + return int(d.End.Column) + } } func (d *Document) Contents() string { diff --git a/delta.go b/delta.go index 0076199..b67de9b 100644 --- a/delta.go +++ b/delta.go @@ -112,24 +112,33 @@ func (d Delta) Equal(other Delta) bool { } func Remove(row, col uint, str string) Delta { - lines := strings.Split(str, "\n") - nlines := len(lines) - 1 - return Delta{ - Action: DeltaRemove, - Lines: lines, - Start: Position{row, col}, - End: Position{row + uint(nlines), uint(len(lines[nlines]))}, - } + dl := Insert(row, col, str) + dl.Action = DeltaRemove + return dl } func Insert(row, col uint, str string) Delta { lines := strings.Split(str, "\n") - nlines := uint(len(lines) - 1) + + var endcol uint + addedLines := uint(len(lines) - 1) + + if len(lines) == 0 { + addedLines = 1 + } else { + lastLine := lines[len(lines)-1] + endcol += uint(len(lastLine)) + } + + if addedLines == 0 { + endcol += col + } + return Delta{ Action: DeltaInsert, Lines: lines, Start: Position{row, col}, - End: Position{row + nlines, uint(len(lines[nlines]))}, + End: Position{row + addedLines, endcol}, } } @@ -215,7 +224,7 @@ func (d *Document) validate(dl Delta) error { } if dl.Action == DeltaRemove && !d.InDocument(dl.End) { - return fmt.Errorf("end is not in document for remove") + return fmt.Errorf("end %v is not in document %q for remove", dl.End, d.contents()) } if dl.nLines() != dl.nRows() {