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