2 * Copyright (c) 1992, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1992, 1993, 1994, 1995, 1996
5 * Keith Bostic. All rights reserved.
7 * See the LICENSE file for redistribution information.
13 static const char sccsid
[] = "$Id: delete.c,v 10.18 2012/02/11 15:52:33 zy Exp $";
16 #include <sys/types.h>
17 #include <sys/queue.h>
20 #include <bitstring.h>
31 * Delete a range of text.
33 * PUBLIC: int del(SCR *, MARK *, MARK *, int);
43 size_t blen
, len
, nlen
, tlen
;
49 /* Case 1 -- delete in line mode. */
51 for (lno
= tm
->lno
; lno
>= fm
->lno
; --lno
) {
52 if (db_delete(sp
, lno
))
54 ++sp
->rptlines
[L_DELETED
];
55 if (lno
% INTERRUPT_CHECK
== 0 && INTERRUPTED(sp
))
62 * Case 2 -- delete to EOF. This is a special case because it's
63 * easier to pick it off than try and find it in the other cases.
65 if (db_last(sp
, &lno
))
69 if (db_get(sp
, lno
, DBG_FATAL
, &p
, &len
))
71 eof
= tm
->cno
!= ENTIRE_LINE
&& tm
->cno
>= len
? 1 : 0;
75 for (lno
= tm
->lno
; lno
> fm
->lno
; --lno
) {
76 if (db_delete(sp
, lno
))
78 ++sp
->rptlines
[L_DELETED
];
80 INTERRUPT_CHECK
== 0 && INTERRUPTED(sp
))
83 if (db_get(sp
, fm
->lno
, DBG_FATAL
, &p
, &len
))
85 GET_SPACE_RETW(sp
, bp
, blen
, fm
->cno
);
86 MEMCPY(bp
, p
, fm
->cno
);
87 if (db_set(sp
, fm
->lno
, bp
, fm
->cno
))
93 /* Case 3 -- delete within a single line. */
94 if (tm
->lno
== fm
->lno
) {
95 if (db_get(sp
, fm
->lno
, DBG_FATAL
, &p
, &len
))
97 GET_SPACE_RETW(sp
, bp
, blen
, len
);
99 MEMCPY(bp
, p
, fm
->cno
);
100 MEMCPY(bp
+ fm
->cno
, p
+ (tm
->cno
+ 1),
101 len
- (tm
->cno
+ 1));
102 if (db_set(sp
, fm
->lno
,
103 bp
, len
- ((tm
->cno
- fm
->cno
) + 1)))
109 * Case 4 -- delete over multiple lines.
111 * Copy the start partial line into place.
113 if ((tlen
= fm
->cno
) != 0) {
114 if (db_get(sp
, fm
->lno
, DBG_FATAL
, &p
, NULL
))
116 GET_SPACE_RETW(sp
, bp
, blen
, tlen
+ 256);
120 /* Copy the end partial line into place. */
121 if (db_get(sp
, tm
->lno
, DBG_FATAL
, &p
, &len
))
123 if (len
!= 0 && tm
->cno
!= len
- 1) {
126 * We can overflow memory here, if the total length is greater
127 * than SIZE_T_MAX. The only portable way I've found to test
128 * is depending on the overflow being less than the value.
130 nlen
= (len
- (tm
->cno
+ 1)) + tlen
;
132 msgq(sp
, M_ERR
, "002|Line length overflow");
136 GET_SPACE_RETW(sp
, bp
, blen
, nlen
);
138 ADD_SPACE_RETW(sp
, bp
, blen
, nlen
);
140 MEMCPY(bp
+ tlen
, p
+ (tm
->cno
+ 1), len
- (tm
->cno
+ 1));
141 tlen
+= len
- (tm
->cno
+ 1);
144 /* Set the current line. */
145 if (db_set(sp
, fm
->lno
, bp
, tlen
))
148 /* Delete the last and intermediate lines. */
149 for (lno
= tm
->lno
; lno
> fm
->lno
; --lno
) {
150 if (db_delete(sp
, lno
))
152 ++sp
->rptlines
[L_DELETED
];
153 if (lno
% INTERRUPT_CHECK
== 0 && INTERRUPTED(sp
))
161 FREE_SPACEW(sp
, bp
, blen
);