]> git.lyx.org Git - lyx.git/blob - src/mathed/MathData.cpp
33446a4aa3f86ae576c92d0bf1c95af3852ce791
[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         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         CoordCacheBase<Inset> & coords = mi.base.bv->coordCache().insets();
257         for (size_t i = 0, n = size(); i != n; ++i) {
258                 MathAtom const & at = operator[](i);
259                 at->metrics(mi, d);
260                 coords.add(at.nucleus(), d);
261                 dim += d;
262                 if (i == n - 1)
263                         kerning_ = at->kerning(mi.base.bv);
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         CoordCacheBase<Inset> & coords = pi.base.bv->coordCache().insets();
291         for (size_t i = 0, n = size(); i != n; ++i) {
292                 MathAtom const & at = operator[](i);
293                 coords.add(at.nucleus(), x, y);
294                 at->drawSelection(pi, x, y);
295                 at->draw(pi, x, y);
296                 x += coords.dim(at.nucleus()).wid;
297         }
298 }
299
300
301 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
302 {
303         dim.clear();
304         Dimension d;
305         for (const_iterator it = begin(); it != end(); ++it) {
306                 (*it)->metricsT(mi, d);
307                 dim += d;
308         }
309 }
310
311
312 void MathData::drawT(TextPainter & pain, int x, int y) const
313 {
314         //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
315
316         // FIXME: Abdel 16/10/2006
317         // This drawT() method is never used, this is dead code.
318
319         for (const_iterator it = begin(), et = end(); it != et; ++it) {
320                 (*it)->drawT(pain, x, y);
321                 //x += (*it)->width_;
322                 x += 2;
323         }
324 }
325
326
327 void MathData::updateMacros(Cursor * cur, MacroContext const & mc)
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(mc);
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();
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
356                         detachMacroParameters(cur, i);
357                 }
358
359                 // the macro could have been copied while resizing this
360                 macroInset = operator[](i).nucleus()->asMacro();
361
362                 // Cursor in \label?
363                 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED 
364                                 && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
365                         // put cursor in front of macro
366                         if (cur) {
367                                 int macroSlice = cur->find(macroInset);
368                                 if (macroSlice != -1)
369                                         cur->cutOff(macroSlice - 1);
370                         }
371                 }
372
373                 // update the display mode
374                 macroInset->setDisplayMode(newDisplayMode);
375
376                 // arity changed?
377                 if (newDisplayMode == MathMacro::DISPLAY_NORMAL 
378                                 && (macroInset->arity() != macroNumArgs
379                                                 || macroInset->optionals() != macroOptionals)) {
380                         // is it a virgin macro which was never attached to parameters?
381                         bool fromInitToNormalMode
382                         = (oldDisplayMode == MathMacro::DISPLAY_INIT 
383                                  || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
384                                 && newDisplayMode == MathMacro::DISPLAY_NORMAL;
385                         
386                         // if the macro was entered interactively (i.e. not by paste or during
387                         // loading), it should not be greedy, but the cursor should
388                         // automatically jump into the macro when behind
389                         bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
390                         
391                         // attach parameters
392                         attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
393                                 fromInitToNormalMode, interactive);
394                         
395                         if (cur) {
396                                 // FIXME: proper anchor handling, this removes the selection
397                                 cur->updateInsets(&cur->bottom().inset());
398                                 cur->clearSelection();  
399                         }
400                 }
401
402                 // Give macro the chance to adapt to new situation.
403                 // The macroInset could be invalid now because it was put into a script 
404                 // inset and therefore "deep" copied. So get it again from the MathData.
405                 InsetMath * inset = operator[](i).nucleus();
406                 if (inset->asScriptInset())
407                         inset = inset->asScriptInset()->nuc()[0].nucleus();
408                 BOOST_ASSERT(inset->asMacro());
409                 inset->asMacro()->updateRepresentation(cur);
410         }
411 }
412
413
414 void MathData::detachMacroParameters(Cursor * cur, const size_type macroPos)
415 {
416         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
417         
418         // detach all arguments
419         vector<MathData> detachedArgs;
420         if (macroPos + 1 == size())
421                 // strip arguments if we are at the MathData end
422                 macroInset->detachArguments(detachedArgs, true);
423         else
424                 macroInset->detachArguments(detachedArgs, false);
425         
426         // find cursor slice
427         int curMacroSlice = -1;
428         if (cur)
429                 curMacroSlice = cur->find(macroInset);
430         idx_type curMacroIdx = -1;
431         pos_type curMacroPos = -1;
432         vector<CursorSlice> argSlices;
433         if (curMacroSlice != -1) {
434                 curMacroPos = (*cur)[curMacroSlice].pos();
435                 curMacroIdx = (*cur)[curMacroSlice].idx();
436                 cur->cutOff(curMacroSlice, argSlices);
437                 cur->pop_back();
438         }
439         
440         // only [] after the last non-empty argument can be dropped later 
441         size_t lastNonEmptyOptional = 0;
442         for (size_t l = 0; l < detachedArgs.size() && l < macroInset->optionals(); ++l) {
443                 if (!detachedArgs[l].empty())
444                         lastNonEmptyOptional = l;
445         }
446         
447         // optional arguments to be put back?
448         pos_type p = macroPos + 1;
449         size_t j = 0;
450         for (; j < detachedArgs.size() && j < macroInset->optionals(); ++j) {
451                 // another non-empty parameter follows?
452                 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
453                 
454                 // then we can drop empty optional parameters
455                 if (detachedArgs[j].empty() && canDropEmptyOptional) {
456                         if (curMacroIdx == j)
457                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 1;
458                         continue;
459                 }
460                 
461                 // Otherwise we don't drop an empty optional, put it back normally
462                 MathData optarg;
463                 asArray(from_ascii("[]"), optarg);
464                 MathData & arg = detachedArgs[j];
465                 
466                 // look for "]", i.e. put a brace around?
467                 InsetMathBrace * brace = 0;
468                 for (size_t q = 0; q < arg.size(); ++q) {
469                         if (arg[q]->getChar() == ']') {
470                                 // put brace
471                                 brace = new InsetMathBrace();
472                                 break;
473                         }
474                 }
475                 
476                 // put arg between []
477                 if (brace) {
478                         brace->cell(0) = arg;
479                         optarg.insert(1, MathAtom(brace));
480                 } else
481                         optarg.insert(1, arg);
482                 
483                 // insert it into the array
484                 insert(p, optarg);
485                 p += optarg.size();
486                 
487                 // cursor in macro?
488                 if (curMacroSlice == -1)
489                         continue;
490                 
491                 // cursor in optional argument of macro?
492                 if (curMacroIdx == j) {
493                         if (brace) {
494                                 cur->append(0, curMacroPos);
495                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 2;
496                         } else
497                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
498                         cur->append(argSlices);
499                 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
500                         // cursor right of macro
501                         (*cur)[curMacroSlice - 1].pos() += optarg.size();
502         }
503         
504         // put them back into the MathData
505         for (; j < detachedArgs.size(); ++j, ++p) {
506                 MathData const & arg = detachedArgs[j];
507                 if (arg.size() == 1 
508                     && !arg[0]->asScriptInset()
509                     && !(arg[0]->asMacro() && arg[0]->asMacro()->arity() > 0))
510                         insert(p, arg[0]);
511                 else
512                         insert(p, MathAtom(new InsetMathBrace(arg)));
513                 
514                 // cursor in macro?
515                 if (curMacroSlice == -1)
516                         continue;
517                 
518                 // cursor in j-th argument of macro?
519                 if (curMacroIdx == j) {
520                         if (operator[](p).nucleus()->asBraceInset()) {
521                                 (*cur)[curMacroSlice - 1].pos() = p;
522                                 cur->append(0, curMacroPos);
523                                 cur->append(argSlices);
524                         } else {
525                                 (*cur)[curMacroSlice - 1].pos() = p; // + macroPos;
526                                 cur->append(argSlices);
527                         }
528                 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
529                         ++(*cur)[curMacroSlice - 1].pos();
530         }
531         
532         if (cur) {
533                 // FIXME: proper anchor handling, this removes the selection
534                 cur->clearSelection();
535                 cur->updateInsets(&cur->bottom().inset());
536         }
537 }
538
539
540 void MathData::attachMacroParameters(Cursor * cur, 
541         const size_type macroPos, const size_type macroNumArgs,
542         const int macroOptionals, const bool fromInitToNormalMode,
543         const bool interactiveInit)
544 {
545         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
546
547         // start at atom behind the macro again, maybe with some new arguments 
548         // from the detach phase above, to add them back into the macro inset
549         size_t p = macroPos + 1;
550         vector<MathData> detachedArgs;
551         MathAtom scriptToPutAround;
552         
553         // find cursor slice again of this MathData
554         int thisSlice = -1;
555         if (cur)
556                 thisSlice = cur->find(*this);
557         int thisPos = -1;
558         if (thisSlice != -1)
559                 thisPos = (*cur)[thisSlice].pos();
560         
561         // find arguments behind the macro
562         if (!interactiveInit) {
563                 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
564                         scriptToPutAround, macroPos, thisPos, thisSlice);
565                 collectParameters(cur, macroNumArgs, detachedArgs, p,
566                         scriptToPutAround, macroPos, thisPos, thisSlice);
567         }
568                 
569         // attach arguments back to macro inset
570         macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
571         
572         // found tail script? E.g. \foo{a}b^x
573         if (scriptToPutAround.nucleus()) {
574                 // put macro into a script inset
575                 scriptToPutAround.nucleus()->asScriptInset()->nuc()[0] 
576                 = operator[](macroPos);
577                 operator[](macroPos) = scriptToPutAround;
578
579                 // go into the script inset nucleus
580                 if (cur && thisPos == int(macroPos))
581                         cur->append(0, 0);
582                 
583                 // get pointer to "deep" copied macro inset
584                 InsetMathScript * scriptInset 
585                 = operator[](macroPos).nucleus()->asScriptInset();
586                 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();        
587         }
588         
589         // remove them from the MathData
590         erase(begin() + macroPos + 1, begin() + p);
591
592         // cursor outside this MathData?
593         if (thisSlice == -1)
594                 return;
595
596         // fix cursor if right of p
597         if (thisPos >= int(p))
598                 (*cur)[thisSlice].pos() -= p - (macroPos + 1);
599         
600         // was the macro inset just inserted interactively and was now folded
601         // and the cursor is just behind?
602         if ((*cur)[thisSlice].pos() == int(macroPos + 1)
603             && interactiveInit
604             && fromInitToNormalMode
605             && macroInset->arity() > 0
606             && thisSlice + 1 == int(cur->depth())) {
607                 // then enter it if the cursor was just behind
608                 (*cur)[thisSlice].pos() = macroPos;
609                 cur->push_back(CursorSlice(*macroInset));
610                 macroInset->idxFirst(*cur);
611         }
612 }
613
614
615 void MathData::collectOptionalParameters(Cursor * cur, 
616         const size_type numOptionalParams, vector<MathData> & params, 
617         size_t & pos, MathAtom & scriptToPutAround,
618         const pos_type macroPos, const int thisPos, const int thisSlice)
619 {
620         // insert optional arguments?
621         while (params.size() < numOptionalParams 
622                && pos < size()
623                && !scriptToPutAround.nucleus()) {
624                 // is a [] block following which could be an optional parameter?
625                 if (operator[](pos)->getChar() != '[')
626                         break;
627                 
628                 // found possible optional argument, look for "]"
629                 size_t right = pos + 1;
630                 for (; right < size(); ++right) {
631                         MathAtom & cell = operator[](right);
632
633                         if (cell->getChar() == ']')
634                                 // found right end
635                                 break;
636                         
637                         // maybe "]" with a script around?
638                         InsetMathScript * script = cell.nucleus()->asScriptInset();
639                         if (!script)
640                                 continue;
641                         if (script->nuc().size() != 1)
642                                 continue;
643                         if (script->nuc()[0]->getChar() == ']') {
644                                 // script will be put around the macro later
645                                 scriptToPutAround = cell;
646                                 break;
647                         }
648                 }
649                 
650                 // found?
651                 if (right >= size()) {
652                         // no ] found, so it's not an optional argument
653                         break;
654                 }
655                 
656                 // add everything between [ and ] as optional argument
657                 MathData optarg(begin() + pos + 1, begin() + right);
658                 
659                 // a brace?
660                 bool brace = false;
661                 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
662                         brace = true;
663                         params.push_back(optarg[0]->asBraceInset()->cell(0));
664                 } else
665                         params.push_back(optarg);
666                 
667                 // place cursor in optional argument of macro
668                 if (thisSlice != -1
669                     && thisPos >= int(pos) && thisPos <= int(right)) {
670                         int paramPos = max(0, thisPos - int(pos) - 1);
671                         vector<CursorSlice> x;
672                         cur->cutOff(thisSlice, x);
673                         (*cur)[thisSlice].pos() = macroPos;
674                         if (brace) {
675                                 paramPos = x[0].pos();
676                                 x.erase(x.begin());
677                         }
678                         cur->append(0, paramPos);
679                         cur->append(x);
680                 }
681                 pos = right + 1;
682         }
683
684         // fill up empty optional parameters
685         while (params.size() < numOptionalParams)
686                 params.push_back(MathData());   
687 }
688
689
690 void MathData::collectParameters(Cursor * cur, 
691         const size_type numParams, vector<MathData> & params, 
692         size_t & pos, MathAtom & scriptToPutAround,
693         const pos_type macroPos, const int thisPos, const int thisSlice) 
694 {
695         // insert normal arguments
696         while (params.size() < numParams
697                && pos < size()
698                && !scriptToPutAround.nucleus()) {
699                 MathAtom & cell = operator[](pos);
700                 
701                 // fix cursor
702                 vector<CursorSlice> argSlices;
703                 int argPos = 0;
704                 if (thisSlice != -1 && thisPos == int(pos))
705                         cur->cutOff(thisSlice, argSlices);              
706                 
707                 // which kind of parameter is it? In {}? With index x^n?
708                 InsetMathBrace const * brace = cell->asBraceInset();
709                 if (brace) {
710                         // found brace, convert into argument
711                         params.push_back(brace->cell(0));
712                         
713                         // cursor inside of the brace or just in front of?
714                         if (thisPos == int(pos) && !argSlices.empty()) {
715                                 argPos = argSlices[0].pos();
716                                 argSlices.erase(argSlices.begin());
717                         }
718                 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
719                         // last inset with scripts without braces
720                         // -> they belong to the macro, not the argument
721                         InsetMathScript * script = cell.nucleus()->asScriptInset();
722                         if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
723                                 // nucleus in brace? Unpack!
724                                 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
725                         else
726                                 params.push_back(script->nuc());
727                         
728                         // script will be put around below
729                         scriptToPutAround = cell;
730                         
731                         // this should only happen after loading, so make cursor handling simple
732                         if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
733                                 argSlices.clear();
734                                 if (cur)
735                                         cur->append(0, 0);
736                         }
737                 } else {
738                         // the simplest case: plain inset
739                         MathData array;
740                         array.insert(0, cell);
741                         params.push_back(array);
742                 }
743                 
744                 // put cursor in argument again
745                 if (thisSlice != - 1 && thisPos == int(pos)) {
746                         cur->append(params.size() - 1, argPos);
747                         cur->append(argSlices);
748                         (*cur)[thisSlice].pos() = macroPos;
749                 }
750                 
751                 ++pos;
752         }       
753 }
754
755
756 int MathData::pos2x(BufferView const * bv, size_type pos) const
757 {
758         return pos2x(bv, pos, 0);
759 }
760
761
762 int MathData::pos2x(BufferView const * bv, size_type pos, int glue) const
763 {
764         int x = 0;
765         size_type target = min(pos, size());
766         CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
767         for (size_type i = 0; i < target; ++i) {
768                 const_iterator it = begin() + i;
769                 if ((*it)->getChar() == ' ')
770                         x += glue;
771                 //lyxerr << "char: " << (*it)->getChar()
772                 //      << "width: " << (*it)->width() << endl;
773                 x += coords.dim((*it).nucleus()).wid;
774         }
775         return x;
776 }
777
778
779 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx) const
780 {
781         return x2pos(bv, targetx, 0);
782 }
783
784
785 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx, int glue) const
786 {
787         const_iterator it = begin();
788         int lastx = 0;
789         int currx = 0;
790         CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
791         // find first position after targetx
792         for (; currx < targetx && it < end(); ++it) {
793                 lastx = currx;
794                 if ((*it)->getChar() == ' ')
795                         currx += glue;
796                 currx += coords.dim((*it).nucleus()).wid;
797         }
798
799         /**
800          * If we are not at the beginning of the array, go to the left
801          * of the inset if one of the following two condition holds:
802          * - the current inset is editable (so that the cursor tip is
803          *   deeper than us): in this case, we want all intermediate
804          *   cursor slices to be before insets;
805          * - the mouse is closer to the left side of the inset than to
806          *   the right one.
807          * See bug 1918 for details.
808          **/
809         if (it != begin() && currx >= targetx
810             && ((*boost::prior(it))->asNestInset()
811                 || abs(lastx - targetx) < abs(currx - targetx))) {
812                 --it;
813         }
814
815         return it - begin();
816 }
817
818
819 int MathData::dist(BufferView const & bv, int x, int y) const
820 {
821         return bv.coordCache().getArrays().squareDistance(this, x, y);
822 }
823
824
825 void MathData::setXY(BufferView & bv, int x, int y) const
826 {
827         //lyxerr << "setting position cache for MathData " << this << endl;
828         bv.coordCache().arrays().add(this, x, y);
829 }
830
831
832 Dimension const & MathData::dimension(BufferView const & bv) const
833 {
834         return bv.coordCache().getArrays().dim(this);
835 }
836
837
838 int MathData::xm(BufferView const & bv) const
839 {
840         Geometry const & g = bv.coordCache().getArrays().geometry(this);
841
842         return g.pos.x_ + g.dim.wid / 2;
843 }
844
845
846 int MathData::ym(BufferView const & bv) const
847 {
848         Geometry const & g = bv.coordCache().getArrays().geometry(this);
849
850         return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
851 }
852
853
854 int MathData::xo(BufferView const & bv) const
855 {
856         return bv.coordCache().getArrays().x(this);
857 }
858
859
860 int MathData::yo(BufferView const & bv) const
861 {
862         return bv.coordCache().getArrays().y(this);
863 }
864
865
866 ostream & operator<<(ostream & os, MathData const & ar)
867 {
868         odocstringstream oss;
869         NormalStream ns(oss);
870         ns << ar;
871         return os << to_utf8(oss.str());
872 }
873
874
875 odocstream & operator<<(odocstream & os, MathData const & ar)
876 {
877         NormalStream ns(os);
878         ns << ar;
879         return os;
880 }
881
882
883 } // namespace lyx