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