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