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