]> git.lyx.org Git - lyx.git/blob - src/mathed/MathData.cpp
253a888c745eae46e9b70832dc3b3cfd3753193b
[lyx.git] / src / mathed / MathData.cpp
1 /**
2  * \file MathData.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "MathData.h"
15
16 #include "InsetMathBrace.h"
17 #include "InsetMathFont.h"
18 #include "InsetMathScript.h"
19 #include "MacroTable.h"
20 #include "MathMacro.h"
21 #include "MathStream.h"
22 #include "MathSupport.h"
23 #include "MetricsInfo.h"
24 #include "ReplaceData.h"
25
26 #include "Buffer.h"
27 #include "BufferView.h"
28 #include "CoordCache.h"
29 #include "Cursor.h"
30 #include "support/debug.h"
31
32 #include "support/docstream.h"
33
34 #include "frontends/FontMetrics.h"
35 #include "frontends/Painter.h"
36
37 #include <boost/assert.hpp>
38 #include <boost/next_prior.hpp>
39
40
41 namespace lyx {
42
43 using std::abs;
44 using std::endl;
45 using std::min;
46 using std::ostringstream;
47 using std::string;
48 using std::vector;
49
50
51 MathData::MathData(const_iterator from, const_iterator to)
52         : base_type(from, to)
53 {}
54
55
56 MathAtom & MathData::operator[](pos_type pos)
57 {
58         BOOST_ASSERT(pos < size());
59         return base_type::operator[](pos);
60 }
61
62
63 MathAtom const & MathData::operator[](pos_type pos) const
64 {
65         BOOST_ASSERT(pos < size());
66         return base_type::operator[](pos);
67 }
68
69
70 void MathData::insert(size_type pos, MathAtom const & t)
71 {
72         base_type::insert(begin() + pos, t);
73 }
74
75
76 void MathData::insert(size_type pos, MathData const & ar)
77 {
78         BOOST_ASSERT(pos <= size());
79         base_type::insert(begin() + pos, ar.begin(), ar.end());
80 }
81
82
83 void MathData::append(MathData const & ar)
84 {
85         insert(size(), ar);
86 }
87
88
89 void MathData::erase(size_type pos)
90 {
91         if (pos < size())
92                 erase(pos, pos + 1);
93 }
94
95
96 void MathData::erase(iterator pos1, iterator pos2)
97 {
98         base_type::erase(pos1, pos2);
99 }
100
101
102 void MathData::erase(iterator pos)
103 {
104         base_type::erase(pos);
105 }
106
107
108 void MathData::erase(size_type pos1, size_type pos2)
109 {
110         base_type::erase(begin() + pos1, begin() + pos2);
111 }
112
113
114 void MathData::dump2() const
115 {
116         odocstringstream os;
117         NormalStream ns(os);
118         for (const_iterator it = begin(); it != end(); ++it)
119                 ns << *it << ' ';
120         lyxerr << to_utf8(os.str());
121 }
122
123
124 void MathData::dump() const
125 {
126         odocstringstream os;
127         NormalStream ns(os);
128         for (const_iterator it = begin(); it != end(); ++it)
129                 ns << '<' << *it << '>';
130         lyxerr << to_utf8(os.str());
131 }
132
133
134 void MathData::validate(LaTeXFeatures & features) const
135 {
136         for (const_iterator it = begin(); it != end(); ++it)
137                 (*it)->validate(features);
138 }
139
140
141 bool MathData::match(MathData const & ar) const
142 {
143         return size() == ar.size() && matchpart(ar, 0);
144 }
145
146
147 bool MathData::matchpart(MathData const & ar, pos_type pos) const
148 {
149         if (size() < ar.size() + pos)
150                 return false;
151         const_iterator it = begin() + pos;
152         for (const_iterator jt = ar.begin(); jt != ar.end(); ++jt, ++it)
153                 if (asString(*it) != asString(*jt))
154                         return false;
155         return true;
156 }
157
158
159 void MathData::replace(ReplaceData & rep)
160 {
161         for (size_type i = 0; i < size(); ++i) {
162                 if (find1(rep.from, i)) {
163                         // match found
164                         lyxerr << "match found!" << endl;
165                         erase(i, i + rep.from.size());
166                         insert(i, rep.to);
167                 }
168         }
169
170         // FIXME: temporarily disabled
171         // for (const_iterator it = begin(); it != end(); ++it)
172         //      it->nucleus()->replace(rep);
173 }
174
175
176 bool MathData::find1(MathData const & ar, size_type pos) const
177 {
178         lyxerr << "finding '" << ar << "' in '" << *this << "'" << endl;
179         for (size_type i = 0, n = ar.size(); i < n; ++i)
180                 if (asString(operator[](pos + i)) != asString(ar[i]))
181                         return false;
182         return true;
183 }
184
185
186 MathData::size_type MathData::find(MathData const & ar) const
187 {
188         for (int i = 0, last = size() - ar.size(); i < last; ++i)
189                 if (find1(ar, i))
190                         return i;
191         return size();
192 }
193
194
195 MathData::size_type MathData::find_last(MathData const & ar) const
196 {
197         for (int i = size() - ar.size(); i >= 0; --i)
198                 if (find1(ar, i))
199                         return i;
200         return size();
201 }
202
203
204 bool MathData::contains(MathData const & ar) const
205 {
206         if (find(ar) != size())
207                 return true;
208         for (const_iterator it = begin(); it != end(); ++it)
209                 if ((*it)->contains(ar))
210                         return true;
211         return false;
212 }
213
214
215 void MathData::touch() const
216 {
217 }
218
219
220 namespace {
221
222 bool isInside(DocIterator const & it, MathData const & ar,
223         pos_type p1, pos_type p2)
224 {
225         for (size_t i = 0; i != it.depth(); ++i) {
226                 CursorSlice const & sl = it[i];
227                 if (sl.inset().inMathed() && &sl.cell() == &ar)
228                         return p1 <= sl.pos() && sl.pos() < p2;
229         }
230         return false;
231 }
232
233 }
234
235
236
237 void MathData::metrics(MetricsInfo & mi, Dimension & dim) const
238 {
239         frontend::FontMetrics const & fm = theFontMetrics(mi.base.font);
240         dim = fm.dimension('I');
241         int xascent = fm.dimension('x').ascent();
242         if (xascent >= dim.asc)
243                 xascent = (2 * dim.asc) / 3;
244         minasc_ = xascent;
245         mindes_ = (3 * xascent) / 4;
246         slevel_ = (4 * xascent) / 5;
247         sshift_ = xascent / 4;
248         kerning_ = 0;
249
250         if (empty()) {
251                 // Cache the dimension.
252                 mi.base.bv->coordCache().arrays().add(this, dim);
253                 return;
254         }
255
256         const_cast<MathData*>(this)->updateMacros(mi);
257
258         dim.asc = 0;
259         dim.wid = 0;
260         Dimension d;
261         atom_dims_.clear();
262         for (size_t i = 0, n = size(); i != n; ++i) {
263                 MathAtom const & at = operator[](i);
264                 at->metrics(mi, d);
265                 atom_dims_.push_back(d);
266                 dim += d;
267                 if (i == n - 1)
268                         kerning_ = at->kerning();
269         }
270         // Cache the dimension.
271         mi.base.bv->coordCache().arrays().add(this, dim);
272 }
273
274
275 void MathData::draw(PainterInfo & pi, int x, int y) const
276 {
277         //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
278         BufferView & bv  = *pi.base.bv;
279         setXY(bv, x, y);
280
281         Dimension const & dim = bv.coordCache().getArrays().dim(this);
282
283         if (empty()) {
284                 pi.pain.rectangle(x, y - dim.ascent(), dim.width(), dim.height(), Color_mathline);
285                 return;
286         }
287
288         // don't draw outside the workarea
289         if (y + dim.descent() <= 0
290                 || y - dim.ascent() >= bv.workHeight()
291                 || x + dim.width() <= 0
292                 || x >= bv. workWidth())
293                 return;
294
295         for (size_t i = 0, n = size(); i != n; ++i) {
296                 MathAtom const & at = operator[](i);
297                 bv.coordCache().insets().add(at.nucleus(), x, y);
298                 at->drawSelection(pi, x, y);
299                 at->draw(pi, x, y);
300                 x += atom_dims_[i].wid;
301         }
302 }
303
304
305 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
306 {
307         dim.clear();
308         Dimension d;
309         for (const_iterator it = begin(); it != end(); ++it) {
310                 (*it)->metricsT(mi, d);
311                 dim += d;
312         }
313 }
314
315
316 void MathData::drawT(TextPainter & pain, int x, int y) const
317 {
318         //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
319
320         // FIXME: Abdel 16/10/2006
321         // This drawT() method is never used, this is dead code.
322
323         for (const_iterator it = begin(), et = end(); it != et; ++it) {
324                 (*it)->drawT(pain, x, y);
325                 //x += (*it)->width_;
326                 x += 2;
327         }
328 }
329
330
331 void MathData::updateMacros(MetricsInfo & mi) 
332 {
333         Cursor & cur = mi.base.bv->cursor();
334
335         // go over the array and look for macros
336         for (size_t i = 0; i < size(); ++i) {
337                 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
338                 if (!macroInset)
339                         continue;
340                 
341                 // get macro
342                 macroInset->updateMacro(mi);
343                 size_t macroNumArgs = 0;
344                 size_t macroOptionals = 0;
345                 MacroData const * macro = macroInset->macro();
346                 if (macro) {
347                         macroNumArgs = macro->numargs();
348                         macroOptionals = macro->optionals();
349                 }
350
351                 // store old and compute new display mode
352                 MathMacro::DisplayMode newDisplayMode;
353                 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
354                 newDisplayMode = macroInset->computeDisplayMode(mi);
355
356                 // arity changed or other reason to detach?
357                 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
358                                 && (macroInset->arity() != macroNumArgs
359                                                 || macroInset->optionals() != macroOptionals
360                                                 || newDisplayMode == MathMacro::DISPLAY_UNFOLDED)) {
361                         detachMacroParameters(cur, i);
362                 }
363
364                 // the macro could have been copied while resizing this
365                 macroInset = operator[](i).nucleus()->asMacro();
366
367                 // Cursor in \label?
368                 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED 
369                                 && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
370                         // put cursor in front of macro
371                         int macroSlice = cur.find(macroInset);
372                         if (macroSlice != -1)
373                                 cur.cutOff(macroSlice - 1);
374                 }
375
376                 // update the display mode
377                 macroInset->setDisplayMode(newDisplayMode);
378
379                 // arity changed?
380                 if (newDisplayMode == MathMacro::DISPLAY_NORMAL 
381                                 && (macroInset->arity() != macroNumArgs
382                                                 || macroInset->optionals() != macroOptionals)) {
383                         // is it a virgin macro which was never attached to parameters?
384                         bool fromInitToNormalMode
385                         = (oldDisplayMode == MathMacro::DISPLAY_INIT 
386                                  || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
387                                 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
388                         
389                         // if the macro was entered interactively (i.e. not by paste or during
390                         // loading), it should not be greedy, but the cursor should
391                         // automatically jump into the macro when behind
392                         bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
393                         
394                         // attach parameters
395                         attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
396                                 fromInitToNormalMode, interactive);
397                         
398                         // FIXME: proper anchor handling, this removes the selection
399                         cur.updateInsets(&cur.bottom().inset());
400                         cur.clearSelection();   
401                 }
402
403                 // Give macro the chance to adapt to new situation.
404                 // The macroInset could be invalid now because it was put into a script 
405                 // inset and therefore "deep" copied. So get it again from the MathData.
406                 InsetMath * inset = operator[](i).nucleus();
407                 if (inset->asScriptInset())
408                         inset = inset->asScriptInset()->nuc()[0].nucleus();
409                 BOOST_ASSERT(inset->asMacro());
410                 inset->asMacro()->updateRepresentation(mi);
411         }
412 }
413
414
415 void MathData::detachMacroParameters(Cursor & cur, const size_type macroPos)
416 {
417         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
418         
419         // detach all arguments
420         std::vector<MathData> detachedArgs;
421         if (macroPos + 1 == size())
422                                 // strip arguments if we are at the MathData end
423                                 macroInset->detachArguments(detachedArgs, true);
424         else
425                                 macroInset->detachArguments(detachedArgs, false);
426         
427         // find cursor slice
428         int curMacroSlice = cur.find(macroInset);
429         idx_type curMacroIdx = -1;
430         pos_type curMacroPos = -1;
431         std::vector<CursorSlice> argSlices;
432         if (curMacroSlice != -1) {
433                                 curMacroPos = cur[curMacroSlice].pos();
434                                 curMacroIdx = cur[curMacroSlice].idx();
435                                 cur.cutOff(curMacroSlice, argSlices);
436                                 cur.pop_back();
437         }
438         
439         // only [] after the last non-empty argument can be dropped later 
440         size_t lastNonEmptyOptional = 0;
441         for (size_t l = 0; l < detachedArgs.size() && l < macroInset->optionals(); ++l) {
442                                 if (!detachedArgs[l].empty())
443                                         lastNonEmptyOptional = l;
444         }
445         
446         // optional arguments to be put back?
447         pos_type p = macroPos + 1;
448         size_t j = 0;
449         for (; j < detachedArgs.size() && j < macroInset->optionals(); ++j) {
450                 // another non-empty parameter follows?
451                 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
452                 
453                 // then we can drop empty optional parameters
454                 if (detachedArgs[j].empty() && canDropEmptyOptional) {
455                         if (curMacroIdx == j)
456                                 cur[curMacroSlice - 1].pos() = macroPos + 1;
457                         continue;
458                 }
459                 
460                 // Otherwise we don't drop an empty optional, put it back normally
461                 MathData optarg;
462                 asArray(from_ascii("[]"), optarg);
463                 MathData & arg = detachedArgs[j];
464                 
465                 // look for "]", i.e. put a brace around?
466                 InsetMathBrace * brace = 0;
467                 for (size_t q = 0; q < arg.size(); ++q) {
468                         if (arg[q]->getChar() == ']') {
469                                 // put brace
470                                 brace = new InsetMathBrace();
471                                 break;
472                         }
473                 }
474                 
475                 // put arg between []
476                 if (brace) {
477                         brace->cell(0) = arg;
478                         optarg.insert(1, MathAtom(brace));
479                 } else
480                         optarg.insert(1, arg);
481                 
482                 // insert it into the array
483                 insert(p, optarg);
484                 p += optarg.size();
485                 
486                 // cursor in macro?
487                 if (curMacroSlice == -1)
488                         continue;
489                 
490                 // cursor in optional argument of macro?
491                 if (curMacroIdx == j) {
492                         if (brace) {
493                                 cur.append(0, curMacroPos);
494                                 cur[curMacroSlice - 1].pos() = macroPos + 2;
495                         } else
496                                 cur[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
497                         cur.append(argSlices);
498                 } else if (cur[curMacroSlice - 1].pos() >= int(p))
499                         // cursor right of macro
500                         cur[curMacroSlice - 1].pos() += optarg.size();
501         }
502         
503         // put them back into the MathData
504         for (; j < detachedArgs.size(); ++j, ++p) {
505                 MathData const & arg = detachedArgs[j];
506                 if (arg.size() == 1 && !arg[0]->asScriptInset()) // && arg[0]->asCharInset())
507                         insert(p, arg[0]);
508                 else
509                         insert(p, MathAtom(new InsetMathBrace(arg)));
510
511                 // cursor in macro?
512                 if (curMacroSlice == -1)
513                         continue;
514                 
515                 // cursor in j-th argument of macro?
516                 if (curMacroIdx == j) {
517                         if (operator[](p).nucleus()->asBraceInset()) {
518                                 cur[curMacroSlice - 1].pos() = p;
519                                 cur.append(0, curMacroPos);
520                                 cur.append(argSlices);
521                         } else {
522                                 cur[curMacroSlice - 1].pos() = p; // + macroPos;
523                                 cur.append(argSlices);
524                         }
525                 } else if (cur[curMacroSlice - 1].pos() >= int(p))
526                         ++cur[curMacroSlice - 1].pos();
527         }
528         
529         // FIXME: proper anchor handling, this removes the selection
530         cur.clearSelection();
531         cur.updateInsets(&cur.bottom().inset());
532 }
533
534
535 void MathData::attachMacroParameters(Cursor & cur, 
536         const size_type macroPos, const size_type macroNumArgs,
537         const int macroOptionals, const bool fromInitToNormalMode,
538         const bool interactiveInit)
539 {
540         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
541
542         // start at atom behind the macro again, maybe with some new arguments 
543         // from the detach phase above, to add them back into the macro inset
544         size_t p = macroPos + 1;
545         std::vector<MathData> detachedArgs;
546         MathAtom scriptToPutAround;
547         
548         // find cursor slice again of this MathData
549         int thisSlice = cur.find(*this);
550         int thisPos = -1;
551         if (thisSlice != -1)
552                 thisPos = cur[thisSlice].pos();
553         
554         // find arguments behind the macro
555         if (!interactiveInit) {
556                 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
557                         macroPos, thisPos, thisSlice);
558                 collectParameters(cur, macroNumArgs, detachedArgs, p,
559                         scriptToPutAround, macroPos, thisPos, thisSlice);
560         }
561                 
562         // attach arguments back to macro inset
563         macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
564         
565         // found tail script? E.g. \foo{a}b^x
566         if (scriptToPutAround.nucleus()) {
567                 // put macro into a script inset
568                 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0] 
569                 = operator[](macroPos);
570                 operator[](macroPos) = scriptToPutAround;
571
572                 // go into the script inset nucleus
573                 if (thisPos == int(macroPos))
574                         cur.append(0, 0);
575                 
576                 // get pointer to "deep" copied macro inset
577                 InsetMathScript * scriptInset 
578                 = operator[](macroPos).nucleus()->asScriptInset();
579                 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();        
580         }
581         
582         // remove them from the MathData
583         erase(begin() + macroPos + 1, begin() + p);
584
585         // cursor outside this MathData?
586         if (thisSlice == -1)
587                 return;
588
589         // fix cursor if right of p
590         if (thisPos >= int(p))
591                 cur[thisSlice].pos() -= p - (macroPos + 1);
592         
593         // was the macro inset just inserted interactively and was now folded
594         // and the cursor is just behind?
595         if (cur[thisSlice].pos() == int(macroPos + 1)
596                         && interactiveInit
597                         && fromInitToNormalMode
598                         && macroInset->arity() > 0
599                         && thisSlice + 1 == int(cur.depth())) {
600                 // then enter it if the cursor was just behind
601                 cur[thisSlice].pos() = macroPos;
602                 cur.push_back(CursorSlice(*macroInset));
603                 macroInset->idxFirst(cur);
604         }
605 }
606
607
608 void MathData::collectOptionalParameters(Cursor & cur, 
609         const size_type numOptionalParams, std::vector<MathData> & params, 
610         size_t & pos, const pos_type macroPos, const int thisPos, const int thisSlice)
611 {
612         // insert optional arguments?
613         while (params.size() < numOptionalParams && pos < size()) {
614                 // is a [] block following which could be an optional parameter?
615                 if (operator[](pos)->getChar() != '[')
616                         break;
617                                 
618                 // found possible optional argument, look for "]"
619                 size_t right = pos + 1;
620                 for (; right < size(); ++right) {
621                         if (operator[](right)->getChar() == ']')
622                                 // found right end
623                                 break;
624                 }
625                 
626                 // found?
627                 if (right >= size()) {
628                         // no ] found, so it's not an optional argument
629                         break;
630                 }
631                 
632                 // add everything between [ and ] as optional argument
633                 MathData optarg(begin() + pos + 1, begin() + right);
634                 
635                 // a brace?
636                 bool brace = false;
637                 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
638                         brace = true;
639                         params.push_back(optarg[0]->asBraceInset()->cell(0));
640                 } else
641                         params.push_back(optarg);
642                 
643                 // place cursor in optional argument of macro
644                 if (thisSlice != -1
645                                 && thisPos >= int(pos) && thisPos <= int(right)) {
646                         int paramPos = std::max(0, thisPos - int(pos) - 1);
647                         std::vector<CursorSlice> x;
648                         cur.cutOff(thisSlice, x);
649                         cur[thisSlice].pos() = macroPos;
650                         if (brace) {
651                                 paramPos = x[0].pos();
652                                 x.erase(x.begin());
653                         }
654                         cur.append(0, paramPos);
655                         cur.append(x);
656                 }
657                 pos = right + 1;
658         }
659
660         // fill up empty optional parameters
661         while (params.size() < numOptionalParams) {
662                 params.push_back(MathData());
663         }
664 }
665
666
667 void MathData::collectParameters(Cursor & cur, 
668         const size_type numParams, std::vector<MathData> & params, 
669         size_t & pos, MathAtom & scriptToPutAround,
670         const pos_type macroPos, const int thisPos, const int thisSlice) 
671 {
672         // insert normal arguments
673         for (; params.size() < numParams && pos < size();) {
674                 MathAtom & cell = operator[](pos);
675                 
676                 // fix cursor
677                 std::vector<CursorSlice> argSlices;
678                 int argPos = 0;
679                 if (thisSlice != -1 && thisPos == int(pos)) {
680                         cur.cutOff(thisSlice, argSlices);
681                 }
682                 
683                 // which kind of parameter is it? In {}? With index x^n?
684                 InsetMathBrace const * brace = cell->asBraceInset();
685                 if (brace) {
686                         // found brace, convert into argument
687                         params.push_back(brace->cell(0));
688                         
689                         // cursor inside of the brace or just in front of?
690                         if (thisPos == int(pos) && !argSlices.empty()) {
691                                 argPos = argSlices[0].pos();
692                                 argSlices.erase(argSlices.begin());
693                         }
694                 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
695                         // last inset with scripts without braces
696                         // -> they belong to the macro, not the argument
697                         InsetMathScript * script = cell.nucleus()->asScriptInset();
698                         if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
699                                 // nucleus in brace? Unpack!
700                                 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
701                         else
702                                 params.push_back(script->nuc());
703                         
704                         // script will be put around below
705                         scriptToPutAround = cell;
706                         
707                         // this should only happen after loading, so make cursor handling simple
708                         if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
709                                 argSlices.clear();
710                                 cur.append(0, 0);
711                         }
712                 } else {
713                         // the simplest case: plain inset
714                         MathData array;
715                         array.insert(0, cell);
716                         params.push_back(array);
717                 }
718                 
719                 // put cursor in argument again
720                 if (thisSlice != - 1 && thisPos == int(pos)) {
721                         cur.append(params.size() - 1, argPos);
722                         cur.append(argSlices);
723                         cur[thisSlice].pos() = macroPos;
724                 }
725                 
726                 ++pos;
727         }       
728 }
729
730
731 int MathData::pos2x(size_type pos) const
732 {
733         return pos2x(pos, 0);
734 }
735
736
737 int MathData::pos2x(size_type pos, int glue) const
738 {
739         int x = 0;
740         size_type target = min(pos, size());
741         for (size_type i = 0; i < target; ++i) {
742                 const_iterator it = begin() + i;
743                 if ((*it)->getChar() == ' ')
744                         x += glue;
745                 //lyxerr << "char: " << (*it)->getChar()
746                 //      << "width: " << (*it)->width() << std::endl;
747                 x += atom_dims_[i].wid;
748         }
749         return x;
750 }
751
752
753 MathData::size_type MathData::x2pos(int targetx) const
754 {
755         return x2pos(targetx, 0);
756 }
757
758
759 MathData::size_type MathData::x2pos(int targetx, int glue) const
760 {
761         const_iterator it = begin();
762         int lastx = 0;
763         int currx = 0;
764         // find first position after targetx
765         for (; currx < targetx && it < end(); ++it) {
766                 lastx = currx;
767                 if ((*it)->getChar() == ' ')
768                         currx += glue;
769                 currx += atom_dims_[it - begin()].wid;
770         }
771
772         /**
773          * If we are not at the beginning of the array, go to the left
774          * of the inset if one of the following two condition holds:
775          * - the current inset is editable (so that the cursor tip is
776          *   deeper than us): in this case, we want all intermediate
777          *   cursor slices to be before insets;
778          * - the mouse is closer to the left side of the inset than to
779          *   the right one.
780          * See bug 1918 for details.
781          **/
782         if (it != begin() && currx >= targetx
783             && ((*boost::prior(it))->asNestInset()
784                 || abs(lastx - targetx) < abs(currx - targetx))) {
785                 --it;
786         }
787
788         return it - begin();
789 }
790
791
792 int MathData::dist(BufferView const & bv, int x, int y) const
793 {
794         return bv.coordCache().getArrays().squareDistance(this, x, y);
795 }
796
797
798 void MathData::setXY(BufferView & bv, int x, int y) const
799 {
800         //lyxerr << "setting position cache for MathData " << this << std::endl;
801         bv.coordCache().arrays().add(this, x, y);
802 }
803
804
805 Dimension const & MathData::dimension(BufferView const & bv) const
806 {
807         return bv.coordCache().getArrays().dim(this);
808 }
809
810
811 int MathData::xm(BufferView const & bv) const
812 {
813         Geometry const & g = bv.coordCache().getArrays().geometry(this);
814
815         return g.pos.x_ + g.dim.wid / 2;
816 }
817
818
819 int MathData::ym(BufferView const & bv) const
820 {
821         Geometry const & g = bv.coordCache().getArrays().geometry(this);
822
823         return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
824 }
825
826
827 int MathData::xo(BufferView const & bv) const
828 {
829         return bv.coordCache().getArrays().x(this);
830 }
831
832
833 int MathData::yo(BufferView const & bv) const
834 {
835         return bv.coordCache().getArrays().y(this);
836 }
837
838
839 std::ostream & operator<<(std::ostream & os, MathData const & ar)
840 {
841         odocstringstream oss;
842         NormalStream ns(oss);
843         ns << ar;
844         return os << to_utf8(oss.str());
845 }
846
847
848 odocstream & operator<<(odocstream & os, MathData const & ar)
849 {
850         NormalStream ns(os);
851         ns << ar;
852         return os;
853 }
854
855
856 } // namespace lyx