]> git.lyx.org Git - lyx.git/blob - src/mathed/MathData.cpp
2ad3309af02901985509b91f6ba2f1c86338046a
[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 "support/debug.h"
34 #include "support/docstream.h"
35
36 #include "frontends/FontMetrics.h"
37 #include "frontends/Painter.h"
38
39 #include "support/gettext.h"
40 #include "support/lassert.h"
41 #include <boost/next_prior.hpp>
42
43 #include <cstdlib>
44
45 using namespace std;
46
47 namespace lyx {
48
49
50 MathData::MathData(Buffer * buf, const_iterator from, const_iterator to)
51         : base_type(from, to), buffer_(buf)
52 {}
53
54
55 MathAtom & MathData::operator[](pos_type pos)
56 {
57         LBUFERR(pos < size(), _("Invalid MathData."));
58         return base_type::operator[](pos);
59 }
60
61
62 MathAtom const & MathData::operator[](pos_type pos) const
63 {
64         LBUFERR(pos < size(), _("Invalid MathData."));
65         return base_type::operator[](pos);
66 }
67
68
69 void MathData::insert(size_type pos, MathAtom const & t)
70 {
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(), _("Invalid MathData."));
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 namespace {
220
221 bool isInside(DocIterator const & it, MathData const & ar,
222         pos_type p1, pos_type p2)
223 {
224         for (size_t i = 0; i != it.depth(); ++i) {
225                 CursorSlice const & sl = it[i];
226                 if (sl.inset().inMathed() && &sl.cell() == &ar)
227                         return p1 <= sl.pos() && sl.pos() < p2;
228         }
229         return false;
230 }
231
232 }
233
234
235
236 void MathData::metrics(MetricsInfo & mi, Dimension & dim) const
237 {
238         frontend::FontMetrics const & fm = theFontMetrics(mi.base.font);
239         dim = fm.dimension('I');
240         int xascent = fm.dimension('x').ascent();
241         if (xascent >= dim.asc)
242                 xascent = (2 * dim.asc) / 3;
243         minasc_ = xascent;
244         mindes_ = (3 * xascent) / 4;
245         slevel_ = (4 * xascent) / 5;
246         sshift_ = xascent / 4;
247         kerning_ = 0;
248
249         if (empty()) {
250                 // Cache the dimension.
251                 mi.base.bv->coordCache().arrays().add(this, dim);
252                 return;
253         }
254
255         Cursor & cur = mi.base.bv->cursor();
256         const_cast<MathData*>(this)->updateMacros(&cur, mi.macrocontext, InternalUpdate);
257
258         DocIterator const & inlineCompletionPos = mi.base.bv->inlineCompletionPos();
259         MathData const * inlineCompletionData = 0;
260         if (inlineCompletionPos.inMathed())
261                 inlineCompletionData = &inlineCompletionPos.cell();
262
263         dim.asc = 0;
264         dim.wid = 0;
265         Dimension d;
266         CoordCacheBase<Inset> & coords = mi.base.bv->coordCache().insets();
267         for (pos_type i = 0, n = size(); i != n; ++i) {
268                 MathAtom const & at = operator[](i);
269                 at->metrics(mi, d);
270                 coords.add(at.nucleus(), d);
271                 dim += d;
272                 if (i == n - 1)
273                         kerning_ = at->kerning(mi.base.bv);
274                 
275                 // HACK to draw completion suggestion inline
276                 if (inlineCompletionData != this
277                     || size_t(inlineCompletionPos.pos()) != i + 1)
278                         continue;
279                 
280                 docstring const & completion = mi.base.bv->inlineCompletion();
281                 if (completion.length() == 0)
282                         continue;
283                 
284                 FontInfo font = mi.base.font;
285                 augmentFont(font, from_ascii("mathnormal"));
286                 dim.wid += mathed_string_width(font, completion);
287         }
288         // Cache the dimension.
289         mi.base.bv->coordCache().arrays().add(this, dim);
290 }
291
292
293 void MathData::draw(PainterInfo & pi, int x, int y) const
294 {
295         //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
296         BufferView & bv  = *pi.base.bv;
297         setXY(bv, x, y);
298
299         Dimension const & dim = bv.coordCache().getArrays().dim(this);
300
301         if (empty()) {
302                 pi.pain.rectangle(x, y - dim.ascent(), dim.width(), dim.height(), Color_mathline);
303                 return;
304         }
305
306         // don't draw outside the workarea
307         if (y + dim.descent() <= 0
308                 || y - dim.ascent() >= bv.workHeight()
309                 || x + dim.width() <= 0
310                 || x >= bv. workWidth())
311                 return;
312
313         DocIterator const & inlineCompletionPos = bv.inlineCompletionPos();
314         MathData const * inlineCompletionData = 0;
315         if (inlineCompletionPos.inMathed())
316                 inlineCompletionData = &inlineCompletionPos.cell();
317
318         CoordCacheBase<Inset> & coords = pi.base.bv->coordCache().insets();
319         for (size_t i = 0, n = size(); i != n; ++i) {
320                 MathAtom const & at = operator[](i);
321                 coords.add(at.nucleus(), x, y);
322                 at->drawSelection(pi, x, y);
323                 at->draw(pi, x, y);
324                 x += coords.dim(at.nucleus()).wid;
325                 
326                 // Is the inline completion here?
327                 if (inlineCompletionData != this
328                     || size_t(inlineCompletionPos.pos()) != i + 1)
329                         continue;
330                 docstring const & completion = bv.inlineCompletion();
331                 if (completion.length() == 0)
332                         continue;
333                 FontInfo f = pi.base.font;
334                 augmentFont(f, from_ascii("mathnormal"));
335                 
336                 // draw the unique and the non-unique completion part
337                 // Note: this is not time-critical as it is
338                 // only done once per screen.
339                 size_t uniqueTo = bv.inlineCompletionUniqueChars();
340                 docstring s1 = completion.substr(0, uniqueTo);
341                 docstring s2 = completion.substr(uniqueTo);
342                 
343                 if (!s1.empty()) {
344                         f.setColor(Color_inlinecompletion);
345                         pi.pain.text(x, y, s1, f);
346                         x += mathed_string_width(f, s1);
347                 }
348                 
349                 if (!s2.empty()) {
350                         f.setColor(Color_nonunique_inlinecompletion);
351                         pi.pain.text(x, y, s2, f);
352                         x += mathed_string_width(f, s2);
353                 }
354         }
355 }
356
357
358 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
359 {
360         dim.clear();
361         Dimension d;
362         for (const_iterator it = begin(); it != end(); ++it) {
363                 (*it)->metricsT(mi, d);
364                 dim += d;
365         }
366 }
367
368
369 void MathData::drawT(TextPainter & pain, int x, int y) const
370 {
371         //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
372
373         // FIXME: Abdel 16/10/2006
374         // This drawT() method is never used, this is dead code.
375
376         for (const_iterator it = begin(), et = end(); it != et; ++it) {
377                 (*it)->drawT(pain, x, y);
378                 //x += (*it)->width_;
379                 x += 2;
380         }
381 }
382
383
384 void MathData::updateBuffer(ParIterator const & it, UpdateType utype)
385 {
386         // pass down
387         for (size_t i = 0, n = size(); i != n; ++i) {
388                 MathAtom & at = operator[](i);
389                 at.nucleus()->updateBuffer(it, utype);
390         }
391 }
392
393
394 void MathData::updateMacros(Cursor * cur, MacroContext const & mc,
395                 UpdateType utype)
396 {
397         // If we are editing a macro, we cannot update it immediately,
398         // otherwise wrong undo steps will be recorded (bug 6208).
399         InsetMath const * inmath = cur ? cur->inset().asInsetMath() : 0;
400         MathMacro const * inmacro = inmath ? inmath->asMacro() : 0;
401         docstring const edited_name = inmacro ? inmacro->name() : docstring();
402
403         // go over the array and look for macros
404         for (size_t i = 0; i < size(); ++i) {
405                 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
406                 if (!macroInset || macroInset->name_.empty()
407                                 || macroInset->name_[0] == '^'
408                                 || macroInset->name_[0] == '_'
409                                 || (macroInset->name() == edited_name
410                                     && macroInset->displayMode() ==
411                                                 MathMacro::DISPLAY_UNFOLDED))
412                         continue;
413
414                 // get macro
415                 macroInset->updateMacro(mc);
416                 size_t macroNumArgs = 0;
417                 size_t macroOptionals = 0;
418                 MacroData const * macro = macroInset->macro();
419                 if (macro) {
420                         macroNumArgs = macro->numargs();
421                         macroOptionals = macro->optionals();
422                 }
423
424                 // store old and compute new display mode
425                 MathMacro::DisplayMode newDisplayMode;
426                 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
427                 newDisplayMode = macroInset->computeDisplayMode();
428
429                 // arity changed or other reason to detach?
430                 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
431                     && (macroInset->arity() != macroNumArgs
432                         || macroInset->optionals() != macroOptionals
433                         || newDisplayMode == MathMacro::DISPLAY_UNFOLDED)) {
434
435                         detachMacroParameters(cur, i);
436                         // FIXME: proper anchor handling, this removes the selection
437                         if (cur)
438                                 cur->clearSelection();
439                 }
440
441                 // the macro could have been copied while resizing this
442                 macroInset = operator[](i).nucleus()->asMacro();
443
444                 // Cursor in \label?
445                 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED 
446                     && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
447                         // put cursor in front of macro
448                         if (cur) {
449                                 int macroSlice = cur->find(macroInset);
450                                 if (macroSlice != -1)
451                                         cur->cutOff(macroSlice - 1);
452                         }
453                 }
454
455                 // update the display mode
456                 size_t appetite = macroInset->appetite();
457                 macroInset->setDisplayMode(newDisplayMode);
458
459                 // arity changed?
460                 if (newDisplayMode == MathMacro::DISPLAY_NORMAL 
461                     && (macroInset->arity() != macroNumArgs
462                         || macroInset->optionals() != macroOptionals)) {
463                         // is it a virgin macro which was never attached to parameters?
464                         bool fromInitToNormalMode
465                         = (oldDisplayMode == MathMacro::DISPLAY_INIT 
466                            || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
467                           && newDisplayMode == MathMacro::DISPLAY_NORMAL;
468                         
469                         // if the macro was entered interactively (i.e. not by paste or during
470                         // loading), it should not be greedy, but the cursor should
471                         // automatically jump into the macro when behind
472                         bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
473                         
474                         // attach parameters
475                         attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
476                                 fromInitToNormalMode, interactive, appetite);
477                         
478                         if (cur) {
479                                 // FIXME: proper anchor handling, this removes the selection
480                                 cur->updateInsets(&cur->bottom().inset());
481                                 cur->clearSelection();  
482                         }
483                 }
484
485                 // Give macro the chance to adapt to new situation.
486                 // The macroInset could be invalid now because it was put into a script 
487                 // inset and therefore "deep" copied. So get it again from the MathData.
488                 InsetMath * inset = operator[](i).nucleus();
489                 if (inset->asScriptInset())
490                         inset = inset->asScriptInset()->nuc()[0].nucleus();
491                 LASSERT(inset->asMacro(), continue);
492                 inset->asMacro()->updateRepresentation(cur, mc, utype);
493         }
494 }
495
496
497 void MathData::detachMacroParameters(DocIterator * cur, const size_type macroPos)
498 {
499         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
500         
501         // detach all arguments
502         vector<MathData> detachedArgs;
503         if (macroPos + 1 == size())
504                 // strip arguments if we are at the MathData end
505                 macroInset->detachArguments(detachedArgs, true);
506         else
507                 macroInset->detachArguments(detachedArgs, false);
508         
509         // find cursor slice
510         int curMacroSlice = -1;
511         if (cur)
512                 curMacroSlice = cur->find(macroInset);
513         idx_type curMacroIdx = -1;
514         pos_type curMacroPos = -1;
515         vector<CursorSlice> argSlices;
516         if (curMacroSlice != -1) {
517                 curMacroPos = (*cur)[curMacroSlice].pos();
518                 curMacroIdx = (*cur)[curMacroSlice].idx();
519                 cur->cutOff(curMacroSlice, argSlices);
520                 cur->pop_back();
521         }
522         
523         // only [] after the last non-empty argument can be dropped later 
524         size_t lastNonEmptyOptional = 0;
525         for (size_t l = 0; l < detachedArgs.size() && l < macroInset->optionals(); ++l) {
526                 if (!detachedArgs[l].empty())
527                         lastNonEmptyOptional = l;
528         }
529         
530         // optional arguments to be put back?
531         pos_type p = macroPos + 1;
532         size_t j = 0;
533         for (; j < detachedArgs.size() && j < macroInset->optionals(); ++j) {
534                 // another non-empty parameter follows?
535                 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
536                 
537                 // then we can drop empty optional parameters
538                 if (detachedArgs[j].empty() && canDropEmptyOptional) {
539                         if (curMacroIdx == j)
540                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 1;
541                         continue;
542                 }
543                 
544                 // Otherwise we don't drop an empty optional, put it back normally
545                 MathData optarg;
546                 asArray(from_ascii("[]"), optarg);
547                 MathData & arg = detachedArgs[j];
548                 
549                 // look for "]", i.e. put a brace around?
550                 InsetMathBrace * brace = 0;
551                 for (size_t q = 0; q < arg.size(); ++q) {
552                         if (arg[q]->getChar() == ']') {
553                                 // put brace
554                                 brace = new InsetMathBrace(buffer_);
555                                 break;
556                         }
557                 }
558                 
559                 // put arg between []
560                 if (brace) {
561                         brace->cell(0) = arg;
562                         optarg.insert(1, MathAtom(brace));
563                 } else
564                         optarg.insert(1, arg);
565                 
566                 // insert it into the array
567                 insert(p, optarg);
568                 p += optarg.size();
569                 
570                 // cursor in macro?
571                 if (curMacroSlice == -1)
572                         continue;
573                 
574                 // cursor in optional argument of macro?
575                 if (curMacroIdx == j) {
576                         if (brace) {
577                                 cur->append(0, curMacroPos);
578                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 2;
579                         } else
580                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
581                         cur->append(argSlices);
582                 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
583                         // cursor right of macro
584                         (*cur)[curMacroSlice - 1].pos() += optarg.size();
585         }
586         
587         // put them back into the MathData
588         for (; j < detachedArgs.size(); ++j, ++p) {
589                 MathData const & arg = detachedArgs[j];
590                 if (arg.size() == 1 
591                     && !arg[0]->asScriptInset()
592                     && !(arg[0]->asMacro() && arg[0]->asMacro()->arity() > 0))
593                         insert(p, arg[0]);
594                 else
595                         insert(p, MathAtom(new InsetMathBrace(arg)));
596                 
597                 // cursor in macro?
598                 if (curMacroSlice == -1)
599                         continue;
600                 
601                 // cursor in j-th argument of macro?
602                 if (curMacroIdx == j) {
603                         if (operator[](p).nucleus()->asBraceInset()) {
604                                 (*cur)[curMacroSlice - 1].pos() = p;
605                                 cur->append(0, curMacroPos);
606                                 cur->append(argSlices);
607                         } else {
608                                 (*cur)[curMacroSlice - 1].pos() = p; // + macroPos;
609                                 cur->append(argSlices);
610                         }
611                 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
612                         ++(*cur)[curMacroSlice - 1].pos();
613         }
614         
615         if (cur)
616                 cur->updateInsets(&cur->bottom().inset());
617 }
618
619
620 void MathData::attachMacroParameters(Cursor * cur, 
621         const size_type macroPos, const size_type macroNumArgs,
622         const int macroOptionals, const bool fromInitToNormalMode,
623         const bool interactiveInit, const size_t appetite)
624 {
625         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
626
627         // start at atom behind the macro again, maybe with some new arguments 
628         // from the detach phase above, to add them back into the macro inset
629         size_t p = macroPos + 1;
630         vector<MathData> detachedArgs;
631         MathAtom scriptToPutAround;
632
633         // find cursor slice again of this MathData
634         int thisSlice = -1;
635         if (cur)
636                 thisSlice = cur->find(*this);
637         int thisPos = -1;
638         if (thisSlice != -1)
639                 thisPos = (*cur)[thisSlice].pos();
640
641         // find arguments behind the macro
642         if (!interactiveInit) {
643                 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
644                         scriptToPutAround, macroPos, thisPos, thisSlice);
645         }
646         collectParameters(cur, macroNumArgs, detachedArgs, p,
647                 scriptToPutAround, macroPos, thisPos, thisSlice, appetite);
648
649         // attach arguments back to macro inset
650         macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
651
652         // found tail script? E.g. \foo{a}b^x
653         if (scriptToPutAround.nucleus()) {
654                 InsetMathScript * scriptInset =
655                         scriptToPutAround.nucleus()->asScriptInset();
656                 // In the math parser we remove empty braces in the base
657                 // of a script inset, but we have to restore them here.
658                 if (scriptInset->nuc().empty()) {
659                         MathData ar;
660                         scriptInset->nuc().push_back(
661                                         MathAtom(new InsetMathBrace(ar)));
662                 }
663                 // put macro into a script inset
664                 scriptInset->nuc()[0] = operator[](macroPos);
665                 operator[](macroPos) = scriptToPutAround;
666
667                 // go into the script inset nucleus
668                 if (cur && thisPos == int(macroPos))
669                         cur->append(0, 0);
670
671                 // get pointer to "deep" copied macro inset
672                 scriptInset = operator[](macroPos).nucleus()->asScriptInset();
673                 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();        
674         }
675
676         // remove them from the MathData
677         erase(begin() + macroPos + 1, begin() + p);
678
679         // cursor outside this MathData?
680         if (thisSlice == -1)
681                 return;
682
683         // fix cursor if right of p
684         if (thisPos >= int(p))
685                 (*cur)[thisSlice].pos() -= p - (macroPos + 1);
686
687         // was the macro inset just inserted interactively and was now folded
688         // and the cursor is just behind?
689         if ((*cur)[thisSlice].pos() == int(macroPos + 1)
690             && interactiveInit
691             && fromInitToNormalMode
692             && macroInset->arity() > 0
693             && thisSlice + 1 == int(cur->depth())) {
694                 // then enter it if the cursor was just behind
695                 (*cur)[thisSlice].pos() = macroPos;
696                 cur->push_back(CursorSlice(*macroInset));
697                 macroInset->idxFirst(*cur);
698         }
699 }
700
701
702 void MathData::collectOptionalParameters(Cursor * cur, 
703         const size_type numOptionalParams, vector<MathData> & params, 
704         size_t & pos, MathAtom & scriptToPutAround,
705         const pos_type macroPos, const int thisPos, const int thisSlice)
706 {
707         Buffer * buf = cur ? cur->buffer() : 0;
708         // insert optional arguments?
709         while (params.size() < numOptionalParams 
710                && pos < size()
711                && !scriptToPutAround.nucleus()) {
712                 // is a [] block following which could be an optional parameter?
713                 if (operator[](pos)->getChar() != '[')
714                         break;
715                 
716                 // found possible optional argument, look for "]"
717                 size_t right = pos + 1;
718                 for (; right < size(); ++right) {
719                         MathAtom & cell = operator[](right);
720
721                         if (cell->getChar() == ']')
722                                 // found right end
723                                 break;
724                         
725                         // maybe "]" with a script around?
726                         InsetMathScript * script = cell.nucleus()->asScriptInset();
727                         if (!script)
728                                 continue;
729                         if (script->nuc().size() != 1)
730                                 continue;
731                         if (script->nuc()[0]->getChar() == ']') {
732                                 // script will be put around the macro later
733                                 scriptToPutAround = cell;
734                                 break;
735                         }
736                 }
737                 
738                 // found?
739                 if (right >= size()) {
740                         // no ] found, so it's not an optional argument
741                         break;
742                 }
743                 
744                 // add everything between [ and ] as optional argument
745                 MathData optarg(buf, begin() + pos + 1, begin() + right);
746                 
747                 // a brace?
748                 bool brace = false;
749                 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
750                         brace = true;
751                         params.push_back(optarg[0]->asBraceInset()->cell(0));
752                 } else
753                         params.push_back(optarg);
754                 
755                 // place cursor in optional argument of macro
756                 if (thisSlice != -1
757                     && thisPos >= int(pos) && thisPos <= int(right)) {
758                         int paramPos = max(0, thisPos - int(pos) - 1);
759                         vector<CursorSlice> x;
760                         cur->cutOff(thisSlice, x);
761                         (*cur)[thisSlice].pos() = macroPos;
762                         if (brace) {
763                                 paramPos = x[0].pos();
764                                 x.erase(x.begin());
765                         }
766                         cur->append(0, paramPos);
767                         cur->append(x);
768                 }
769                 pos = right + 1;
770         }
771
772         // fill up empty optional parameters
773         while (params.size() < numOptionalParams)
774                 params.push_back(MathData());   
775 }
776
777
778 void MathData::collectParameters(Cursor * cur, 
779         const size_type numParams, vector<MathData> & params, 
780         size_t & pos, MathAtom & scriptToPutAround,
781         const pos_type macroPos, const int thisPos, const int thisSlice,
782         const size_t appetite) 
783 {
784         size_t startSize = params.size();
785         
786         // insert normal arguments
787         while (params.size() < numParams
788                && params.size() - startSize < appetite
789                && pos < size()
790                && !scriptToPutAround.nucleus()) {
791                 MathAtom & cell = operator[](pos);
792                 
793                 // fix cursor
794                 vector<CursorSlice> argSlices;
795                 int argPos = 0;
796                 if (thisSlice != -1 && thisPos == int(pos))
797                         cur->cutOff(thisSlice, argSlices);              
798                 
799                 // which kind of parameter is it? In {}? With index x^n?
800                 InsetMathBrace const * brace = cell->asBraceInset();
801                 if (brace) {
802                         // found brace, convert into argument
803                         params.push_back(brace->cell(0));
804                         
805                         // cursor inside of the brace or just in front of?
806                         if (thisPos == int(pos) && !argSlices.empty()) {
807                                 argPos = argSlices[0].pos();
808                                 argSlices.erase(argSlices.begin());
809                         }
810                 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
811                         // last inset with scripts without braces
812                         // -> they belong to the macro, not the argument
813                         InsetMathScript * script = cell.nucleus()->asScriptInset();
814                         if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
815                                 // nucleus in brace? Unpack!
816                                 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
817                         else
818                                 params.push_back(script->nuc());
819                         
820                         // script will be put around below
821                         scriptToPutAround = cell;
822                         
823                         // this should only happen after loading, so make cursor handling simple
824                         if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
825                                 argSlices.clear();
826                                 if (cur)
827                                         cur->append(0, 0);
828                         }
829                 } else {
830                         // the simplest case: plain inset
831                         MathData array;
832                         array.insert(0, cell);
833                         params.push_back(array);
834                 }
835                 
836                 // put cursor in argument again
837                 if (thisSlice != - 1 && thisPos == int(pos)) {
838                         cur->append(params.size() - 1, argPos);
839                         cur->append(argSlices);
840                         (*cur)[thisSlice].pos() = macroPos;
841                 }
842                 
843                 ++pos;
844         }       
845 }
846
847
848 int MathData::pos2x(BufferView const * bv, size_type pos) const
849 {
850         return pos2x(bv, pos, 0);
851 }
852
853
854 int MathData::pos2x(BufferView const * bv, size_type pos, int glue) const
855 {
856         int x = 0;
857         size_type target = min(pos, size());
858         CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
859         for (size_type i = 0; i < target; ++i) {
860                 const_iterator it = begin() + i;
861                 if ((*it)->getChar() == ' ')
862                         x += glue;
863                 //lyxerr << "char: " << (*it)->getChar()
864                 //      << "width: " << (*it)->width() << endl;
865                 x += coords.dim((*it).nucleus()).wid;
866         }
867         return x;
868 }
869
870
871 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx) const
872 {
873         return x2pos(bv, targetx, 0);
874 }
875
876
877 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx, int glue) const
878 {
879         const_iterator it = begin();
880         int lastx = 0;
881         int currx = 0;
882         CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
883         // find first position after targetx
884         for (; currx < targetx && it < end(); ++it) {
885                 lastx = currx;
886                 if ((*it)->getChar() == ' ')
887                         currx += glue;
888                 currx += coords.dim((*it).nucleus()).wid;
889         }
890
891         /**
892          * If we are not at the beginning of the array, go to the left
893          * of the inset if one of the following two condition holds:
894          * - the current inset is editable (so that the cursor tip is
895          *   deeper than us): in this case, we want all intermediate
896          *   cursor slices to be before insets;
897          * - the mouse is closer to the left side of the inset than to
898          *   the right one.
899          * See bug 1918 for details.
900          **/
901         if (it != begin() && currx >= targetx
902             && ((*boost::prior(it))->asNestInset()
903                 || abs(lastx - targetx) < abs(currx - targetx))) {
904                 --it;
905         }
906
907         return it - begin();
908 }
909
910
911 int MathData::dist(BufferView const & bv, int x, int y) const
912 {
913         return bv.coordCache().getArrays().squareDistance(this, x, y);
914 }
915
916
917 void MathData::setXY(BufferView & bv, int x, int y) const
918 {
919         //lyxerr << "setting position cache for MathData " << this << endl;
920         bv.coordCache().arrays().add(this, x, y);
921 }
922
923
924 Dimension const & MathData::dimension(BufferView const & bv) const
925 {
926         return bv.coordCache().getArrays().dim(this);
927 }
928
929
930 int MathData::xm(BufferView const & bv) const
931 {
932         Geometry const & g = bv.coordCache().getArrays().geometry(this);
933
934         return g.pos.x_ + g.dim.wid / 2;
935 }
936
937
938 int MathData::ym(BufferView const & bv) const
939 {
940         Geometry const & g = bv.coordCache().getArrays().geometry(this);
941
942         return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
943 }
944
945
946 int MathData::xo(BufferView const & bv) const
947 {
948         return bv.coordCache().getArrays().x(this);
949 }
950
951
952 int MathData::yo(BufferView const & bv) const
953 {
954         return bv.coordCache().getArrays().y(this);
955 }
956
957
958 ostream & operator<<(ostream & os, MathData const & ar)
959 {
960         odocstringstream oss;
961         NormalStream ns(oss);
962         ns << ar;
963         return os << to_utf8(oss.str());
964 }
965
966
967 odocstream & operator<<(odocstream & os, MathData const & ar)
968 {
969         NormalStream ns(os);
970         ns << ar;
971         return os;
972 }
973
974
975 } // namespace lyx