+ // check if the given co-ordinates are inside an inset at the
+ // given cursor, if one exists. If so, the inset is returned,
+ // and the co-ordinates are made relative. Otherwise, 0 is returned.
+ Inset * checkInset(BufferView * bv, LyXText const & text,
+ LyXCursor const & cur, int & x, int & y)
+ {
+ lyx::pos_type const pos = cur.pos();
+ Paragraph /*const*/ & par = *cur.par();
+
+ if (pos >= par.size() || !par.isInset(pos))
+ return 0;
+
+ Inset /*const*/ * inset = par.getInset(pos);
+
+ if (!isEditableInset(inset))
+ return 0;
+
+ // get inset dimensions
+ lyx::Assert(par.getInset(pos));
+
+ LyXFont const & font = text.getFont(bv->buffer(), &par, pos);
+
+ int const width = inset->width(bv, font);
+ int const inset_x = font.isVisibleRightToLeft()
+ ? (cur.ix() - width) : cur.ix();
+
+ Box b(
+ inset_x + inset->scroll(),
+ inset_x + width,
+ cur.iy() - inset->ascent(bv, font),
+ cur.iy() + inset->descent(bv, font)
+ );
+
+ if (!b.contained(x, y)) {
+ lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y
+ << " box " << b << endl;
+ return 0;
+ }
+
+ text.setCursor(bv, &par, pos, true);
+
+ x -= b.x1;
+ // The origin of an inset is on the baseline
+ y -= text.cursor.iy();
+
+ return inset;
+ }
+
+} // anon namespace
+
+
+Inset * LyXText::checkInsetHit(BufferView * bv, int & x, int & y) const
+{
+ int y_tmp = y + first_y;
+
+ LyXCursor cur;
+ setCursorFromCoordinates(bv, cur, x, y_tmp);
+
+ Inset * inset = checkInset(bv, *this, cur, x, y_tmp);
+ if (inset) {
+ y = y_tmp;
+ return inset;
+ }
+
+ // look at previous position
+ if (cur.pos() == 0)
+ return 0;
+
+ // move back one
+ setCursor(bv, cur, cur.par(), cur.pos() - 1, true);
+
+ inset = checkInset(bv, *this, cur, x, y_tmp);
+ if (inset)
+ y = y_tmp;
+ return inset;