#include "config.h"
#include <sys/types.h>
#include <sys/queue.h>
#include <sys/time.h>
#include <bitstring.h>
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include "../common/common.h"
#include "vi.h"
int
v_match(SCR *sp, VICMD *vp)
{
VCS cs;
MARK *mp;
size_t cno, len, off;
int cnt, isempty, matchc, startc, (*gc)(SCR *, VCS *);
char *p;
if (db_eget(sp, vp->m_start.lno, &p, &len, &isempty)) {
if (isempty)
goto nomatch;
return (1);
}
for (off = vp->m_start.cno;; ++off) {
if (off >= len) {
nomatch: msgq(sp, M_BERR, "No match character on this line");
return (1);
}
switch (startc = p[off]) {
case '(':
matchc = ')';
gc = cs_next;
break;
case ')':
matchc = '(';
gc = cs_prev;
break;
case '[':
matchc = ']';
gc = cs_next;
break;
case ']':
matchc = '[';
gc = cs_prev;
break;
case '{':
matchc = '}';
gc = cs_next;
break;
case '}':
matchc = '{';
gc = cs_prev;
break;
case '<':
matchc = '>';
gc = cs_next;
break;
case '>':
matchc = '<';
gc = cs_prev;
break;
default:
continue;
}
break;
}
cs.cs_lno = vp->m_start.lno;
cs.cs_cno = off;
if (cs_init(sp, &cs))
return (1);
for (cnt = 1;;) {
if (gc(sp, &cs))
return (1);
if (cs.cs_flags != 0) {
if (cs.cs_flags == CS_EOF || cs.cs_flags == CS_SOF)
break;
continue;
}
if (cs.cs_ch == startc)
++cnt;
else if (cs.cs_ch == matchc && --cnt == 0)
break;
}
if (cnt) {
msgq(sp, M_BERR, "Matching character not found");
return (1);
}
vp->m_stop.lno = cs.cs_lno;
vp->m_stop.cno = cs.cs_cno;
if (vp->m_start.lno < vp->m_stop.lno ||
(vp->m_start.lno == vp->m_stop.lno &&
vp->m_start.cno < vp->m_stop.cno))
vp->m_final = ISMOTION(vp) ? vp->m_start : vp->m_stop;
else
vp->m_final = vp->m_stop;
if (!ISMOTION(vp) || vp->m_start.lno == vp->m_stop.lno)
return (0);
mp = vp->m_start.lno < vp->m_stop.lno ? &vp->m_start : &vp->m_stop;
if (mp->cno != 0) {
cno = 0;
if (nonblank(sp, mp->lno, &cno))
return (1);
if (cno < mp->cno)
return (0);
}
mp = vp->m_start.lno < vp->m_stop.lno ? &vp->m_stop : &vp->m_start;
if (db_get(sp, mp->lno, DBG_FATAL, &p, &len))
return (1);
for (p += mp->cno + 1, len -= mp->cno; --len; ++p)
if (!isblank(*p))
return (0);
F_SET(vp, VM_LMODE);
return (0);
}