]> git.lyx.org Git - features.git/blob - src/mathed/MathData.cpp
* Lazy MathData to avoid unneeded interpretation of macro definitions
[features.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         Cursor & cur = mi.base.bv->cursor();
251         const_cast<MathData*>(this)->updateMacros(&cur, mi.macrocontext);
252
253         dim.asc = 0;
254         dim.wid = 0;
255         Dimension d;
256         atom_dims_.clear();
257         for (size_t i = 0, n = size(); i != n; ++i) {
258                 MathAtom const & at = operator[](i);
259                 at->metrics(mi, d);
260                 atom_dims_.push_back(d);
261                 dim += d;
262                 if (i == n - 1)
263                         kerning_ = at->kerning();
264         }
265         // Cache the dimension.
266         mi.base.bv->coordCache().arrays().add(this, dim);
267 }
268
269
270 void MathData::draw(PainterInfo & pi, int x, int y) const
271 {
272         //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
273         BufferView & bv  = *pi.base.bv;
274         setXY(bv, x, y);
275
276         Dimension const & dim = bv.coordCache().getArrays().dim(this);
277
278         if (empty()) {
279                 pi.pain.rectangle(x, y - dim.ascent(), dim.width(), dim.height(), Color_mathline);
280                 return;
281         }
282
283         // don't draw outside the workarea
284         if (y + dim.descent() <= 0
285                 || y - dim.ascent() >= bv.workHeight()
286                 || x + dim.width() <= 0
287                 || x >= bv. workWidth())
288                 return;
289
290         for (size_t i = 0, n = size(); i != n; ++i) {
291                 MathAtom const & at = operator[](i);
292                 bv.coordCache().insets().add(at.nucleus(), x, y);
293                 at->drawSelection(pi, x, y);
294                 at->draw(pi, x, y);
295                 x += atom_dims_[i].wid;
296         }
297 }
298
299
300 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
301 {
302         dim.clear();
303         Dimension d;
304         for (const_iterator it = begin(); it != end(); ++it) {
305                 (*it)->metricsT(mi, d);
306                 dim += d;
307         }
308 }
309
310
311 void MathData::drawT(TextPainter & pain, int x, int y) const
312 {
313         //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
314
315         // FIXME: Abdel 16/10/2006
316         // This drawT() method is never used, this is dead code.
317
318         for (const_iterator it = begin(), et = end(); it != et; ++it) {
319                 (*it)->drawT(pain, x, y);
320                 //x += (*it)->width_;
321                 x += 2;
322         }
323 }
324
325
326 void MathData::updateMacros(Cursor * cur, MacroContext const & mc)
327 {
328         // go over the array and look for macros
329         for (size_t i = 0; i < size(); ++i) {
330                 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
331                 if (!macroInset)
332                         continue;
333                 
334                 // get macro
335                 macroInset->updateMacro(mc);
336                 size_t macroNumArgs = 0;
337                 size_t macroOptionals = 0;
338                 MacroData const * macro = macroInset->macro();
339                 if (macro) {
340                         macroNumArgs = macro->numargs();
341                         macroOptionals = macro->optionals();
342                 }
343
344                 // store old and compute new display mode
345                 MathMacro::DisplayMode newDisplayMode;
346                 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
347                 newDisplayMode = macroInset->computeDisplayMode();
348
349                 // arity changed or other reason to detach?
350                 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
351                                 && (macroInset->arity() != macroNumArgs
352                                                 || macroInset->optionals() != macroOptionals
353                                                 || newDisplayMode == MathMacro::DISPLAY_UNFOLDED)) {
354
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                         if (cur) {
366                                 int macroSlice = cur->find(macroInset);
367                                 if (macroSlice != -1)
368                                         cur->cutOff(macroSlice - 1);
369                         }
370                 }
371
372                 // update the display mode
373                 macroInset->setDisplayMode(newDisplayMode);
374
375                 // arity changed?
376                 if (newDisplayMode == MathMacro::DISPLAY_NORMAL 
377                                 && (macroInset->arity() != macroNumArgs
378                                                 || macroInset->optionals() != macroOptionals)) {
379                         // is it a virgin macro which was never attached to parameters?
380                         bool fromInitToNormalMode
381                         = (oldDisplayMode == MathMacro::DISPLAY_INIT 
382                                  || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
383                                 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
384                         
385                         // if the macro was entered interactively (i.e. not by paste or during
386                         // loading), it should not be greedy, but the cursor should
387                         // automatically jump into the macro when behind
388                         bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
389                         
390                         // attach parameters
391                         attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
392                                 fromInitToNormalMode, interactive);
393                         
394                         if (cur) {
395                                 // FIXME: proper anchor handling, this removes the selection
396                                 cur->updateInsets(&cur->bottom().inset());
397                                 cur->clearSelection();  
398                         }
399                 }
400
401                 // Give macro the chance to adapt to new situation.
402                 // The macroInset could be invalid now because it was put into a script 
403                 // inset and therefore "deep" copied. So get it again from the MathData.
404                 InsetMath * inset = operator[](i).nucleus();
405                 if (inset->asScriptInset())
406                         inset = inset->asScriptInset()->nuc()[0].nucleus();
407                 BOOST_ASSERT(inset->asMacro());
408                 inset->asMacro()->updateRepresentation(cur);
409         }
410 }
411
412
413 void MathData::detachMacroParameters(Cursor * cur, const size_type macroPos)
414 {
415         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
416         
417         // detach all arguments
418         vector<MathData> detachedArgs;
419         if (macroPos + 1 == size())
420                 // strip arguments if we are at the MathData end
421                 macroInset->detachArguments(detachedArgs, true);
422         else
423                 macroInset->detachArguments(detachedArgs, false);
424         
425         // find cursor slice
426         int curMacroSlice = -1;
427         if (cur)
428                 curMacroSlice = cur->find(macroInset);
429         idx_type curMacroIdx = -1;
430         pos_type curMacroPos = -1;
431         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 
507                     && !arg[0]->asScriptInset()
508                     && !(arg[0]->asMacro() && arg[0]->asMacro()->arity() > 0))
509                         insert(p, arg[0]);
510                 else
511                         insert(p, MathAtom(new InsetMathBrace(arg)));
512                 
513                 // cursor in macro?
514                 if (curMacroSlice == -1)
515                         continue;
516                 
517                 // cursor in j-th argument of macro?
518                 if (curMacroIdx == j) {
519                         if (operator[](p).nucleus()->asBraceInset()) {
520                                 (*cur)[curMacroSlice - 1].pos() = p;
521                                 cur->append(0, curMacroPos);
522                                 cur->append(argSlices);
523                         } else {
524                                 (*cur)[curMacroSlice - 1].pos() = p; // + macroPos;
525                                 cur->append(argSlices);
526                         }
527                 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
528                         ++(*cur)[curMacroSlice - 1].pos();
529         }
530         
531         if (cur) {
532                 // FIXME: proper anchor handling, this removes the selection
533                 cur->clearSelection();
534                 cur->updateInsets(&cur->bottom().inset());
535         }
536 }
537
538
539 void MathData::attachMacroParameters(Cursor * cur, 
540         const size_type macroPos, const size_type macroNumArgs,
541         const int macroOptionals, const bool fromInitToNormalMode,
542         const bool interactiveInit)
543 {
544         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
545
546         // start at atom behind the macro again, maybe with some new arguments 
547         // from the detach phase above, to add them back into the macro inset
548         size_t p = macroPos + 1;
549         vector<MathData> detachedArgs;
550         MathAtom scriptToPutAround;
551         
552         // find cursor slice again of this MathData
553         int thisSlice = -1;
554         if (cur)
555                 thisSlice = cur->find(*this);
556         int thisPos = -1;
557         if (thisSlice != -1)
558                 thisPos = (*cur)[thisSlice].pos();
559         
560         // find arguments behind the macro
561         if (!interactiveInit) {
562                 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
563                         macroPos, thisPos, thisSlice);
564                 collectParameters(cur, macroNumArgs, detachedArgs, p,
565                         scriptToPutAround, macroPos, thisPos, thisSlice);
566         }
567                 
568         // attach arguments back to macro inset
569         macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
570         
571         // found tail script? E.g. \foo{a}b^x
572         if (scriptToPutAround.nucleus()) {
573                 // put macro into a script inset
574                 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0] 
575                 = operator[](macroPos);
576                 operator[](macroPos) = scriptToPutAround;
577
578                 // go into the script inset nucleus
579                 if (cur && thisPos == int(macroPos))
580                         cur->append(0, 0);
581                 
582                 // get pointer to "deep" copied macro inset
583                 InsetMathScript * scriptInset 
584                 = operator[](macroPos).nucleus()->asScriptInset();
585                 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();        
586         }
587         
588         // remove them from the MathData
589         erase(begin() + macroPos + 1, begin() + p);
590
591         // cursor outside this MathData?
592         if (thisSlice == -1)
593                 return;
594
595         // fix cursor if right of p
596         if (thisPos >= int(p))
597                 (*cur)[thisSlice].pos() -= p - (macroPos + 1);
598         
599         // was the macro inset just inserted interactively and was now folded
600         // and the cursor is just behind?
601         if ((*cur)[thisSlice].pos() == int(macroPos + 1)
602             && interactiveInit
603             && fromInitToNormalMode
604             && macroInset->arity() > 0
605             && thisSlice + 1 == int(cur->depth())) {
606                 // then enter it if the cursor was just behind
607                 (*cur)[thisSlice].pos() = macroPos;
608                 cur->push_back(CursorSlice(*macroInset));
609                 macroInset->idxFirst(*cur);
610         }
611 }
612
613
614 void MathData::collectOptionalParameters(Cursor * cur, 
615         const size_type numOptionalParams, vector<MathData> & params, 
616         size_t & pos, const pos_type macroPos, const int thisPos, const int thisSlice)
617 {
618         // insert optional arguments?
619         while (params.size() < numOptionalParams && pos < size()) {
620                 // is a [] block following which could be an optional parameter?
621                 if (operator[](pos)->getChar() != '[')
622                         break;
623                 
624                 // found possible optional argument, look for "]"
625                 size_t right = pos + 1;
626                 for (; right < size(); ++right) {
627                         if (operator[](right)->getChar() == ']')
628                                 // found right end
629                                 break;
630                 }
631                 
632                 // found?
633                 if (right >= size()) {
634                         // no ] found, so it's not an optional argument
635                         break;
636                 }
637                 
638                 // add everything between [ and ] as optional argument
639                 MathData optarg(begin() + pos + 1, begin() + right);
640                 
641                 // a brace?
642                 bool brace = false;
643                 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
644                         brace = true;
645                         params.push_back(optarg[0]->asBraceInset()->cell(0));
646                 } else
647                         params.push_back(optarg);
648                 
649                 // place cursor in optional argument of macro
650                 if (thisSlice != -1
651                     && thisPos >= int(pos) && thisPos <= int(right)) {
652                         int paramPos = max(0, thisPos - int(pos) - 1);
653                         vector<CursorSlice> x;
654                         cur->cutOff(thisSlice, x);
655                         (*cur)[thisSlice].pos() = macroPos;
656                         if (brace) {
657                                 paramPos = x[0].pos();
658                                 x.erase(x.begin());
659                         }
660                         cur->append(0, paramPos);
661                         cur->append(x);
662                 }
663                 pos = right + 1;
664         }
665
666         // fill up empty optional parameters
667         while (params.size() < numOptionalParams)
668                 params.push_back(MathData());   
669 }
670
671
672 void MathData::collectParameters(Cursor * cur, 
673         const size_type numParams, vector<MathData> & params, 
674         size_t & pos, MathAtom & scriptToPutAround,
675         const pos_type macroPos, const int thisPos, const int thisSlice) 
676 {
677         // insert normal arguments
678         for (; params.size() < numParams && pos < size();) {
679                 MathAtom & cell = operator[](pos);
680                 
681                 // fix cursor
682                 vector<CursorSlice> argSlices;
683                 int argPos = 0;
684                 if (thisSlice != -1 && thisPos == int(pos))
685                         cur->cutOff(thisSlice, argSlices);              
686                 
687                 // which kind of parameter is it? In {}? With index x^n?
688                 InsetMathBrace const * brace = cell->asBraceInset();
689                 if (brace) {
690                         // found brace, convert into argument
691                         params.push_back(brace->cell(0));
692                         
693                         // cursor inside of the brace or just in front of?
694                         if (thisPos == int(pos) && !argSlices.empty()) {
695                                 argPos = argSlices[0].pos();
696                                 argSlices.erase(argSlices.begin());
697                         }
698                 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
699                         // last inset with scripts without braces
700                         // -> they belong to the macro, not the argument
701                         InsetMathScript * script = cell.nucleus()->asScriptInset();
702                         if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
703                                 // nucleus in brace? Unpack!
704                                 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
705                         else
706                                 params.push_back(script->nuc());
707                         
708                         // script will be put around below
709                         scriptToPutAround = cell;
710                         
711                         // this should only happen after loading, so make cursor handling simple
712                         if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
713                                 argSlices.clear();
714                                 if (cur)
715                                         cur->append(0, 0);
716                         }
717                 } else {
718                         // the simplest case: plain inset
719                         MathData array;
720                         array.insert(0, cell);
721                         params.push_back(array);
722                 }
723                 
724                 // put cursor in argument again
725                 if (thisSlice != - 1 && thisPos == int(pos)) {
726                         cur->append(params.size() - 1, argPos);
727                         cur->append(argSlices);
728                         (*cur)[thisSlice].pos() = macroPos;
729                 }
730                 
731                 ++pos;
732         }       
733 }
734
735
736 int MathData::pos2x(size_type pos) const
737 {
738         return pos2x(pos, 0);
739 }
740
741
742 int MathData::pos2x(size_type pos, int glue) const
743 {
744         int x = 0;
745         size_type target = min(pos, size());
746         for (size_type i = 0; i < target; ++i) {
747                 const_iterator it = begin() + i;
748                 if ((*it)->getChar() == ' ')
749                         x += glue;
750                 //lyxerr << "char: " << (*it)->getChar()
751                 //      << "width: " << (*it)->width() << endl;
752                 x += atom_dims_[i].wid;
753         }
754         return x;
755 }
756
757
758 MathData::size_type MathData::x2pos(int targetx) const
759 {
760         return x2pos(targetx, 0);
761 }
762
763
764 MathData::size_type MathData::x2pos(int targetx, int glue) const
765 {
766         const_iterator it = begin();
767         int lastx = 0;
768         int currx = 0;
769         // find first position after targetx
770         for (; currx < targetx && it < end(); ++it) {
771                 lastx = currx;
772                 if ((*it)->getChar() == ' ')
773                         currx += glue;
774                 currx += atom_dims_[it - begin()].wid;
775         }
776
777         /**
778          * If we are not at the beginning of the array, go to the left
779          * of the inset if one of the following two condition holds:
780          * - the current inset is editable (so that the cursor tip is
781          *   deeper than us): in this case, we want all intermediate
782          *   cursor slices to be before insets;
783          * - the mouse is closer to the left side of the inset than to
784          *   the right one.
785          * See bug 1918 for details.
786          **/
787         if (it != begin() && currx >= targetx
788             && ((*boost::prior(it))->asNestInset()
789                 || abs(lastx - targetx) < abs(currx - targetx))) {
790                 --it;
791         }
792
793         return it - begin();
794 }
795
796
797 int MathData::dist(BufferView const & bv, int x, int y) const
798 {
799         return bv.coordCache().getArrays().squareDistance(this, x, y);
800 }
801
802
803 void MathData::setXY(BufferView & bv, int x, int y) const
804 {
805         //lyxerr << "setting position cache for MathData " << this << endl;
806         bv.coordCache().arrays().add(this, x, y);
807 }
808
809
810 Dimension const & MathData::dimension(BufferView const & bv) const
811 {
812         return bv.coordCache().getArrays().dim(this);
813 }
814
815
816 int MathData::xm(BufferView const & bv) const
817 {
818         Geometry const & g = bv.coordCache().getArrays().geometry(this);
819
820         return g.pos.x_ + g.dim.wid / 2;
821 }
822
823
824 int MathData::ym(BufferView const & bv) const
825 {
826         Geometry const & g = bv.coordCache().getArrays().geometry(this);
827
828         return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
829 }
830
831
832 int MathData::xo(BufferView const & bv) const
833 {
834         return bv.coordCache().getArrays().x(this);
835 }
836
837
838 int MathData::yo(BufferView const & bv) const
839 {
840         return bv.coordCache().getArrays().y(this);
841 }
842
843
844 ostream & operator<<(ostream & os, MathData const & ar)
845 {
846         odocstringstream oss;
847         NormalStream ns(oss);
848         ns << ar;
849         return os << to_utf8(oss.str());
850 }
851
852
853 odocstream & operator<<(odocstream & os, MathData const & ar)
854 {
855         NormalStream ns(os);
856         ns << ar;
857         return os;
858 }
859
860
861 } // namespace lyx