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