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