]> git.lyx.org Git - lyx.git/blob - src/mathed/math_gridinset.C
the DocIterator stuff
[lyx.git] / src / mathed / math_gridinset.C
1 /**
2  * \file math_gridinset.C
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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "math_gridinset.h"
14 #include "math_data.h"
15 #include "math_mathmlstream.h"
16 #include "math_streamstr.h"
17 #include "BufferView.h"
18 #include "cursor.h"
19 #include "debug.h"
20 #include "funcrequest.h"
21 #include "LColor.h"
22
23 #include "frontends/Painter.h"
24
25 #include "support/std_sstream.h"
26
27 #include "insets/mailinset.h"
28
29 using std::endl;
30 using std::max;
31 using std::min;
32 using std::swap;
33
34 using std::string;
35 using std::auto_ptr;
36 using std::istream;
37 using std::istringstream;
38 using std::ostringstream;
39 using std::vector;
40
41
42 class GridInsetMailer : public MailInset {
43 public:
44         GridInsetMailer(MathGridInset & inset) : inset_(inset) {}
45         ///
46         virtual string const & name() const
47         {
48                 static string const theName = "tabular";
49                 return theName;
50         }
51         ///
52         virtual string const inset2string(Buffer const &) const
53         {
54                 ostringstream data;
55                 //data << name() << " active_cell " << inset.getActCell() << '\n';
56                 data << name() << " active_cell " << 0 << '\n';
57                 WriteStream ws(data);
58                 inset_.write(ws);
59                 return data.str();
60         }
61
62 protected:
63         InsetBase & inset() const { return inset_; }
64         MathGridInset & inset_;
65 };
66
67
68 void mathed_parse_normal(MathGridInset &, string const & argument);
69
70 namespace {
71
72 string verboseHLine(int n)
73 {
74         string res;
75         for (int i = 0; i < n; ++i)
76                 res += "\\hline";
77         if (n)
78                 res += ' ';
79         return res;
80 }
81
82
83 int extractInt(istream & is)
84 {
85         int num = 1;
86         is >> num;
87         return (num == 0) ? 1 : num;
88 }
89
90 }
91
92
93 //////////////////////////////////////////////////////////////
94
95
96 MathGridInset::CellInfo::CellInfo()
97         : dummy_(false)
98 {}
99
100
101
102
103 //////////////////////////////////////////////////////////////
104
105
106 MathGridInset::RowInfo::RowInfo()
107         : lines_(0), skip_(0)
108 {}
109
110
111
112 int MathGridInset::RowInfo::skipPixels() const
113 {
114         return crskip_.inBP();
115 }
116
117
118
119 //////////////////////////////////////////////////////////////
120
121
122 MathGridInset::ColInfo::ColInfo()
123         : align_('c'), leftline_(false), rightline_(false), lines_(0)
124 {}
125
126
127 //////////////////////////////////////////////////////////////
128
129
130 MathGridInset::MathGridInset(char v, string const & h)
131         : MathNestInset(guessColumns(h)),
132           rowinfo_(2),
133           colinfo_(guessColumns(h) + 1),
134           cellinfo_(1 * guessColumns(h))
135 {
136         setDefaults();
137         valign(v);
138         halign(h);
139         //lyxerr << "created grid with " << ncols() << " columns" << endl;
140 }
141
142
143 MathGridInset::MathGridInset()
144         : MathNestInset(1),
145           rowinfo_(1 + 1),
146                 colinfo_(1 + 1),
147                 cellinfo_(1),
148                 v_align_('c')
149 {
150         setDefaults();
151 }
152
153
154 MathGridInset::MathGridInset(col_type m, row_type n)
155         : MathNestInset(m * n),
156           rowinfo_(n + 1),
157                 colinfo_(m + 1),
158                 cellinfo_(m * n),
159                 v_align_('c')
160 {
161         setDefaults();
162 }
163
164
165 MathGridInset::MathGridInset(col_type m, row_type n, char v, string const & h)
166         : MathNestInset(m * n),
167           rowinfo_(n + 1),
168           colinfo_(m + 1),
169                 cellinfo_(m * n),
170                 v_align_(v)
171 {
172         setDefaults();
173         valign(v);
174         halign(h);
175 }
176
177
178 MathGridInset::~MathGridInset()
179 {
180         GridInsetMailer mailer(*this);
181         mailer.hideDialog();
182 }
183
184
185 auto_ptr<InsetBase> MathGridInset::clone() const
186 {
187         return auto_ptr<InsetBase>(new MathGridInset(*this));
188 }
189
190
191 MathInset::idx_type MathGridInset::index(row_type row, col_type col) const
192 {
193         return col + ncols() * row;
194 }
195
196
197 void MathGridInset::setDefaults()
198 {
199         if (ncols() <= 0)
200                 lyxerr << "positive number of columns expected" << endl;
201         //if (nrows() <= 0)
202         //      lyxerr << "positive number of rows expected" << endl;
203         for (col_type col = 0; col < ncols(); ++col) {
204                 colinfo_[col].align_ = defaultColAlign(col);
205                 colinfo_[col].skip_  = defaultColSpace(col);
206         }
207 }
208
209
210 void MathGridInset::halign(string const & hh)
211 {
212         col_type col = 0;
213         for (string::const_iterator it = hh.begin(); it != hh.end(); ++it) {
214                 if (col >= ncols())
215                         break;
216                 char c = *it;
217                 if (c == '|') {
218                         colinfo_[col].lines_++;
219                 } else if (c == 'c' || c == 'l' || c == 'r') {
220                         colinfo_[col].align_ = c;
221                         ++col;
222                         colinfo_[col].lines_ = 0;
223                 } else {
224                         lyxerr << "unknown column separator: '" << c << "'" << endl;
225                 }
226         }
227
228 /*
229         col_type n = hh.size();
230         if (n > ncols())
231                 n = ncols();
232         for (col_type col = 0; col < n; ++col)
233                 colinfo_[col].align_ = hh[col];
234 */
235 }
236
237
238 MathGridInset::col_type MathGridInset::guessColumns(string const & hh) const
239 {
240         col_type col = 0;
241         for (string::const_iterator it = hh.begin(); it != hh.end(); ++it)
242                 if (*it == 'c' || *it == 'l' || *it == 'r')
243                         ++col;
244         // let's have at least one column, even if we did not recognize its
245         // alignment
246         if (col == 0)
247                 col = 1;
248         return col;
249 }
250
251
252 void MathGridInset::halign(char h, col_type col)
253 {
254         colinfo_[col].align_ = h;
255 }
256
257
258 char MathGridInset::halign(col_type col) const
259 {
260         return colinfo_[col].align_;
261 }
262
263
264 string MathGridInset::halign() const
265 {
266         string res;
267         for (col_type col = 0; col < ncols(); ++col) {
268                 res += string(colinfo_[col].lines_, '|');
269                 res += colinfo_[col].align_;
270         }
271         return res + string(colinfo_[ncols()].lines_, '|');
272 }
273
274
275 void MathGridInset::valign(char c)
276 {
277         v_align_ = c;
278 }
279
280
281 char MathGridInset::valign() const
282 {
283         return v_align_;
284 }
285
286
287 MathGridInset::col_type MathGridInset::ncols() const
288 {
289         return colinfo_.size() - 1;
290 }
291
292
293 MathGridInset::row_type MathGridInset::nrows() const
294 {
295         return rowinfo_.size() - 1;
296 }
297
298
299 MathGridInset::col_type MathGridInset::col(idx_type idx) const
300 {
301         return idx % ncols();
302 }
303
304
305 MathGridInset::row_type MathGridInset::row(idx_type idx) const
306 {
307         return idx / ncols();
308 }
309
310
311 void MathGridInset::vcrskip(LyXLength const & crskip, row_type row)
312 {
313         rowinfo_[row].crskip_ = crskip;
314 }
315
316
317 LyXLength MathGridInset::vcrskip(row_type row) const
318 {
319         return rowinfo_[row].crskip_;
320 }
321
322
323 void MathGridInset::metrics(MetricsInfo & mi) const
324 {
325         // let the cells adjust themselves
326         MathNestInset::metrics(mi);
327
328         // compute absolute sizes of vertical structure
329         for (row_type row = 0; row < nrows(); ++row) {
330                 int asc  = 0;
331                 int desc = 0;
332                 for (col_type col = 0; col < ncols(); ++col) {
333                         MathArray const & c = cell(index(row, col));
334                         asc  = max(asc,  c.ascent());
335                         desc = max(desc, c.descent());
336                 }
337                 rowinfo_[row].ascent_  = asc;
338                 rowinfo_[row].descent_ = desc;
339         }
340         rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
341         rowinfo_[nrows()].ascent_  = 0;
342         rowinfo_[nrows()].descent_ = 0;
343
344         // compute vertical offsets
345         rowinfo_[0].offset_ = 0;
346         for (row_type row = 1; row <= nrows(); ++row) {
347                 rowinfo_[row].offset_  =
348                         rowinfo_[row - 1].offset_  +
349                         rowinfo_[row - 1].descent_ +
350                         rowinfo_[row - 1].skipPixels() +
351                         rowsep() +
352                         rowinfo_[row].lines_ * hlinesep() +
353                         rowinfo_[row].ascent_;
354         }
355
356         // adjust vertical offset
357         int h = 0;
358         switch (v_align_) {
359                 case 't':
360                         h = 0;
361                         break;
362                 case 'b':
363                         h = rowinfo_[nrows() - 1].offset_;
364                         break;
365                 default:
366                         h = rowinfo_[nrows() - 1].offset_ / 2;
367         }
368         for (row_type row = 0; row <= nrows(); ++row)
369                 rowinfo_[row].offset_ -= h;
370
371
372         // compute absolute sizes of horizontal structure
373         for (col_type col = 0; col < ncols(); ++col) {
374                 int wid = 0;
375                 for (row_type row = 0; row < nrows(); ++row)
376                         wid = max(wid, cell(index(row, col)).width());
377                 colinfo_[col].width_ = wid;
378         }
379         colinfo_[ncols()].width_  = 0;
380
381         // compute horizontal offsets
382         colinfo_[0].offset_ = border();
383         for (col_type col = 1; col <= ncols(); ++col) {
384                 colinfo_[col].offset_ =
385                         colinfo_[col - 1].offset_ +
386                         colinfo_[col - 1].width_ +
387                         colinfo_[col - 1].skip_ +
388                         colsep() +
389                         colinfo_[col].lines_ * vlinesep();
390         }
391
392
393         dim_.wid   =   colinfo_[ncols() - 1].offset_
394                        + colinfo_[ncols() - 1].width_
395                  + vlinesep() * colinfo_[ncols()].lines_
396                        + border();
397
398         dim_.asc  = - rowinfo_[0].offset_
399                        + rowinfo_[0].ascent_
400                  + hlinesep() * rowinfo_[0].lines_
401                        + border();
402
403         dim_.des =   rowinfo_[nrows() - 1].offset_
404                        + rowinfo_[nrows() - 1].descent_
405                  + hlinesep() * rowinfo_[nrows()].lines_
406                        + border();
407
408
409 /*
410         // Increase ws_[i] for 'R' columns (except the first one)
411         for (int i = 1; i < nc_; ++i)
412                 if (align_[i] == 'R')
413                         ws_[i] += 10 * df_width;
414         // Increase ws_[i] for 'C' column
415         if (align_[0] == 'C')
416                 if (ws_[0] < 7 * workwidth / 8)
417                         ws_[0] = 7 * workwidth / 8;
418
419         // Adjust local tabs
420         width = colsep();
421         for (cxrow = row_.begin(); cxrow; ++cxrow) {
422                 int rg = COLSEP;
423                 int lf = 0;
424                 for (int i = 0; i < nc_; ++i) {
425                         bool isvoid = false;
426                         if (cxrow->getTab(i) <= 0) {
427                                 cxrow->setTab(i, df_width);
428                                 isvoid = true;
429                         }
430                         switch (align_[i]) {
431                         case 'l':
432                                 lf = 0;
433                                 break;
434                         case 'c':
435                                 lf = (ws_[i] - cxrow->getTab(i))/2;
436                                 break;
437                         case 'r':
438                         case 'R':
439                                 lf = ws_[i] - cxrow->getTab(i);
440                                 break;
441                         case 'C':
442                                 if (cxrow == row_.begin())
443                                         lf = 0;
444                                 else if (cxrow.is_last())
445                                         lf = ws_[i] - cxrow->getTab(i);
446                                 else
447                                         lf = (ws_[i] - cxrow->getTab(i))/2;
448                                 break;
449                         }
450                         int const ww = (isvoid) ? lf : lf + cxrow->getTab(i);
451                         cxrow->setTab(i, lf + rg);
452                         rg = ws_[i] - ww + colsep();
453                         if (cxrow == row_.begin())
454                                 width += ws_[i] + colsep();
455                 }
456                 cxrow->setBaseline(cxrow->getBaseline() - ascent);
457         }
458 */
459 }
460
461
462 void MathGridInset::metrics(MetricsInfo & mi, Dimension & dim) const
463 {
464         metrics(mi);
465         dim = dim_;
466 }
467
468
469 void MathGridInset::draw(PainterInfo & pi, int x, int y) const
470 {
471         for (idx_type idx = 0; idx < nargs(); ++idx)
472                 cell(idx).draw(pi, x + cellXOffset(idx), y + cellYOffset(idx));
473
474         for (row_type row = 0; row <= nrows(); ++row)
475                 for (int i = 0; i < rowinfo_[row].lines_; ++i) {
476                         int yy = y + rowinfo_[row].offset_ - rowinfo_[row].ascent_
477                                 - i * hlinesep() - hlinesep()/2 - rowsep()/2;
478                         pi.pain.line(x + 1, yy,
479                                      x + dim_.width() - 1, yy,
480                                      LColor::foreground);
481                 }
482
483         for (col_type col = 0; col <= ncols(); ++col)
484                 for (int i = 0; i < colinfo_[col].lines_; ++i) {
485                         int xx = x + colinfo_[col].offset_
486                                 - i * vlinesep() - vlinesep()/2 - colsep()/2;
487                         pi.pain.line(xx, y - dim_.ascent() + 1,
488                                      xx, y + dim_.descent() - 1,
489                                      LColor::foreground);
490                 }
491 }
492
493
494 void MathGridInset::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
495 {
496         // let the cells adjust themselves
497         //MathNestInset::metrics(mi);
498         for (idx_type i = 0; i < nargs(); ++i)
499                 cell(i).metricsT(mi, dim);
500
501         // compute absolute sizes of vertical structure
502         for (row_type row = 0; row < nrows(); ++row) {
503                 int asc  = 0;
504                 int desc = 0;
505                 for (col_type col = 0; col < ncols(); ++col) {
506                         MathArray const & c = cell(index(row, col));
507                         asc  = max(asc,  c.ascent());
508                         desc = max(desc, c.descent());
509                 }
510                 rowinfo_[row].ascent_  = asc;
511                 rowinfo_[row].descent_ = desc;
512         }
513         //rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
514         rowinfo_[nrows()].ascent_  = 0;
515         rowinfo_[nrows()].descent_ = 0;
516
517         // compute vertical offsets
518         rowinfo_[0].offset_ = 0;
519         for (row_type row = 1; row <= nrows(); ++row) {
520                 rowinfo_[row].offset_  =
521                         rowinfo_[row - 1].offset_  +
522                         rowinfo_[row - 1].descent_ +
523                         //rowinfo_[row - 1].skipPixels() +
524                         1 + //rowsep() +
525                         //rowinfo_[row].lines_ * hlinesep() +
526                         rowinfo_[row].ascent_;
527         }
528
529         // adjust vertical offset
530         int h = 0;
531         switch (v_align_) {
532                 case 't':
533                         h = 0;
534                         break;
535                 case 'b':
536                         h = rowinfo_[nrows() - 1].offset_;
537                         break;
538                 default:
539                         h = rowinfo_[nrows() - 1].offset_ / 2;
540         }
541         for (row_type row = 0; row <= nrows(); ++row)
542                 rowinfo_[row].offset_ -= h;
543
544
545         // compute absolute sizes of horizontal structure
546         for (col_type col = 0; col < ncols(); ++col) {
547                 int wid = 0;
548                 for (row_type row = 0; row < nrows(); ++row)
549                         wid = max(wid, cell(index(row, col)).width());
550                 colinfo_[col].width_ = wid;
551         }
552         colinfo_[ncols()].width_  = 0;
553
554         // compute horizontal offsets
555         colinfo_[0].offset_ = border();
556         for (col_type col = 1; col <= ncols(); ++col) {
557                 colinfo_[col].offset_ =
558                         colinfo_[col - 1].offset_ +
559                         colinfo_[col - 1].width_ +
560                         colinfo_[col - 1].skip_ +
561                         1 ; //colsep() +
562                         //colinfo_[col].lines_ * vlinesep();
563         }
564
565
566         dim.wid  =  colinfo_[ncols() - 1].offset_
567                        + colinfo_[ncols() - 1].width_
568                  //+ vlinesep() * colinfo_[ncols()].lines_
569                        + 2;
570
571         dim.asc  = -rowinfo_[0].offset_
572                        + rowinfo_[0].ascent_
573                  //+ hlinesep() * rowinfo_[0].lines_
574                        + 1;
575
576         dim.des  =  rowinfo_[nrows() - 1].offset_
577                        + rowinfo_[nrows() - 1].descent_
578                  //+ hlinesep() * rowinfo_[nrows()].lines_
579                        + 1;
580 }
581
582
583 void MathGridInset::drawT(TextPainter & pain, int x, int y) const
584 {
585         for (idx_type idx = 0; idx < nargs(); ++idx)
586                 cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
587 }
588
589
590 string MathGridInset::eolString(row_type row, bool fragile) const
591 {
592         string eol;
593
594         if (!rowinfo_[row].crskip_.zero())
595                 eol += '[' + rowinfo_[row].crskip_.asLatexString() + ']';
596
597         // make sure an upcoming '[' does not break anything
598         if (row + 1 < nrows()) {
599                 MathArray const & c = cell(index(row + 1, 0));
600                 if (c.size() && c.front()->getChar() == '[')
601                         //eol += "[0pt]";
602                         eol += "{}";
603         }
604
605         // only add \\ if necessary
606         if (eol.empty() && row + 1 == nrows())
607                 return string();
608
609         return (fragile ? "\\protect\\\\" : "\\\\") + eol;
610 }
611
612
613 string MathGridInset::eocString(col_type col, col_type lastcol) const
614 {
615         if (col + 1 == lastcol)
616                 return string();
617         return " & ";
618 }
619
620
621 void MathGridInset::addRow(row_type row)
622 {
623         rowinfo_.insert(rowinfo_.begin() + row + 1, RowInfo());
624         cells_.insert
625                 (cells_.begin() + (row + 1) * ncols(), ncols(), MathArray());
626         cellinfo_.insert
627                 (cellinfo_.begin() + (row + 1) * ncols(), ncols(), CellInfo());
628 }
629
630
631 void MathGridInset::appendRow()
632 {
633         rowinfo_.push_back(RowInfo());
634         //cells_.insert(cells_.end(), ncols(), MathArray());
635         for (col_type col = 0; col < ncols(); ++col) {
636                 cells_.push_back(cells_type::value_type());
637                 cellinfo_.push_back(CellInfo());
638         }
639 }
640
641
642 void MathGridInset::delRow(row_type row)
643 {
644         if (nrows() == 1)
645                 return;
646
647         cells_type::iterator it = cells_.begin() + row * ncols();
648         cells_.erase(it, it + ncols());
649
650         vector<CellInfo>::iterator jt = cellinfo_.begin() + row * ncols();
651         cellinfo_.erase(jt, jt + ncols());
652
653         rowinfo_.erase(rowinfo_.begin() + row);
654 }
655
656
657 void MathGridInset::copyRow(row_type row)
658 {
659         addRow(row);
660         for (col_type col = 0; col < ncols(); ++col)
661                 cells_[(row + 1) * ncols() + col] = cells_[row * ncols() + col];
662 }
663
664
665 void MathGridInset::swapRow(row_type row)
666 {
667         if (nrows() == 1)
668                 return;
669         if (row + 1 == nrows())
670                 --row;
671         for (col_type col = 0; col < ncols(); ++col)
672                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
673 }
674
675
676 void MathGridInset::addCol(col_type newcol)
677 {
678         const col_type nc = ncols();
679         const row_type nr = nrows();
680         cells_type new_cells((nc + 1) * nr);
681         vector<CellInfo> new_cellinfo((nc + 1) * nr);
682
683         for (row_type row = 0; row < nr; ++row)
684                 for (col_type col = 0; col < nc; ++col) {
685                         new_cells[row * (nc + 1) + col + (col > newcol)]
686                                 = cells_[row * nc + col];
687                         new_cellinfo[row * (nc + 1) + col + (col > newcol)]
688                                 = cellinfo_[row * nc + col];
689                 }
690         swap(cells_, new_cells);
691         swap(cellinfo_, new_cellinfo);
692
693         ColInfo inf;
694         inf.skip_  = defaultColSpace(newcol);
695         inf.align_ = defaultColAlign(newcol);
696         colinfo_.insert(colinfo_.begin() + newcol, inf);
697 }
698
699
700 void MathGridInset::delCol(col_type col)
701 {
702         if (ncols() == 1)
703                 return;
704
705         cells_type tmpcells;
706         vector<CellInfo> tmpcellinfo;
707         for (col_type i = 0; i < nargs(); ++i)
708                 if (i % ncols() != col) {
709                         tmpcells.push_back(cells_[i]);
710                         tmpcellinfo.push_back(cellinfo_[i]);
711                 }
712         swap(cells_, tmpcells);
713         swap(cellinfo_, tmpcellinfo);
714
715         colinfo_.erase(colinfo_.begin() + col);
716 }
717
718
719 void MathGridInset::copyCol(col_type col)
720 {
721         addCol(col);
722         for (row_type row = 0; row < nrows(); ++row)
723                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
724 }
725
726
727 void MathGridInset::swapCol(col_type col)
728 {
729         if (ncols() == 1)
730                 return;
731         if (col + 1 == ncols())
732                 --col;
733         for (row_type row = 0; row < nrows(); ++row)
734                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
735 }
736
737
738 int MathGridInset::cellXOffset(idx_type idx) const
739 {
740         col_type c = col(idx);
741         int x = colinfo_[c].offset_;
742         char align = colinfo_[c].align_;
743         if (align == 'r' || align == 'R')
744                 x += colinfo_[c].width_ - cell(idx).width();
745         if (align == 'c' || align == 'C')
746                 x += (colinfo_[c].width_ - cell(idx).width()) / 2;
747         return x;
748 }
749
750
751 int MathGridInset::cellYOffset(idx_type idx) const
752 {
753         return rowinfo_[row(idx)].offset_;
754 }
755
756
757 bool MathGridInset::idxUpDown(LCursor & cur, bool up) const
758 {
759         if (up) {
760                 if (cur.idx() < ncols())
761                         return false;
762                 cur.idx() -= ncols();
763         } else {
764                 if (cur.idx() >= ncols() * (nrows() - 1))
765                         return false;
766                 cur.idx() += ncols();
767         }
768         cur.pos() = cur.cell().x2pos(cur.x_target() - cur.cell().xo());
769         return true;
770 }
771
772
773 bool MathGridInset::idxLeft(LCursor & cur) const
774 {
775         // leave matrix if on the left hand edge
776         if (cur.col() == 0)
777                 return false;
778         --cur.idx();
779         cur.pos() = cur.lastpos();
780         return true;
781 }
782
783
784 bool MathGridInset::idxRight(LCursor & cur) const
785 {
786         // leave matrix if on the right hand edge
787         if (cur.col() + 1 == ncols())
788                 return false;
789         ++cur.idx();
790         cur.pos() = 0;
791         return true;
792 }
793
794
795 bool MathGridInset::idxFirst(LCursor & cur) const
796 {
797         switch (v_align_) {
798                 case 't':
799                         cur.idx() = 0;
800                         break;
801                 case 'b':
802                         cur.idx() = (nrows() - 1) * ncols();
803                         break;
804                 default:
805                         cur.idx() = ((nrows() - 1) / 2) * ncols();
806         }
807         cur.pos() = 0;
808         return true;
809 }
810
811
812 bool MathGridInset::idxLast(LCursor & cur) const
813 {
814         switch (v_align_) {
815                 case 't':
816                         cur.idx() = ncols() - 1;
817                         break;
818                 case 'b':
819                         cur.idx() = nargs() - 1;
820                         break;
821                 default:
822                         cur.idx() = ((nrows() - 1) / 2 + 1) * ncols() - 1;
823         }
824         cur.pos() = cur.lastpos();
825         return true;
826 }
827
828
829 bool MathGridInset::idxDelete(idx_type & idx)
830 {
831         // nothing to do if we have just one row
832         if (nrows() == 1)
833                 return false;
834
835         // nothing to do if we are in the middle of the last row of the inset
836         if (idx + ncols() > nargs())
837                 return false;
838
839         // try to delete entire sequence of ncols() empty cells if possible
840         for (idx_type i = idx; i < idx + ncols(); ++i)
841                 if (cell(i).size())
842                         return false;
843
844         // move cells if necessary
845         for (idx_type i = index(row(idx), 0); i < idx; ++i)
846                 swap(cell(i), cell(i + ncols()));
847
848         delRow(row(idx));
849
850         if (idx >= nargs())
851                 idx = nargs() - 1;
852
853         // undo effect of Ctrl-Tab (i.e. pull next cell)
854         //if (idx + 1 != nargs())
855         //      cell(idx).swap(cell(idx + 1));
856
857         // we handled the event..
858         return true;
859 }
860
861
862 // reimplement old behaviour when pressing Delete in the last position
863 // of a cell
864 void MathGridInset::idxGlue(idx_type idx)
865 {
866         col_type c = col(idx);
867         if (c + 1 == ncols()) {
868                 if (row(idx) + 1 != nrows()) {
869                         for (col_type cc = 0; cc < ncols(); ++cc)
870                                 cell(idx).append(cell(idx + cc + 1));
871                         delRow(row(idx) + 1);
872                 }
873         } else {
874                 cell(idx).append(cell(idx + 1));
875                 for (col_type cc = c + 2; cc < ncols(); ++cc)
876                         cell(idx - c + cc - 1) = cell(idx - c + cc);
877                 cell(idx - c + ncols() - 1).clear();
878         }
879 }
880
881
882 MathGridInset::RowInfo const & MathGridInset::rowinfo(row_type row) const
883 {
884         return rowinfo_[row];
885 }
886
887
888 MathGridInset::RowInfo & MathGridInset::rowinfo(row_type row)
889 {
890         return rowinfo_[row];
891 }
892
893
894 bool MathGridInset::idxBetween(idx_type idx, idx_type from, idx_type to) const
895 {
896         row_type const ri = row(idx);
897         row_type const r1 = min(row(from), row(to));
898         row_type const r2 = max(row(from), row(to));
899         col_type const ci = col(idx);
900         col_type const c1 = min(col(from), col(to));
901         col_type const c2 = max(col(from), col(to));
902         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
903 }
904
905
906
907 void MathGridInset::normalize(NormalStream & os) const
908 {
909         os << "[grid ";
910         for (row_type row = 0; row < nrows(); ++row) {
911                 os << "[row ";
912                 for (col_type col = 0; col < ncols(); ++col)
913                         os << "[cell " << cell(index(row, col)) << ']';
914                 os << ']';
915         }
916         os << ']';
917 }
918
919
920 void MathGridInset::mathmlize(MathMLStream & os) const
921 {
922         os << MTag("mtable");
923         for (row_type row = 0; row < nrows(); ++row) {
924                 os << MTag("mtr");
925                 for (col_type col = 0; col < ncols(); ++col)
926                         os << cell(index(row, col));
927                 os << ETag("mtr");
928         }
929         os << ETag("mtable");
930 }
931
932
933 void MathGridInset::write(WriteStream & os) const
934 {
935         for (row_type row = 0; row < nrows(); ++row) {
936                 os << verboseHLine(rowinfo_[row].lines_);
937                 // don't write & and empty cells at end of line
938                 col_type lastcol = 0;
939                 bool emptyline = true;
940                 for (col_type col = 0; col < ncols(); ++col)
941                         if (!cell(index(row, col)).empty()) {
942                                 lastcol = col + 1;
943                                 emptyline = false;
944                         }
945                 for (col_type col = 0; col < lastcol; ++col)
946                         os << cell(index(row, col)) << eocString(col, lastcol);
947                 os << eolString(row, os.fragile());
948                 // append newline only if line wasn't completely empty
949                 // and this was not the last line in the grid
950                 if (!emptyline && row + 1 < nrows())
951                         os << "\n";
952         }
953         string const s = verboseHLine(rowinfo_[nrows()].lines_);
954         if (!s.empty() && s != " ") {
955                 if (os.fragile())
956                         os << "\\protect";
957                 os << "\\\\" << s;
958         }
959 }
960
961
962 int MathGridInset::colsep() const
963 {
964         return 6;
965 }
966
967
968 int MathGridInset::rowsep() const
969 {
970         return 6;
971 }
972
973
974 int MathGridInset::hlinesep() const
975 {
976         return 3;
977 }
978
979
980 int MathGridInset::vlinesep() const
981 {
982         return 3;
983 }
984
985
986 int MathGridInset::border() const
987 {
988         return 1;
989 }
990
991
992 void MathGridInset::splitCell(LCursor & cur)
993 {
994         if (cur.idx() == cur.lastidx())
995                 return;
996         MathArray ar = cur.cell();
997         ar.erase(0, cur.pos());
998         cur.cell().erase(cur.pos(), cur.lastpos());
999         ++cur.idx();
1000         cur.pos() = 0;
1001         cur.cell().insert(0, ar);
1002 }
1003
1004
1005 void MathGridInset::priv_dispatch(LCursor & cur, FuncRequest const & cmd)
1006 {
1007         //lyxerr << "*** MathGridInset: request: " << cmd << endl;
1008         switch (cmd.action) {
1009
1010         case LFUN_MOUSE_RELEASE:
1011                 //if (cmd.button() == mouse_button::button3) {
1012                 //      GridInsetMailer(*this).showDialog();
1013                 //      return DispatchResult(true, true);
1014                 //}
1015                 MathNestInset::priv_dispatch(cur, cmd);
1016                 return;
1017
1018         case LFUN_INSET_DIALOG_UPDATE:
1019                 GridInsetMailer(*this).updateDialog(&cur.bv());
1020                 return;
1021
1022         // insert file functions
1023         case LFUN_DELETE_LINE_FORWARD:
1024                 //autocorrect_ = false;
1025                 //macroModeClose();
1026                 //if (selection_) {
1027                 //      selDel();
1028                 //      return;
1029                 //}
1030                 if (nrows() > 1)
1031                         delRow(cur.row());
1032                 if (cur.idx() > cur.lastidx())
1033                         cur.idx() = cur.lastidx();
1034                 if (cur.pos() > cur.lastpos())
1035                         cur.pos() = cur.lastpos();
1036                 return;
1037
1038         case LFUN_CELL_SPLIT:
1039                 ////recordUndo(cur, Undo::ATOMIC);
1040                 splitCell(cur);
1041                 return;
1042
1043         case LFUN_BREAKLINE: {
1044                 ////recordUndo(cur, Undo::INSERT);
1045                 row_type const r = cur.row();
1046                 addRow(r);
1047
1048                 // split line
1049                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1050                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1051
1052                 // split cell
1053                 splitCell(cur);
1054                 swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1055                 if (cur.idx() > 0)
1056                         --cur.idx();
1057                 cur.idx() = cur.lastpos();
1058
1059                 //mathcursor->normalize();
1060                 cur.dispatched(FINISHED_LEFT);
1061                 return;
1062         }
1063
1064         case LFUN_TABULAR_FEATURE: {
1065                 //lyxerr << "handling tabular-feature " << cmd.argument << endl;
1066                 istringstream is(cmd.argument);
1067                 string s;
1068                 is >> s;
1069                 if (s == "valign-top")
1070                         valign('t');
1071                 else if (s == "valign-middle")
1072                         valign('c');
1073                 else if (s == "valign-bottom")
1074                         valign('b');
1075                 else if (s == "align-left")
1076                         halign('l', col(cur.idx()));
1077                 else if (s == "align-right")
1078                         halign('r', col(cur.idx()));
1079                 else if (s == "align-center")
1080                         halign('c', col(cur.idx()));
1081                 else if (s == "append-row")
1082                         for (int i = 0, n = extractInt(is); i < n; ++i)
1083                                 addRow(cur.row());
1084                 else if (s == "delete-row")
1085                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1086                                 delRow(cur.row());
1087                                 if (cur.idx() > nargs())
1088                                         cur.idx() -= ncols();
1089                         }
1090                 else if (s == "copy-row")
1091                         for (int i = 0, n = extractInt(is); i < n; ++i)
1092                                 copyRow(cur.row());
1093                 else if (s == "swap-row")
1094                         swapRow(cur.row());
1095                 else if (s == "append-column")
1096                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1097                                 row_type r = cur.row();
1098                                 col_type c = col(cur.idx());
1099                                 addCol(c);
1100                                 cur.idx() = index(r, c);
1101                         }
1102                 else if (s == "delete-column")
1103                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1104                                 row_type r = cur.row();
1105                                 col_type c = col(cur.idx());
1106                                 delCol(col(cur.idx()));
1107                                 cur.idx() = index(r, c);
1108                                 if (cur.idx() > nargs())
1109                                         cur.idx() -= ncols();
1110                         }
1111                 else if (s == "copy-column")
1112                         copyCol(col(cur.idx()));
1113                 else if (s == "swap-column")
1114                         swapCol(col(cur.idx()));
1115                 else {
1116                         cur.undispatched();
1117                         return;
1118                 }
1119                 lyxerr << "returning FINISHED_LEFT" << endl;
1120                 return;
1121         }
1122
1123         case LFUN_PASTE: {
1124                 //lyxerr << "pasting '" << cmd.argument << "'" << endl;
1125                 MathGridInset grid(1, 1);
1126                 mathed_parse_normal(grid, cmd.argument);
1127                 if (grid.nargs() == 1) {
1128                         // single cell/part of cell
1129                         cur.cell().insert(cur.pos(), grid.cell(0));
1130                         cur.pos() += grid.cell(0).size();
1131                 } else {
1132                         // multiple cells
1133                         col_type const numcols =
1134                                 min(grid.ncols(), ncols() - col(cur.idx()));
1135                         row_type const numrows =
1136                                 min(grid.nrows(), nrows() - cur.row());
1137                         for (row_type r = 0; r < numrows; ++r) {
1138                                 for (col_type c = 0; c < numcols; ++c) {
1139                                         idx_type i = index(r + cur.row(), c + col(cur.idx()));
1140                                         cell(i).insert(0, grid.cell(grid.index(r, c)));
1141                                 }
1142                                 // append the left over horizontal cells to the last column
1143                                 idx_type i = index(r + cur.row(), ncols() - 1);
1144                                 for (MathInset::col_type c = numcols; c < grid.ncols(); ++c)
1145                                         cell(i).append(grid.cell(grid.index(r, c)));
1146                         }
1147                         // append the left over vertical cells to the last _cell_
1148                         idx_type i = nargs() - 1;
1149                         for (row_type r = numrows; r < grid.nrows(); ++r)
1150                                 for (col_type c = 0; c < grid.ncols(); ++c)
1151                                         cell(i).append(grid.cell(grid.index(r, c)));
1152                 }
1153                 return;
1154         }
1155
1156         case LFUN_HOMESEL:
1157         case LFUN_HOME:
1158         case LFUN_WORDLEFTSEL:
1159         case LFUN_WORDLEFT:
1160                 cur.selHandle(cmd.action == LFUN_WORDLEFTSEL || cmd.action == LFUN_HOMESEL);
1161                 cur.macroModeClose();
1162                 if (cur.pos() != 0)
1163                         cur.pos() = 0;
1164                 else if (cur.idx() != 0)
1165                         cur.idx() = 0;
1166                 else
1167                         cur.dispatched(FINISHED_LEFT);
1168                 break;
1169
1170         case LFUN_WORDRIGHTSEL:
1171         case LFUN_WORDRIGHT:
1172         case LFUN_ENDSEL:
1173         case LFUN_END:
1174                 cur.selHandle(cmd.action == LFUN_WORDRIGHTSEL || cmd.action == LFUN_ENDSEL);
1175                 cur.macroModeClose();
1176                 cur.clearTargetX();
1177                 if (cur.pos() != cur.lastpos())
1178                         cur.pos() = cur.lastpos();
1179                 else if (cur.idx() != cur.lastidx())
1180                         cur.idx() = cur.lastidx();
1181                 else
1182                         cur.dispatched(FINISHED_RIGHT);
1183                 break;
1184
1185         default:
1186                 MathNestInset::priv_dispatch(cur, cmd);
1187                 return;
1188         }
1189 }