]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
Stupid bug fix.
[lyx.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Matthias Ettrich
8  * \author José Matos
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Jürgen Vigna
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "InsetTabular.h"
21
22 #include "buffer_funcs.h"
23 #include "Buffer.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
27 #include "Counters.h"
28 #include "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Language.h"
34 #include "LaTeXFeatures.h"
35 #include "Lexer.h"
36 #include "LyXFunc.h"
37 #include "LyXRC.h"
38 #include "MetricsInfo.h"
39 #include "OutputParams.h"
40 #include "paragraph_funcs.h"
41 #include "Paragraph.h"
42 #include "ParagraphParameters.h"
43 #include "ParIterator.h"
44 #include "TextClass.h"
45 #include "TextMetrics.h"
46
47 #include "frontends/Application.h"
48 #include "frontends/alert.h"
49 #include "frontends/Clipboard.h"
50 #include "frontends/Painter.h"
51 #include "frontends/Selection.h"
52
53 #include "support/convert.h"
54 #include "support/debug.h"
55 #include "support/docstream.h"
56 #include "support/FileName.h"
57 #include "support/gettext.h"
58 #include "support/lassert.h"
59 #include "support/lstrings.h"
60
61 #include <boost/scoped_ptr.hpp>
62
63 #include <sstream>
64 #include <iostream>
65 #include <limits>
66 #include <cstring>
67
68 using namespace std;
69 using namespace lyx::support;
70
71 using boost::shared_ptr;
72 using boost::dynamic_pointer_cast;
73
74
75 namespace lyx {
76
77 using cap::dirtyTabularStack;
78 using cap::tabularStackDirty;
79
80 using graphics::PreviewLoader;
81
82 using frontend::Painter;
83 using frontend::Clipboard;
84
85 namespace Alert = frontend::Alert;
86
87
88 namespace {
89
90 int const ADD_TO_HEIGHT = 2; // in cell
91 int const ADD_TO_TABULAR_WIDTH = 6; // horiz space before and after the table
92 int const default_line_space = 10; // ?
93 int const WIDTH_OF_LINE = 5; // space between double lines
94
95
96 ///
97 boost::scoped_ptr<Tabular> paste_tabular;
98
99
100 struct TabularFeature {
101         Tabular::Feature action;
102         string feature;
103 };
104
105
106 TabularFeature tabularFeature[] =
107 {
108         { Tabular::APPEND_ROW, "append-row" },
109         { Tabular::APPEND_COLUMN, "append-column" },
110         { Tabular::DELETE_ROW, "delete-row" },
111         { Tabular::DELETE_COLUMN, "delete-column" },
112         { Tabular::COPY_ROW, "copy-row" },
113         { Tabular::COPY_COLUMN, "copy-column" },
114         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top" },
115         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
116         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
117         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
118         { Tabular::ALIGN_LEFT, "align-left" },
119         { Tabular::ALIGN_RIGHT, "align-right" },
120         { Tabular::ALIGN_CENTER, "align-center" },
121         { Tabular::ALIGN_BLOCK, "align-block" },
122         { Tabular::VALIGN_TOP, "valign-top" },
123         { Tabular::VALIGN_BOTTOM, "valign-bottom" },
124         { Tabular::VALIGN_MIDDLE, "valign-middle" },
125         { Tabular::M_ALIGN_LEFT, "m-align-left" },
126         { Tabular::M_ALIGN_RIGHT, "m-align-right" },
127         { Tabular::M_ALIGN_CENTER, "m-align-center" },
128         { Tabular::M_VALIGN_TOP, "m-valign-top" },
129         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
130         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle" },
131         { Tabular::MULTICOLUMN, "multicolumn" },
132         { Tabular::SET_ALL_LINES, "set-all-lines" },
133         { Tabular::UNSET_ALL_LINES, "unset-all-lines" },
134         { Tabular::SET_LONGTABULAR, "set-longtabular" },
135         { Tabular::UNSET_LONGTABULAR, "unset-longtabular" },
136         { Tabular::SET_PWIDTH, "set-pwidth" },
137         { Tabular::SET_MPWIDTH, "set-mpwidth" },
138         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
139         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
140         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular" },
141         { Tabular::SET_ROTATE_CELL, "set-rotate-cell" },
142         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
143         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell" },
144         { Tabular::SET_USEBOX, "set-usebox" },
145         { Tabular::SET_LTHEAD, "set-lthead" },
146         { Tabular::UNSET_LTHEAD, "unset-lthead" },
147         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
148         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead" },
149         { Tabular::SET_LTFOOT, "set-ltfoot" },
150         { Tabular::UNSET_LTFOOT, "unset-ltfoot" },
151         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot" },
152         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot" },
153         { Tabular::SET_LTNEWPAGE, "set-ltnewpage" },
154         { Tabular::TOGGLE_LTCAPTION, "toggle-ltcaption" },
155         { Tabular::SET_SPECIAL_COLUMN, "set-special-column" },
156         { Tabular::SET_SPECIAL_MULTI, "set-special-multi" },
157         { Tabular::SET_BOOKTABS, "set-booktabs" },
158         { Tabular::UNSET_BOOKTABS, "unset-booktabs" },
159         { Tabular::SET_TOP_SPACE, "set-top-space" },
160         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space" },
161         { Tabular::SET_INTERLINE_SPACE, "set-interline-space" },
162         { Tabular::SET_BORDER_LINES, "set-border-lines" },
163         { Tabular::LAST_ACTION, "" }
164 };
165
166
167 class FeatureEqual : public unary_function<TabularFeature, bool> {
168 public:
169         FeatureEqual(Tabular::Feature feature)
170                 : feature_(feature) {}
171         bool operator()(TabularFeature const & tf) const {
172                 return tf.action == feature_;
173         }
174 private:
175         Tabular::Feature feature_;
176 };
177
178
179 template <class T>
180 string const write_attribute(string const & name, T const & t)
181 {
182         string const s = tostr(t);
183         return s.empty() ? s : " " + name + "=\"" + s + "\"";
184 }
185
186 template <>
187 string const write_attribute(string const & name, string const & t)
188 {
189         return t.empty() ? t : " " + name + "=\"" + t + "\"";
190 }
191
192
193 template <>
194 string const write_attribute(string const & name, docstring const & t)
195 {
196         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
197 }
198
199
200 template <>
201 string const write_attribute(string const & name, bool const & b)
202 {
203         // we write only true attribute values so we remove a bit of the
204         // file format bloat for tabulars.
205         return b ? write_attribute(name, convert<string>(b)) : string();
206 }
207
208
209 template <>
210 string const write_attribute(string const & name, int const & i)
211 {
212         // we write only true attribute values so we remove a bit of the
213         // file format bloat for tabulars.
214         return i ? write_attribute(name, convert<string>(i)) : string();
215 }
216
217
218 template <>
219 string const write_attribute(string const & name, Tabular::idx_type const & i)
220 {
221         // we write only true attribute values so we remove a bit of the
222         // file format bloat for tabulars.
223         return i ? write_attribute(name, convert<string>(i)) : string();
224 }
225
226
227 template <>
228 string const write_attribute(string const & name, Length const & value)
229 {
230         // we write only the value if we really have one same reson as above.
231         return value.zero() ? string() : write_attribute(name, value.asString());
232 }
233
234
235 string const tostr(LyXAlignment const & num)
236 {
237         switch (num) {
238         case LYX_ALIGN_NONE:
239                 return "none";
240         case LYX_ALIGN_BLOCK:
241                 return "block";
242         case LYX_ALIGN_LEFT:
243                 return "left";
244         case LYX_ALIGN_CENTER:
245                 return "center";
246         case LYX_ALIGN_RIGHT:
247                 return "right";
248         case LYX_ALIGN_LAYOUT:
249                 return "layout";
250         case LYX_ALIGN_SPECIAL:
251                 return "special";
252         }
253         return string();
254 }
255
256
257 string const tostr(Tabular::VAlignment const & num)
258 {
259         switch (num) {
260         case Tabular::LYX_VALIGN_TOP:
261                 return "top";
262         case Tabular::LYX_VALIGN_MIDDLE:
263                 return "middle";
264         case Tabular::LYX_VALIGN_BOTTOM:
265                 return "bottom";
266         }
267         return string();
268 }
269
270
271 string const tostr(Tabular::BoxType const & num)
272 {
273         switch (num) {
274         case Tabular::BOX_NONE:
275                 return "none";
276         case Tabular::BOX_PARBOX:
277                 return "parbox";
278         case Tabular::BOX_MINIPAGE:
279                 return "minipage";
280         }
281         return string();
282 }
283
284
285 // I would have liked a fromstr template a lot better. (Lgb)
286 bool string2type(string const str, LyXAlignment & num)
287 {
288         if (str == "none")
289                 num = LYX_ALIGN_NONE;
290         else if (str == "block")
291                 num = LYX_ALIGN_BLOCK;
292         else if (str == "left")
293                 num = LYX_ALIGN_LEFT;
294         else if (str == "center")
295                 num = LYX_ALIGN_CENTER;
296         else if (str == "right")
297                 num = LYX_ALIGN_RIGHT;
298         else
299                 return false;
300         return true;
301 }
302
303
304 bool string2type(string const str, Tabular::VAlignment & num)
305 {
306         if (str == "top")
307                 num = Tabular::LYX_VALIGN_TOP;
308         else if (str == "middle" )
309                 num = Tabular::LYX_VALIGN_MIDDLE;
310         else if (str == "bottom")
311                 num = Tabular::LYX_VALIGN_BOTTOM;
312         else
313                 return false;
314         return true;
315 }
316
317
318 bool string2type(string const str, Tabular::BoxType & num)
319 {
320         if (str == "none")
321                 num = Tabular::BOX_NONE;
322         else if (str == "parbox")
323                 num = Tabular::BOX_PARBOX;
324         else if (str == "minipage")
325                 num = Tabular::BOX_MINIPAGE;
326         else
327                 return false;
328         return true;
329 }
330
331
332 bool string2type(string const str, bool & num)
333 {
334         if (str == "true")
335                 num = true;
336         else if (str == "false")
337                 num = false;
338         else
339                 return false;
340         return true;
341 }
342
343
344 bool getTokenValue(string const & str, char const * token, string & ret)
345 {
346         ret.erase();
347         size_t token_length = strlen(token);
348         size_t pos = str.find(token);
349
350         if (pos == string::npos || pos + token_length + 1 >= str.length()
351                 || str[pos + token_length] != '=')
352                 return false;
353         pos += token_length + 1;
354         char ch = str[pos];
355         if (ch != '"' && ch != '\'') { // only read till next space
356                 ret += ch;
357                 ch = ' ';
358         }
359         while (pos < str.length() - 1 && str[++pos] != ch)
360                 ret += str[pos];
361
362         return true;
363 }
364
365
366 bool getTokenValue(string const & str, char const * token, docstring & ret)
367 {
368         string tmp;
369         bool const success = getTokenValue(str, token, tmp);
370         ret = from_utf8(tmp);
371         return success;
372 }
373
374
375 bool getTokenValue(string const & str, char const * token, int & num)
376 {
377         string tmp;
378         num = 0;
379         if (!getTokenValue(str, token, tmp))
380                 return false;
381         num = convert<int>(tmp);
382         return true;
383 }
384
385
386 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
387 {
388         string tmp;
389         return getTokenValue(str, token, tmp) && string2type(tmp, num);
390 }
391
392
393 bool getTokenValue(string const & str, char const * token,
394                                    Tabular::VAlignment & num)
395 {
396         string tmp;
397         return getTokenValue(str, token, tmp) && string2type(tmp, num);
398 }
399
400
401 bool getTokenValue(string const & str, char const * token,
402                                    Tabular::BoxType & num)
403 {
404         string tmp;
405         return getTokenValue(str, token, tmp) && string2type(tmp, num);
406 }
407
408
409 bool getTokenValue(string const & str, char const * token, bool & flag)
410 {
411         // set the flag always to false as this should be the default for bools
412         // not in the file-format.
413         flag = false;
414         string tmp;
415         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
416 }
417
418
419 bool getTokenValue(string const & str, char const * token, Length & len)
420 {
421         // set the length to be zero() as default as this it should be if not
422         // in the file format.
423         len = Length();
424         string tmp;
425         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
426 }
427
428
429 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
430 {
431         len = Length();
432         flag = false;
433         string tmp;
434         if (!getTokenValue(str, token, tmp))
435                 return false;
436         if (tmp == "default") {
437                 flag = true;
438                 return  true;
439         }
440         return isValidLength(tmp, &len);
441 }
442
443
444 void l_getline(istream & is, string & str)
445 {
446         str.erase();
447         while (str.empty()) {
448                 getline(is, str);
449                 if (!str.empty() && str[str.length() - 1] == '\r')
450                         str.erase(str.length() - 1);
451         }
452 }
453
454 } // namespace
455
456
457 string const featureAsString(Tabular::Feature feature)
458 {
459         TabularFeature * end = tabularFeature +
460                 sizeof(tabularFeature) / sizeof(TabularFeature);
461         TabularFeature * it = find_if(tabularFeature, end,
462                                            FeatureEqual(feature));
463         return (it == end) ? string() : it->feature;
464 }
465
466
467
468 /////////////////////////////////////////////////////////////////////
469 //
470 // Tabular
471 //
472 /////////////////////////////////////////////////////////////////////
473
474
475 Tabular::CellData::CellData(Buffer & buf)
476         : cellno(0),
477           width(0),
478           multicolumn(Tabular::CELL_NORMAL),
479           alignment(LYX_ALIGN_CENTER),
480           valignment(LYX_VALIGN_TOP),
481           top_line(false),
482           bottom_line(false),
483           left_line(false),
484           right_line(false),
485           usebox(BOX_NONE),
486           rotate(false),
487           inset(new InsetTableCell(buf))
488 {
489         inset->setBuffer(const_cast<Buffer &>(buf));
490         inset->paragraphs().back().setLayout(buf.params().documentClass().emptyLayout());
491 }
492
493
494 Tabular::CellData::CellData(CellData const & cs)
495         : cellno(cs.cellno),
496           width(cs.width),
497           multicolumn(cs.multicolumn),
498           alignment(cs.alignment),
499           valignment(cs.valignment),
500           top_line(cs.top_line),
501           bottom_line(cs.bottom_line),
502           left_line(cs.left_line),
503           right_line(cs.right_line),
504           usebox(cs.usebox),
505           rotate(cs.rotate),
506           align_special(cs.align_special),
507           p_width(cs.p_width),
508           inset(dynamic_cast<InsetTableCell *>(cs.inset->clone()))
509 {
510 }
511
512 Tabular::CellData & Tabular::CellData::operator=(CellData cs)
513 {
514         swap(cs);
515         return *this;
516 }
517
518 void Tabular::CellData::swap(CellData & rhs)
519 {
520         std::swap(cellno, rhs.cellno);
521         std::swap(width, rhs.width);
522         std::swap(multicolumn, rhs.multicolumn);
523         std::swap(alignment, rhs.alignment);
524         std::swap(valignment, rhs.valignment);
525         std::swap(top_line, rhs.top_line);
526         std::swap(bottom_line, rhs.bottom_line);
527         std::swap(left_line, rhs.left_line);
528         std::swap(right_line, rhs.right_line);
529         std::swap(usebox, rhs.usebox);
530         std::swap(rotate, rhs.rotate);
531         std::swap(align_special, rhs.align_special);
532         p_width.swap(rhs.p_width);
533         inset.swap(rhs.inset);
534 }
535
536
537 Tabular::RowData::RowData()
538         : ascent(0),
539           descent(0),
540           top_space_default(false),
541           bottom_space_default(false),
542           interline_space_default(false),
543           endhead(false),
544           endfirsthead(false),
545           endfoot(false),
546           endlastfoot(false),
547           newpage(false),
548           caption(false)
549 {}
550
551
552 Tabular::ColumnData::ColumnData()
553         : alignment(LYX_ALIGN_CENTER),
554           valignment(LYX_VALIGN_TOP),
555           width(0)
556 {
557 }
558
559
560 Tabular::ltType::ltType()
561         : topDL(false),
562           bottomDL(false),
563           empty(false)
564 {}
565
566
567 Tabular::Tabular(Buffer & buffer, row_type rows_arg, col_type columns_arg)
568 {
569         init(buffer, rows_arg, columns_arg);
570 }
571
572
573 void Tabular::setBuffer(Buffer & buffer)
574 {
575         buffer_ = &buffer;
576         size_t row_count = row_info.size();
577         size_t column_count = column_info.size();
578         // set silly default lines
579         for (row_type i = 0; i < row_count; ++i)
580                 for (col_type j = 0; j < column_count; ++j)
581                         cell_info[i][j].inset->setBuffer(*buffer_);
582 }
583
584
585 // activates all lines and sets all widths to 0
586 void Tabular::init(Buffer & buf, row_type rows_arg,
587                       col_type columns_arg)
588 {
589         buffer_ = &buf;
590         row_info = row_vector(rows_arg);
591         column_info = column_vector(columns_arg);
592         cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf)));
593         row_info.reserve(10);
594         column_info.reserve(10);
595         cell_info.reserve(100);
596         updateIndexes();
597         is_long_tabular = false;
598         rotate = false;
599         use_booktabs = false;
600         size_t row_count = row_info.size();
601         size_t column_count = column_info.size();
602         // set silly default lines
603         for (row_type i = 0; i < row_count; ++i)
604                 for (col_type j = 0; j < column_count; ++j) {
605                         cell_info[i][j].inset->setBuffer(*buffer_);
606                         cell_info[i][j].top_line = true;
607                         cell_info[i][j].left_line = true;
608                         cell_info[i][j].bottom_line = i == 0 || i == row_count - 1;
609                         cell_info[i][j].right_line = j == column_count - 1;
610                 }
611 }
612
613
614 void Tabular::appendRow(idx_type const cell)
615 {
616         BufferParams const & bp = buffer().params();
617         row_type const row = cellRow(cell);
618
619         row_vector::iterator rit = row_info.begin() + row;
620         row_info.insert(rit, RowData());
621         // now set the values of the row before
622         row_info[row] = row_info[row + 1];
623
624         row_type const nrows = row_info.size();
625         col_type const ncols = column_info.size();
626
627         cell_vvector old(nrows - 1);
628         for (row_type i = 0; i < nrows - 1; ++i)
629                 swap(cell_info[i], old[i]);
630
631         cell_info = cell_vvector(nrows, cell_vector(ncols, CellData(buffer())));
632
633         for (row_type i = 0; i <= row; ++i)
634                 swap(cell_info[i], old[i]);
635         for (row_type i = row + 2; i < nrows; ++i)
636                 swap(cell_info[i], old[i - 1]);
637
638         updateIndexes();
639         for (col_type c = 0; c < ncols; ++c) {
640                 // inherit line settings
641                 idx_type const i = cellIndex(row + 1, c);
642                 idx_type const j = cellIndex(row, c);
643                 setLeftLine(i, leftLine(j));
644                 setRightLine(i, rightLine(j));
645                 setTopLine(i, topLine(j));
646                 if (topLine(j) && bottomLine(j)) {
647                         setBottomLine(i, true);
648                         setBottomLine(j, false);
649                 }
650                 // mark track changes
651                 if (bp.trackChanges)
652                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
653         }
654 }
655
656
657 void Tabular::deleteRow(row_type const row)
658 {
659         // Not allowed to delete last row
660         if (row_info.size() == 1)
661                 return;
662
663         row_info.erase(row_info.begin() + row);
664         cell_info.erase(cell_info.begin() + row);
665         updateIndexes();
666 }
667
668
669 void Tabular::copyRow(row_type const row)
670 {
671         row_info.insert(row_info.begin() + row, row_info[row]);
672         cell_info.insert(cell_info.begin() + row, cell_info[row]);
673
674         if (buffer().params().trackChanges)
675                 for (col_type j = 0; j < column_info.size(); ++j)
676                         cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
677
678         updateIndexes();
679 }
680
681
682 void Tabular::appendColumn(idx_type const cell)
683 {
684         col_type const c = cellColumn(cell);
685         column_vector::iterator cit = column_info.begin() + c + 1;
686         column_info.insert(cit, ColumnData());
687         row_type const nrows = row_info.size();
688         // set the column values of the column before
689         column_info[c + 1] = column_info[c];
690
691         for (row_type r = 0; r < nrows; ++r) {
692                 cell_info[r].insert(cell_info[r].begin() + c + 1, 
693                         CellData(buffer()));
694                 if (cell_info[r][c].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
695                         cell_info[r][c + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
696                 else
697                         cell_info[r][c + 1].multicolumn = cell_info[r][c].multicolumn;
698         }
699         updateIndexes();
700         for (row_type r = 0; r < nrows; ++r) {
701                 // inherit line settings
702                 idx_type const i = cellIndex(r, c + 1);
703                 idx_type const j = cellIndex(r, c);
704                 setBottomLine(i, bottomLine(j));
705                 setTopLine(i, topLine(j));
706                 setLeftLine(i, leftLine(j));
707                 if (rightLine(j) && rightLine(j)) {
708                         setRightLine(i, true);
709                         setRightLine(j, false);
710                 }
711                 //
712                 cellInfo(i).inset->clear();
713                 if (buffer().params().trackChanges)
714                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
715         }
716 }
717
718
719 void Tabular::deleteColumn(col_type const column)
720 {
721         // Not allowed to delete last column
722         if (column_info.size() == 1)
723                 return;
724
725         column_info.erase(column_info.begin() + column);
726         size_t row_count = row_info.size();
727         for (row_type i = 0; i < row_count; ++i) {
728                 // Care about multicolumn cells
729                 if (column + 1 < column_info.size() &&
730                     cell_info[i][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
731                     cell_info[i][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
732                         cell_info[i][column + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
733                 }
734                 cell_info[i].erase(cell_info[i].begin() + column);
735         }
736         updateIndexes();
737 }
738
739
740 void Tabular::copyColumn(col_type const column)
741 {
742         BufferParams const & bp = buffer().params();
743         column_info.insert(column_info.begin() + column, column_info[column]);
744
745         size_t row_count = row_info.size();
746         for (row_type i = 0; i < row_count; ++i)
747                 cell_info[i].insert(cell_info[i].begin() + column, cell_info[i][column]);
748
749         if (bp.trackChanges)
750                 for (row_type i = 0; i < row_count; ++i)
751                         cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
752         updateIndexes();
753 }
754
755
756 void Tabular::updateIndexes()
757 {
758         col_type ncols = column_info.size();
759         row_type nrows = row_info.size();
760         numberofcells = 0;
761         for (row_type row = 0; row < nrows; ++row)
762                 for (col_type column = 0; column < ncols; ++column) {
763                         if (!isPartOfMultiColumn(row, column))
764                                 ++numberofcells;
765                         cell_info[row][column].cellno = numberofcells - 1;
766                 }
767
768         rowofcell.resize(numberofcells);
769         columnofcell.resize(numberofcells);
770         idx_type i = 0;
771         for (row_type row = 0; row < nrows; ++row)
772                 for (col_type column = 0; column < ncols; ++column) {
773                         if (isPartOfMultiColumn(row, column))
774                                 continue;
775                         rowofcell[i] = row;
776                         columnofcell[i] = column;
777                         setFixedWidth(row, column);
778                         ++i;
779                 }
780 }
781
782
783 Tabular::idx_type Tabular::numberOfCellsInRow(idx_type const cell) const
784 {
785         row_type const row = cellRow(cell);
786         idx_type result = 0;
787         for (col_type i = 0; i < column_info.size(); ++i)
788                 if (cell_info[row][i].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
789                         ++result;
790         return result;
791 }
792
793
794 bool Tabular::topLine(idx_type const cell) const
795 {
796         return cellInfo(cell).top_line;
797 }
798
799
800 bool Tabular::bottomLine(idx_type const cell) const
801 {
802         return cellInfo(cell).bottom_line;
803 }
804
805
806 bool Tabular::leftLine(idx_type cell) const
807 {
808         if (use_booktabs)
809                 return false;
810         return cellInfo(cell).left_line;
811 }
812
813
814 bool Tabular::rightLine(idx_type cell) const
815 {
816         if (use_booktabs)
817                 return false;
818         return cellInfo(cell).right_line;
819 }
820
821
822 bool Tabular::topAlreadyDrawn(idx_type cell) const
823 {
824         row_type row = cellRow(cell);
825         if (row == 0)
826                 return false;
827         idx_type i = cellIndex(row - 1, cellColumn(cell));
828         return !rowTopLine(row) && bottomLine(i);
829 }
830
831
832 bool Tabular::leftAlreadyDrawn(idx_type cell) const
833 {
834         col_type col = cellColumn(cell);
835         if (col == 0)
836                 return false;
837         idx_type i = cellIndex(cellRow(cell), col - 1);
838         return rightLine(i) && !leftLine(cell);
839 }
840
841
842 bool Tabular::isLastRow(idx_type cell) const
843 {
844         return cellRow(cell) == row_info.size() - 1;
845 }
846
847
848 int Tabular::getAdditionalHeight(row_type row) const
849 {
850         if (!row || row >= row_info.size())
851                 return 0;
852
853         int const interline_space = row_info[row - 1].interline_space_default ?
854                 default_line_space :
855                 row_info[row - 1].interline_space.inPixels(width());
856         if (rowTopLine(row) && rowBottomLine(row - 1))
857                 return interline_space + WIDTH_OF_LINE;
858         return interline_space;
859 }
860
861
862 int Tabular::getAdditionalWidth(idx_type cell) const
863 {
864         col_type const nextcol = cellColumn(cell) + columnSpan(cell);
865         if (rightLine(cell) 
866                 && nextcol < column_info.size() && leftLine(cellIndex(cellRow(cell), nextcol)))
867                 return WIDTH_OF_LINE;
868         return 0;
869 }
870
871
872 int Tabular::columnWidth(idx_type cell) const
873 {
874         int w = 0;
875         col_type const span = columnSpan(cell);
876         col_type const col = cellColumn(cell);
877         for(col_type c = col; c < col + span ; ++c)
878                 w += column_info[c].width;
879         return w;
880 }
881
882
883 bool Tabular::updateColumnWidths()
884 {
885         col_type const ncols = column_info.size();
886         row_type const nrows = row_info.size();
887         bool update = false;
888         // for each col get max of single col cells
889         for(col_type c = 0; c < ncols; ++c) {
890                 int new_width = 0;
891                 for(row_type r = 0; r < nrows; ++r) {
892                         idx_type const i = cellIndex(r, c);
893                         if (columnSpan(i) == 1)
894                                 new_width = max(new_width, cellInfo(i).width);
895                 }
896
897                 if (column_info[c].width != new_width) {
898                         column_info[c].width = new_width;
899                         update = true;
900                 }
901         }
902         // update col widths to fit merged cells
903         for(col_type c = 0; c < ncols; ++c)
904                 for(row_type r = 0; r < nrows; ++r) {
905                         idx_type const i = cellIndex(r, c);
906                         int const span = columnSpan(i);
907                         if (span == 1 || c > cellColumn(i))
908                                 continue;
909
910                         int old_width = 0;
911                         for(col_type j = c; j < c + span ; ++j)
912                                 old_width += column_info[j].width;
913
914                         if (cellInfo(i).width > old_width) {
915                                 column_info[c + span - 1].width += cellInfo(i).width - old_width;
916                                 update = true;
917                         }
918                 }
919
920         return update;
921 }
922
923
924 int Tabular::width() const
925 {
926         col_type const ncols = column_info.size();
927         int width = 0;
928         for (col_type i = 0; i < ncols; ++i)
929                 width += column_info[i].width;
930         return width;
931 }
932
933
934 void Tabular::setCellWidth(idx_type cell, int new_width)
935 {
936         cellInfo(cell).width = new_width + 2 * WIDTH_OF_LINE 
937                 + getAdditionalWidth(cell);
938 }
939
940
941 void Tabular::setAlignment(idx_type cell, LyXAlignment align,
942                               bool onlycolumn)
943 {
944         if (!isMultiColumn(cell) || onlycolumn)
945                 column_info[cellColumn(cell)].alignment = align;
946         if (!onlycolumn)
947                 cellInfo(cell).alignment = align;
948 }
949
950
951 void Tabular::setVAlignment(idx_type cell, VAlignment align,
952                                bool onlycolumn)
953 {
954         if (!isMultiColumn(cell) || onlycolumn)
955                 column_info[cellColumn(cell)].valignment = align;
956         if (!onlycolumn)
957                 cellInfo(cell).valignment = align;
958 }
959
960
961 namespace {
962
963 /**
964  * Allow line and paragraph breaks for fixed width cells or disallow them,
965  * merge cell paragraphs and reset layout to standard for variable width
966  * cells.
967  */
968 void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
969 {
970         inset->setAutoBreakRows(fixedWidth);
971         inset->toggleFixedWidth(fixedWidth);
972         if (fixedWidth)
973                 return;
974
975         // merge all paragraphs to one
976         BufferParams const & bp = cur.bv().buffer().params();
977         while (inset->paragraphs().size() > 1)
978                 mergeParagraph(bp, inset->paragraphs(), 0);
979
980         // reset layout
981         cur.push(*inset);
982         // undo information has already been recorded
983         inset->getText(0)->setLayout(cur.bv().buffer(), 0, cur.lastpit() + 1,
984                         bp.documentClass().emptyLayoutName());
985         cur.pop();
986 }
987
988 }
989
990
991 void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
992                 Length const & width)
993 {
994         col_type const j = cellColumn(cell);
995
996         column_info[j].p_width = width;
997         for (row_type i = 0; i < row_info.size(); ++i) {
998                 idx_type const cell = cellIndex(i, j);
999                 // because of multicolumns
1000                 toggleFixedWidth(cur, cellInset(cell).get(),
1001                                  !getPWidth(cell).zero());
1002         }
1003         // cur paragraph can become invalid after paragraphs were merged
1004         if (cur.pit() > cur.lastpit())
1005                 cur.pit() = cur.lastpit();
1006         // cur position can become invalid after newlines were removed
1007         if (cur.pos() > cur.lastpos())
1008                 cur.pos() = cur.lastpos();
1009 }
1010
1011
1012 bool Tabular::setFixedWidth(row_type r, col_type c)
1013 {
1014         if (!column_info[c].p_width.zero() ||
1015                                 (cell_info[r][c].multicolumn != CELL_NORMAL && 
1016                                 !cell_info[r][c].p_width.zero())) {
1017                 cell_info[r][c].inset->toggleFixedWidth(true);
1018                 return true;
1019         }
1020         return false;
1021 }
1022
1023
1024 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
1025                 Length const & width)
1026 {
1027         if (!isMultiColumn(cell))
1028                 return false;
1029
1030         cellInfo(cell).p_width = width;
1031         toggleFixedWidth(cur, cellInset(cell).get(), !width.zero());
1032         // cur paragraph can become invalid after paragraphs were merged
1033         if (cur.pit() > cur.lastpit())
1034                 cur.pit() = cur.lastpit();
1035         // cur position can become invalid after newlines were removed
1036         if (cur.pos() > cur.lastpos())
1037                 cur.pos() = cur.lastpos();
1038         return true;
1039 }
1040
1041
1042 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
1043                                  Tabular::Feature what)
1044 {
1045         if (what == SET_SPECIAL_MULTI)
1046                 cellInfo(cell).align_special = special;
1047         else
1048                 column_info[cellColumn(cell)].align_special = special;
1049 }
1050
1051
1052 void Tabular::setAllLines(idx_type cell, bool line)
1053 {
1054         setTopLine(cell, line);
1055         setBottomLine(cell, line);
1056         setRightLine(cell, line);
1057         setLeftLine(cell, line);
1058 }
1059
1060
1061 void Tabular::setTopLine(idx_type i, bool line)
1062 {
1063         cellInfo(i).top_line = line;
1064 }
1065
1066
1067 void Tabular::setBottomLine(idx_type i, bool line)
1068 {
1069         cellInfo(i).bottom_line = line;
1070 }
1071
1072
1073 void Tabular::setLeftLine(idx_type cell, bool line)
1074 {
1075         cellInfo(cell).left_line = line;
1076 }
1077
1078
1079 void Tabular::setRightLine(idx_type cell, bool line)
1080 {
1081         cellInfo(cell).right_line = line;
1082 }
1083
1084 bool Tabular::rowTopLine(row_type r) const
1085 {
1086         idx_type i0 = getFirstCellInRow(r);
1087         idx_type i1 = getLastCellInRow(r);
1088         bool all_rows_set = true;
1089         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1090                 all_rows_set = cellInfo(j).top_line;
1091         return all_rows_set;
1092 }
1093
1094
1095 bool Tabular::rowBottomLine(row_type r) const
1096 {
1097         idx_type i0 = getFirstCellInRow(r);
1098         idx_type i1 = getLastCellInRow(r);
1099         bool all_rows_set = true;
1100         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1101                 all_rows_set = cellInfo(j).bottom_line;
1102         return all_rows_set;
1103 }
1104
1105
1106 bool Tabular::columnLeftLine(col_type c) const
1107 {
1108         if (use_booktabs)
1109                 return false;
1110
1111         int nrows_left = 0;
1112         int total = 0;
1113         row_type const nrows = row_info.size();
1114         for (row_type r = 0; r < nrows; ++r) {
1115                 idx_type i = cellIndex(r, c);
1116                 if (c == cellColumn(i)) {
1117                         ++total;
1118                         bool right = c > 0 && cellInfo(cellIndex(r, c - 1)).right_line;
1119                         if (cellInfo(i).left_line || right)
1120                                 ++nrows_left;
1121                 }
1122         }
1123         return 2 * nrows_left >= total;
1124 }
1125
1126
1127 bool Tabular::columnRightLine(col_type c) const
1128 {
1129         if (use_booktabs)
1130                 return false;
1131
1132         int nrows_right = 0;
1133         int total = 0;
1134         row_type const nrows = row_info.size();
1135         for (row_type r = 0; r < nrows; ++r) {
1136                 idx_type i = cellIndex(r, c);
1137                 if (c == cellColumn(i) + columnSpan(i) - 1) {
1138                         ++total;
1139                         bool left = c + 1 < column_info.size() 
1140                                 && cellInfo(cellIndex(r, c + 1)).left_line
1141                                 || c + 1 == column_info.size();
1142                         if (cellInfo(i).right_line && left)
1143                                 ++nrows_right;
1144                 }
1145         }
1146         return 2 * nrows_right >= total;
1147 }
1148
1149
1150 LyXAlignment Tabular::getAlignment(idx_type cell, bool onlycolumn) const
1151 {
1152         if (!onlycolumn && isMultiColumn(cell))
1153                 return cellInfo(cell).alignment;
1154         return column_info[cellColumn(cell)].alignment;
1155 }
1156
1157
1158 Tabular::VAlignment
1159 Tabular::getVAlignment(idx_type cell, bool onlycolumn) const
1160 {
1161         if (!onlycolumn && isMultiColumn(cell))
1162                 return cellInfo(cell).valignment;
1163         return column_info[cellColumn(cell)].valignment;
1164 }
1165
1166
1167 Length const Tabular::getPWidth(idx_type cell) const
1168 {
1169         if (isMultiColumn(cell))
1170                 return cellInfo(cell).p_width;
1171         return column_info[cellColumn(cell)].p_width;
1172 }
1173
1174
1175 int Tabular::cellWidth(idx_type cell) const
1176 {
1177         return cellInfo(cell).width;
1178 }
1179
1180
1181 int Tabular::getBeginningOfTextInCell(idx_type cell) const
1182 {
1183         int x = 0;
1184
1185         switch (getAlignment(cell)) {
1186         case LYX_ALIGN_CENTER:
1187                 x += (columnWidth(cell) - cellWidth(cell)) / 2;
1188                 break;
1189         case LYX_ALIGN_RIGHT:
1190                 x += columnWidth(cell) - cellWidth(cell);
1191                 // + getAdditionalWidth(cell);
1192                 break;
1193         default:
1194                 // LYX_ALIGN_LEFT: nothing :-)
1195                 break;
1196         }
1197
1198         // the LaTeX Way :-(
1199         x += WIDTH_OF_LINE;
1200         return x;
1201 }
1202
1203
1204 bool Tabular::isFirstCellInRow(idx_type cell) const
1205 {
1206         return cellColumn(cell) == 0;
1207 }
1208
1209
1210 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
1211 {
1212         if (row > row_info.size() - 1)
1213                 row = row_info.size() - 1;
1214         return cell_info[row][0].cellno;
1215 }
1216
1217
1218 bool Tabular::isLastCellInRow(idx_type cell) const
1219 {
1220         return cellRightColumn(cell) == column_info.size() - 1;
1221 }
1222
1223
1224 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
1225 {
1226         if (row > row_info.size() - 1)
1227                 row = row_info.size() - 1;
1228         return cell_info[row][column_info.size() - 1].cellno;
1229 }
1230
1231
1232 Tabular::row_type Tabular::cellRow(idx_type cell) const
1233 {
1234         if (cell >= numberofcells)
1235                 return row_info.size() - 1;
1236         if (cell == npos)
1237                 return 0;
1238         return rowofcell[cell];
1239 }
1240
1241
1242 Tabular::col_type Tabular::cellColumn(idx_type cell) const
1243 {
1244         if (cell >= numberofcells)
1245                 return column_info.size() - 1;
1246         if (cell == npos)
1247                 return 0;       
1248         return columnofcell[cell];
1249 }
1250
1251
1252 Tabular::col_type Tabular::cellRightColumn(idx_type cell) const
1253 {
1254         row_type const row = cellRow(cell);
1255         col_type column = cellColumn(cell);
1256         while (column < column_info.size() - 1 &&
1257                    cell_info[row][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN)
1258                 ++column;
1259         return column;
1260 }
1261
1262
1263 void Tabular::write(ostream & os) const
1264 {
1265         // header line
1266         os << "<lyxtabular"
1267            << write_attribute("version", 3)
1268            << write_attribute("rows", row_info.size())
1269            << write_attribute("columns", column_info.size())
1270            << ">\n";
1271         // global longtable options
1272         os << "<features"
1273            << write_attribute("rotate", rotate)
1274            << write_attribute("booktabs", use_booktabs)
1275            << write_attribute("islongtable", is_long_tabular)
1276            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1277            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1278            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1279            << write_attribute("headTopDL", endhead.topDL)
1280            << write_attribute("headBottomDL", endhead.bottomDL)
1281            << write_attribute("footTopDL", endfoot.topDL)
1282            << write_attribute("footBottomDL", endfoot.bottomDL)
1283            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1284            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1285            << write_attribute("lastFootEmpty", endlastfoot.empty)
1286            << ">\n";
1287         for (col_type j = 0; j < column_info.size(); ++j) {
1288                 os << "<column"
1289                    << write_attribute("alignment", column_info[j].alignment)
1290                    << write_attribute("valignment", column_info[j].valignment)
1291                    << write_attribute("width", column_info[j].p_width.asString())
1292                    << write_attribute("special", column_info[j].align_special)
1293                    << ">\n";
1294         }
1295         for (row_type i = 0; i < row_info.size(); ++i) {
1296                 static const string def("default");
1297                 os << "<row";
1298                 if (row_info[i].top_space_default)
1299                         os << write_attribute("topspace", def);
1300                 else
1301                         os << write_attribute("topspace", row_info[i].top_space);
1302                 if (row_info[i].bottom_space_default)
1303                         os << write_attribute("bottomspace", def);
1304                 else
1305                         os << write_attribute("bottomspace", row_info[i].bottom_space);
1306                 if (row_info[i].interline_space_default)
1307                         os << write_attribute("interlinespace", def);
1308                 else
1309                         os << write_attribute("interlinespace", row_info[i].interline_space);
1310                 os << write_attribute("endhead", row_info[i].endhead)
1311                    << write_attribute("endfirsthead", row_info[i].endfirsthead)
1312                    << write_attribute("endfoot", row_info[i].endfoot)
1313                    << write_attribute("endlastfoot", row_info[i].endlastfoot)
1314                    << write_attribute("newpage", row_info[i].newpage)
1315                    << write_attribute("caption", row_info[i].caption)
1316                    << ">\n";
1317                 for (col_type j = 0; j < column_info.size(); ++j) {
1318                         os << "<cell"
1319                            << write_attribute("multicolumn", cell_info[i][j].multicolumn)
1320                            << write_attribute("alignment", cell_info[i][j].alignment)
1321                            << write_attribute("valignment", cell_info[i][j].valignment)
1322                            << write_attribute("topline", cell_info[i][j].top_line)
1323                            << write_attribute("bottomline", cell_info[i][j].bottom_line)
1324                            << write_attribute("leftline", cell_info[i][j].left_line)
1325                            << write_attribute("rightline", cell_info[i][j].right_line)
1326                            << write_attribute("rotate", cell_info[i][j].rotate)
1327                            << write_attribute("usebox", cell_info[i][j].usebox)
1328                            << write_attribute("width", cell_info[i][j].p_width)
1329                            << write_attribute("special", cell_info[i][j].align_special)
1330                            << ">\n";
1331                         os << "\\begin_inset ";
1332                         cell_info[i][j].inset->write(os);
1333                         os << "\n\\end_inset\n"
1334                            << "</cell>\n";
1335                 }
1336                 os << "</row>\n";
1337         }
1338         os << "</lyxtabular>\n";
1339 }
1340
1341
1342 void Tabular::read(Lexer & lex)
1343 {
1344         string line;
1345         istream & is = lex.getStream();
1346
1347         l_getline(is, line);
1348         if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
1349                 LASSERT(false, /**/);
1350                 return;
1351         }
1352
1353         int version;
1354         if (!getTokenValue(line, "version", version))
1355                 return;
1356         LASSERT(version >= 2, /**/);
1357
1358         int rows_arg;
1359         if (!getTokenValue(line, "rows", rows_arg))
1360                 return;
1361         int columns_arg;
1362         if (!getTokenValue(line, "columns", columns_arg))
1363                 return;
1364         init(buffer(), rows_arg, columns_arg);
1365         l_getline(is, line);
1366         if (!prefixIs(line, "<features")) {
1367                 lyxerr << "Wrong tabular format (expected <features ...> got"
1368                        << line << ')' << endl;
1369                 return;
1370         }
1371         getTokenValue(line, "rotate", rotate);
1372         getTokenValue(line, "booktabs", use_booktabs);
1373         getTokenValue(line, "islongtable", is_long_tabular);
1374         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1375         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1376         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1377         getTokenValue(line, "headTopDL", endhead.topDL);
1378         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1379         getTokenValue(line, "footTopDL", endfoot.topDL);
1380         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1381         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1382         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1383         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1384
1385         for (col_type j = 0; j < column_info.size(); ++j) {
1386                 l_getline(is,line);
1387                 if (!prefixIs(line,"<column")) {
1388                         lyxerr << "Wrong tabular format (expected <column ...> got"
1389                                << line << ')' << endl;
1390                         return;
1391                 }
1392                 getTokenValue(line, "alignment", column_info[j].alignment);
1393                 getTokenValue(line, "valignment", column_info[j].valignment);
1394                 getTokenValue(line, "width", column_info[j].p_width);
1395                 getTokenValue(line, "special", column_info[j].align_special);
1396         }
1397
1398         for (row_type i = 0; i < row_info.size(); ++i) {
1399                 l_getline(is, line);
1400                 if (!prefixIs(line, "<row")) {
1401                         lyxerr << "Wrong tabular format (expected <row ...> got"
1402                                << line << ')' << endl;
1403                         return;
1404                 }
1405                 getTokenValue(line, "topspace", row_info[i].top_space,
1406                               row_info[i].top_space_default);
1407                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1408                               row_info[i].bottom_space_default);
1409                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1410                               row_info[i].interline_space_default);
1411                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1412                 getTokenValue(line, "endhead", row_info[i].endhead);
1413                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1414                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1415                 getTokenValue(line, "newpage", row_info[i].newpage);
1416                 getTokenValue(line, "caption", row_info[i].caption);
1417                 for (col_type j = 0; j < column_info.size(); ++j) {
1418                         l_getline(is, line);
1419                         if (!prefixIs(line, "<cell")) {
1420                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1421                                        << line << ')' << endl;
1422                                 return;
1423                         }
1424                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1425                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1426                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1427                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1428                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1429                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1430                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1431                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1432                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1433                         getTokenValue(line, "width", cell_info[i][j].p_width);
1434                         setFixedWidth(i,j);
1435                         getTokenValue(line, "special", cell_info[i][j].align_special);
1436                         l_getline(is, line);
1437                         if (prefixIs(line, "\\begin_inset")) {
1438                                 cell_info[i][j].inset->setBuffer(*buffer_);
1439                                 cell_info[i][j].inset->read(lex);
1440                                 l_getline(is, line);
1441                         }
1442                         if (!prefixIs(line, "</cell>")) {
1443                                 lyxerr << "Wrong tabular format (expected </cell> got"
1444                                        << line << ')' << endl;
1445                                 return;
1446                         }
1447                 }
1448                 l_getline(is, line);
1449                 if (!prefixIs(line, "</row>")) {
1450                         lyxerr << "Wrong tabular format (expected </row> got"
1451                                << line << ')' << endl;
1452                         return;
1453                 }
1454         }
1455         while (!prefixIs(line, "</lyxtabular>")) {
1456                 l_getline(is, line);
1457         }
1458         updateIndexes();
1459 }
1460
1461
1462 bool Tabular::isMultiColumn(idx_type cell) const
1463 {
1464         return cellInfo(cell).multicolumn != CELL_NORMAL;
1465 }
1466
1467
1468 bool Tabular::isMultiColumnReal(idx_type cell) const
1469 {
1470         return cellColumn(cell) != cellRightColumn(cell) &&
1471                         cellInfo(cell).multicolumn != CELL_NORMAL;
1472 }
1473
1474
1475 Tabular::CellData & Tabular::cellInfo(idx_type cell) const
1476 {
1477         return cell_info[cellRow(cell)][cellColumn(cell)];
1478 }
1479
1480
1481 void Tabular::setMultiColumn(idx_type cell, idx_type number)
1482 {
1483         CellData & cs = cellInfo(cell);
1484         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1485         cs.alignment = column_info[cellColumn(cell)].alignment;
1486         setRightLine(cell, rightLine(cell + number - 1));
1487         for (idx_type i = 1; i < number; ++i) {
1488                 CellData & cs1 = cellInfo(cell + i);
1489                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1490                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1491                 cs1.inset->clear();
1492         }
1493         updateIndexes();
1494 }
1495
1496
1497 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
1498 {
1499         row_type const row = cellRow(cell);
1500         col_type const ncols = column_info.size();
1501         idx_type result = 1;
1502         col_type column = cellColumn(cell) + 1;
1503         while (column < ncols && isPartOfMultiColumn(row, column)) {
1504                 ++result;
1505                 ++column;
1506         }
1507         return result;
1508 }
1509
1510
1511 Tabular::idx_type Tabular::unsetMultiColumn(idx_type cell)
1512 {
1513         row_type const row = cellRow(cell);
1514         col_type column = cellColumn(cell);
1515
1516         idx_type result = 0;
1517
1518         if (cell_info[row][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN) {
1519                 cell_info[row][column].multicolumn = CELL_NORMAL;
1520                 ++column;
1521                 while (column < column_info.size() &&
1522                            cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
1523                 {
1524                         cell_info[row][column].multicolumn = CELL_NORMAL;
1525                         ++column;
1526                         ++result;
1527                 }
1528         }
1529         updateIndexes();
1530         return result;
1531 }
1532
1533
1534 void Tabular::setRotateCell(idx_type cell, bool flag)
1535 {
1536         cellInfo(cell).rotate = flag;
1537 }
1538
1539
1540 bool Tabular::getRotateCell(idx_type cell) const
1541 {
1542         return cellInfo(cell).rotate;
1543 }
1544
1545
1546 bool Tabular::needRotating() const
1547 {
1548         if (rotate)
1549                 return true;
1550         for (row_type i = 0; i < row_info.size(); ++i)
1551                 for (col_type j = 0; j < column_info.size(); ++j)
1552                         if (cell_info[i][j].rotate)
1553                                 return true;
1554         return false;
1555 }
1556
1557
1558 bool Tabular::isLastCell(idx_type cell) const
1559 {
1560         if (cell + 1 < numberofcells)
1561                 return false;
1562         return true;
1563 }
1564
1565
1566 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
1567 {
1568         if (cellRow(cell) > 0)
1569                 return cell_info[cellRow(cell)-1][cellColumn(cell)].cellno;
1570         return cell;
1571 }
1572
1573
1574 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
1575 {
1576         if (cellRow(cell) + 1 < row_info.size())
1577                 return cell_info[cellRow(cell)+1][cellColumn(cell)].cellno;
1578         return cell;
1579 }
1580
1581
1582 Tabular::idx_type Tabular::cellIndex(row_type row,
1583                                                col_type column) const
1584 {
1585         BOOST_ASSERT(column != npos && column < column_info.size()
1586                 && row != npos && row < row_info.size());
1587         return cell_info[row][column].cellno;
1588 }
1589
1590
1591 void Tabular::setUsebox(idx_type cell, BoxType type)
1592 {
1593         cellInfo(cell).usebox = type;
1594 }
1595
1596
1597 // FIXME: Remove this routine because we cannot insert \parboxes when the user
1598 // adds line breaks, see bug 4886.
1599 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
1600 {
1601         if ((!column_info[cellColumn(cell)].p_width.zero() && !isMultiColumn(cell)) ||
1602                 (isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
1603                 return BOX_NONE;
1604         if (cellInfo(cell).usebox > 1)
1605                 return cellInfo(cell).usebox;
1606         return useParbox(cell);
1607 }
1608
1609
1610 ///
1611 //  This are functions used for the longtable support
1612 ///
1613 void Tabular::setLTHead(row_type row, bool flag, ltType const & hd,
1614                            bool first)
1615 {
1616         if (first) {
1617                 endfirsthead = hd;
1618                 if (hd.set)
1619                         row_info[row].endfirsthead = flag;
1620         } else {
1621                 endhead = hd;
1622                 if (hd.set)
1623                         row_info[row].endhead = flag;
1624         }
1625 }
1626
1627
1628 bool Tabular::getRowOfLTHead(row_type row, ltType & hd) const
1629 {
1630         hd = endhead;
1631         hd.set = haveLTHead();
1632         return row_info[row].endhead;
1633 }
1634
1635
1636 bool Tabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1637 {
1638         hd = endfirsthead;
1639         hd.set = haveLTFirstHead();
1640         return row_info[row].endfirsthead;
1641 }
1642
1643
1644 void Tabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1645                            bool last)
1646 {
1647         if (last) {
1648                 endlastfoot = fd;
1649                 if (fd.set)
1650                         row_info[row].endlastfoot = flag;
1651         } else {
1652                 endfoot = fd;
1653                 if (fd.set)
1654                         row_info[row].endfoot = flag;
1655         }
1656 }
1657
1658
1659 bool Tabular::getRowOfLTFoot(row_type row, ltType & fd) const
1660 {
1661         fd = endfoot;
1662         fd.set = haveLTFoot();
1663         return row_info[row].endfoot;
1664 }
1665
1666
1667 bool Tabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1668 {
1669         fd = endlastfoot;
1670         fd.set = haveLTLastFoot();
1671         return row_info[row].endlastfoot;
1672 }
1673
1674
1675 void Tabular::setLTNewPage(row_type row, bool what)
1676 {
1677         row_info[row].newpage = what;
1678 }
1679
1680
1681 bool Tabular::getLTNewPage(row_type row) const
1682 {
1683         return row_info[row].newpage;
1684 }
1685
1686
1687 bool Tabular::haveLTHead() const
1688 {
1689         for (row_type i = 0; i < row_info.size(); ++i)
1690                 if (row_info[i].endhead)
1691                         return true;
1692         return false;
1693 }
1694
1695
1696 bool Tabular::haveLTFirstHead() const
1697 {
1698         if (endfirsthead.empty)
1699                 return false;
1700         for (row_type i = 0; i < row_info.size(); ++i)
1701                 if (row_info[i].endfirsthead)
1702                         return true;
1703         return false;
1704 }
1705
1706
1707 bool Tabular::haveLTFoot() const
1708 {
1709         for (row_type i = 0; i < row_info.size(); ++i)
1710                 if (row_info[i].endfoot)
1711                         return true;
1712         return false;
1713 }
1714
1715
1716 bool Tabular::haveLTLastFoot() const
1717 {
1718         if (endlastfoot.empty)
1719                 return false;
1720         for (row_type i = 0; i < row_info.size(); ++i)
1721                 if (row_info[i].endlastfoot)
1722                         return true;
1723         return false;
1724 }
1725
1726
1727 Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
1728 {
1729         idx_type i = getFirstCellInRow(row);
1730         if (what) {
1731                 setMultiColumn(i, column_info.size());
1732                 setTopLine(i, false);
1733                 setBottomLine(i, false);
1734                 setLeftLine(i, false);
1735                 setRightLine(i, false);
1736         } else
1737                 unsetMultiColumn(i);
1738         row_info[row].caption = what;
1739         return i;
1740 }
1741
1742
1743 bool Tabular::ltCaption(row_type row) const
1744 {
1745         return row_info[row].caption;
1746 }
1747
1748
1749 // end longtable support functions
1750
1751 void Tabular::setRowAscent(row_type row, int height)
1752 {
1753         if (row >= row_info.size() || row_info[row].ascent == height)
1754                 return;
1755         row_info[row].ascent = height;
1756 }
1757
1758
1759 void Tabular::setRowDescent(row_type row, int height)
1760 {
1761         if (row >= row_info.size() || row_info[row].descent == height)
1762                 return;
1763         row_info[row].descent = height;
1764 }
1765
1766
1767 int Tabular::rowAscent(row_type row) const
1768 {
1769         if (row >= row_info.size())
1770                 return 0;
1771         return row_info[row].ascent;
1772 }
1773
1774
1775 int Tabular::rowDescent(row_type row) const
1776 {
1777         LASSERT(row < row_info.size(), /**/);
1778         return row_info[row].descent;
1779 }
1780
1781
1782 int Tabular::height() const
1783 {
1784         int height = 0;
1785         for (row_type row = 0; row < row_info.size(); ++row)
1786                 height += rowAscent(row) + rowDescent(row) +
1787                         getAdditionalHeight(row);
1788         return height;
1789 }
1790
1791
1792 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
1793 {
1794         LASSERT(row < row_info.size(), /**/);
1795         LASSERT(column < column_info.size(), /**/);
1796         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
1797 }
1798
1799
1800 int Tabular::TeXTopHLine(odocstream & os, row_type row) const
1801 {
1802         // FIXME: assert or return 0 as in TeXBottomHLine()?
1803         LASSERT(row != npos, /**/);
1804         LASSERT(row < row_info.size(), /**/);
1805
1806         idx_type const fcell = getFirstCellInRow(row);
1807         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1808         idx_type tmp = 0;
1809
1810         for (idx_type i = fcell; i < n; ++i) {
1811                 if (topLine(i))
1812                         ++tmp;
1813         }
1814         if (use_booktabs && row == 0) {
1815                 if (topLine(fcell))
1816                         os << "\\toprule ";
1817         } else if (tmp == n - fcell) {
1818                 os << (use_booktabs ? "\\midrule " : "\\hline ");
1819         } else if (tmp) {
1820                 for (idx_type i = fcell; i < n; ++i) {
1821                         if (topLine(i)) {
1822                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1823                                    << cellColumn(i) + 1
1824                                    << '-'
1825                                    << cellRightColumn(i) + 1
1826                                    << "} ";
1827                         }
1828                 }
1829         } else {
1830                 return 0;
1831         }
1832         os << "\n";
1833         return 1;
1834 }
1835
1836
1837 int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
1838 {
1839         // FIXME: return 0 or assert as in TeXTopHLine()?
1840         if (row == npos || row >= row_info.size())
1841                 return 0;
1842
1843         idx_type const fcell = getFirstCellInRow(row);
1844         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1845         idx_type tmp = 0;
1846
1847         for (idx_type i = fcell; i < n; ++i) {
1848                 if (bottomLine(i))
1849                         ++tmp;
1850         }
1851         if (use_booktabs && row == row_info.size() - 1) {
1852                 if (bottomLine(fcell))
1853                         os << "\\bottomrule";
1854         } else if (tmp == n - fcell) {
1855                 os << (use_booktabs ? "\\midrule" : "\\hline");
1856         } else if (tmp) {
1857                 for (idx_type i = fcell; i < n; ++i) {
1858                         if (bottomLine(i)) {
1859                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1860                                    << cellColumn(i) + 1
1861                                    << '-'
1862                                    << cellRightColumn(i) + 1
1863                                    << "} ";
1864                         }
1865                 }
1866         } else {
1867                 return 0;
1868         }
1869         os << "\n";
1870         return 1;
1871 }
1872
1873
1874 int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol) const
1875 {
1876         int ret = 0;
1877         row_type const r = cellRow(cell);
1878         if (is_long_tabular && row_info[r].caption)
1879                 return ret;
1880
1881         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
1882         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
1883         // figure out how to set the lines
1884         // we always set double lines to the right of the cell
1885         col_type const c = cellColumn(cell);
1886         col_type const nextcol = c + columnSpan(cell);
1887         bool colright = columnRightLine(c);
1888         bool colleft = columnLeftLine(c);
1889         bool nextcolleft = nextcol < column_info.size() && columnLeftLine(nextcol);
1890         bool nextcellleft = nextcol < column_info.size() 
1891                 && leftLine(cellIndex(r, nextcol));
1892         bool coldouble = colright && nextcolleft;
1893         bool celldouble = rightLine(cell) && nextcellleft;
1894         ismulticol = isMultiColumn(cell) 
1895                 || (c == 0 && colleft != leftLine(cell))
1896                 || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
1897                 || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
1898                 || (coldouble != celldouble);
1899         if (ismulticol) {
1900                 os << "\\multicolumn{" << columnSpan(cell) << "}{";
1901                 if (c ==0 && leftLine(cell))
1902                         os << '|';
1903                 if (!cellInfo(cell).align_special.empty()) {
1904                         os << cellInfo(cell).align_special;
1905                 } else {
1906                         if (!getPWidth(cell).zero()) {
1907                                 switch (valign) {
1908                                 case LYX_VALIGN_TOP:
1909                                         os << 'p';
1910                                         break;
1911                                 case LYX_VALIGN_MIDDLE:
1912                                         os << 'm';
1913                                         break;
1914                                 case LYX_VALIGN_BOTTOM:
1915                                         os << 'b';
1916                                         break;
1917                                 }
1918                                 os << '{'
1919                                    << from_ascii(getPWidth(cell).asLatexString())
1920                                    << '}';
1921                         } else {
1922                                 switch (align) {
1923                                 case LYX_ALIGN_LEFT:
1924                                         os << 'l';
1925                                         break;
1926                                 case LYX_ALIGN_RIGHT:
1927                                         os << 'r';
1928                                         break;
1929                                 default:
1930                                         os << 'c';
1931                                         break;
1932                                 }
1933                         } // end if else !getPWidth
1934                 } // end if else !cellinfo_of_cell
1935                 if (rightLine(cell) || nextcellleft)
1936                         os << '|';
1937                 if (celldouble)
1938                         // add extra vertical line if we want a double one
1939                         os << '|';
1940                 os << "}{";
1941                 }
1942         if (getRotateCell(cell)) {
1943                 os << "\\begin{sideways}\n";
1944                 ++ret;
1945         }
1946         if (getUsebox(cell) == BOX_PARBOX) {
1947                 os << "\\parbox[";
1948                 switch (valign) {
1949                 case LYX_VALIGN_TOP:
1950                         os << 't';
1951                         break;
1952                 case LYX_VALIGN_MIDDLE:
1953                         os << 'c';
1954                         break;
1955                 case LYX_VALIGN_BOTTOM:
1956                         os << 'b';
1957                         break;
1958                 }
1959                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
1960                    << "}{";
1961         } else if (getUsebox(cell) == BOX_MINIPAGE) {
1962                 os << "\\begin{minipage}[";
1963                 switch (valign) {
1964                 case LYX_VALIGN_TOP:
1965                         os << 't';
1966                         break;
1967                 case LYX_VALIGN_MIDDLE:
1968                         os << 'm';
1969                         break;
1970                 case LYX_VALIGN_BOTTOM:
1971                         os << 'b';
1972                         break;
1973                 }
1974                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
1975                    << "}\n";
1976                 ++ret;
1977         }
1978         return ret;
1979 }
1980
1981
1982 int Tabular::TeXCellPostamble(odocstream & os, idx_type cell, bool ismulticol) const
1983 {
1984         int ret = 0;
1985         row_type const r = cellRow(cell);
1986         if (is_long_tabular && row_info[r].caption)
1987                 return ret;
1988
1989         // usual cells
1990         if (getUsebox(cell) == BOX_PARBOX)
1991                 os << '}';
1992         else if (getUsebox(cell) == BOX_MINIPAGE) {
1993                 os << "%\n\\end{minipage}";
1994                 ret += 2;
1995         }
1996         if (getRotateCell(cell)) {
1997                 os << "%\n\\end{sideways}";
1998                 ++ret;
1999         }
2000         if (ismulticol) {
2001                 os << '}';
2002         }
2003         return ret;
2004 }
2005
2006
2007 int Tabular::TeXLongtableHeaderFooter(odocstream & os,
2008                                          OutputParams const & runparams) const
2009 {
2010         if (!is_long_tabular)
2011                 return 0;
2012
2013         int ret = 0;
2014         // output header info
2015         if (haveLTHead()) {
2016                 if (endhead.topDL) {
2017                         os << "\\hline\n";
2018                         ++ret;
2019                 }
2020                 for (row_type i = 0; i < row_info.size(); ++i) {
2021                         if (row_info[i].endhead) {
2022                                 ret += TeXRow(os, i, runparams);
2023                         }
2024                 }
2025                 if (endhead.bottomDL) {
2026                         os << "\\hline\n";
2027                         ++ret;
2028                 }
2029                 os << "\\endhead\n";
2030                 ++ret;
2031                 if (endfirsthead.empty) {
2032                         os << "\\endfirsthead\n";
2033                         ++ret;
2034                 }
2035         }
2036         // output firstheader info
2037         if (haveLTFirstHead()) {
2038                 if (endfirsthead.topDL) {
2039                         os << "\\hline\n";
2040                         ++ret;
2041                 }
2042                 for (row_type i = 0; i < row_info.size(); ++i) {
2043                         if (row_info[i].endfirsthead) {
2044                                 ret += TeXRow(os, i, runparams);
2045                         }
2046                 }
2047                 if (endfirsthead.bottomDL) {
2048                         os << "\\hline\n";
2049                         ++ret;
2050                 }
2051                 os << "\\endfirsthead\n";
2052                 ++ret;
2053         }
2054         // output footer info
2055         if (haveLTFoot()) {
2056                 if (endfoot.topDL) {
2057                         os << "\\hline\n";
2058                         ++ret;
2059                 }
2060                 for (row_type i = 0; i < row_info.size(); ++i) {
2061                         if (row_info[i].endfoot) {
2062                                 ret += TeXRow(os, i, runparams);
2063                         }
2064                 }
2065                 if (endfoot.bottomDL) {
2066                         os << "\\hline\n";
2067                         ++ret;
2068                 }
2069                 os << "\\endfoot\n";
2070                 ++ret;
2071                 if (endlastfoot.empty) {
2072                         os << "\\endlastfoot\n";
2073                         ++ret;
2074                 }
2075         }
2076         // output lastfooter info
2077         if (haveLTLastFoot()) {
2078                 if (endlastfoot.topDL) {
2079                         os << "\\hline\n";
2080                         ++ret;
2081                 }
2082                 for (row_type i = 0; i < row_info.size(); ++i) {
2083                         if (row_info[i].endlastfoot) {
2084                                 ret += TeXRow(os, i, runparams);
2085                         }
2086                 }
2087                 if (endlastfoot.bottomDL) {
2088                         os << "\\hline\n";
2089                         ++ret;
2090                 }
2091                 os << "\\endlastfoot\n";
2092                 ++ret;
2093         }
2094         return ret;
2095 }
2096
2097
2098 bool Tabular::isValidRow(row_type row) const
2099 {
2100         if (!is_long_tabular)
2101                 return true;
2102         return !row_info[row].endhead && !row_info[row].endfirsthead &&
2103                         !row_info[row].endfoot && !row_info[row].endlastfoot;
2104 }
2105
2106
2107 int Tabular::TeXRow(odocstream & os, row_type i,
2108                        OutputParams const & runparams) const
2109 {
2110         idx_type cell = cellIndex(i, 0);
2111         int ret = TeXTopHLine(os, i);
2112         if (row_info[i].top_space_default) {
2113                 if (use_booktabs)
2114                         os << "\\addlinespace\n";
2115                 else
2116                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2117                 ++ret;
2118         } else if(!row_info[i].top_space.zero()) {
2119                 if (use_booktabs)
2120                         os << "\\addlinespace["
2121                            << from_ascii(row_info[i].top_space.asLatexString())
2122                            << "]\n";
2123                 else {
2124                         os << "\\noalign{\\vskip"
2125                            << from_ascii(row_info[i].top_space.asLatexString())
2126                            << "}\n";
2127                 }
2128                 ++ret;
2129         }
2130         bool ismulticol = false;
2131         for (col_type j = 0; j < column_info.size(); ++j) {
2132                 if (isPartOfMultiColumn(i, j))
2133                         continue;
2134                 ret += TeXCellPreamble(os, cell, ismulticol);
2135                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2136
2137                 Paragraph const & par = inset->paragraphs().front();
2138                 bool rtl = par.isRTL(buffer().params())
2139                         && !par.empty()
2140                         && getPWidth(cell).zero();
2141
2142                 if (rtl) {
2143                         if (par.getParLanguage(buffer().params())->lang() ==
2144                         "farsi")
2145                                 os << "\\textFR{";
2146                         else if (par.getParLanguage(buffer().params())->lang() == "arabic_arabi")
2147                                 os << "\\textAR{";
2148                         // currently, remaning RTL languages are arabic_arabtex and hebrew
2149                         else
2150                                 os << "\\R{";
2151                 }
2152                 ret += inset->latex(os, runparams);
2153                 if (rtl)
2154                         os << '}';
2155
2156                 ret += TeXCellPostamble(os, cell, ismulticol);
2157                 if (!isLastCellInRow(cell)) { // not last cell in row
2158                         os << " & ";
2159                 }
2160                 ++cell;
2161         }
2162         os << "\\tabularnewline";
2163         if (row_info[i].bottom_space_default) {
2164                 if (use_booktabs)
2165                         os << "\\addlinespace";
2166                 else
2167                         os << "[\\doublerulesep]";
2168         } else if (!row_info[i].bottom_space.zero()) {
2169                 if (use_booktabs)
2170                         os << "\\addlinespace";
2171                 os << '['
2172                    << from_ascii(row_info[i].bottom_space.asLatexString())
2173                    << ']';
2174         }
2175         os << '\n';
2176         ++ret;
2177         ret += TeXBottomHLine(os, i);
2178         if (row_info[i].interline_space_default) {
2179                 if (use_booktabs)
2180                         os << "\\addlinespace\n";
2181                 else
2182                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2183                 ++ret;
2184         } else if (!row_info[i].interline_space.zero()) {
2185                 if (use_booktabs)
2186                         os << "\\addlinespace["
2187                            << from_ascii(row_info[i].interline_space.asLatexString())
2188                            << "]\n";
2189                 else
2190                         os << "\\noalign{\\vskip"
2191                            << from_ascii(row_info[i].interline_space.asLatexString())
2192                            << "}\n";
2193                 ++ret;
2194         }
2195         return ret;
2196 }
2197
2198
2199 int Tabular::latex(odocstream & os, OutputParams const & runparams) const
2200 {
2201         int ret = 0;
2202
2203         //+---------------------------------------------------------------------
2204         //+                      first the opening preamble                    +
2205         //+---------------------------------------------------------------------
2206
2207         if (rotate) {
2208                 os << "\\begin{sideways}\n";
2209                 ++ret;
2210         }
2211         if (is_long_tabular)
2212                 os << "\\begin{longtable}{";
2213         else
2214                 os << "\\begin{tabular}{";
2215
2216         for (col_type i = 0; i < column_info.size(); ++i) {
2217                 if (columnLeftLine(i))
2218                         os << '|';
2219                 if (!column_info[i].align_special.empty()) {
2220                         os << column_info[i].align_special;
2221                 } else {
2222                         if (!column_info[i].p_width.zero()) {
2223                                 switch (column_info[i].alignment) {
2224                                 case LYX_ALIGN_LEFT:
2225                                         os << ">{\\raggedright}";
2226                                         break;
2227                                 case LYX_ALIGN_RIGHT:
2228                                         os << ">{\\raggedleft}";
2229                                         break;
2230                                 case LYX_ALIGN_CENTER:
2231                                         os << ">{\\centering}";
2232                                         break;
2233                                 case LYX_ALIGN_NONE:
2234                                 case LYX_ALIGN_BLOCK:
2235                                 case LYX_ALIGN_LAYOUT:
2236                                 case LYX_ALIGN_SPECIAL:
2237                                         break;
2238                                 }
2239
2240                                 switch (column_info[i].valignment) {
2241                                 case LYX_VALIGN_TOP:
2242                                         os << 'p';
2243                                         break;
2244                                 case LYX_VALIGN_MIDDLE:
2245                                         os << 'm';
2246                                         break;
2247                                 case LYX_VALIGN_BOTTOM:
2248                                         os << 'b';
2249                                         break;
2250                         }
2251                                 os << '{'
2252                                    << from_ascii(column_info[i].p_width.asLatexString())
2253                                    << '}';
2254                         } else {
2255                                 switch (column_info[i].alignment) {
2256                                 case LYX_ALIGN_LEFT:
2257                                         os << 'l';
2258                                         break;
2259                                 case LYX_ALIGN_RIGHT:
2260                                         os << 'r';
2261                                         break;
2262                                 default:
2263                                         os << 'c';
2264                                         break;
2265                                 }
2266                         } // end if else !column_info[i].p_width
2267                 } // end if else !column_info[i].align_special
2268                 if (columnRightLine(i))
2269                         os << '|';
2270         }
2271         os << "}\n";
2272         ++ret;
2273
2274         ret += TeXLongtableHeaderFooter(os, runparams);
2275
2276         //+---------------------------------------------------------------------
2277         //+                      the single row and columns (cells)            +
2278         //+---------------------------------------------------------------------
2279
2280         for (row_type i = 0; i < row_info.size(); ++i) {
2281                 if (isValidRow(i)) {
2282                         ret += TeXRow(os, i, runparams);
2283                         if (is_long_tabular && row_info[i].newpage) {
2284                                 os << "\\newpage\n";
2285                                 ++ret;
2286                         }
2287                 }
2288         }
2289
2290         //+---------------------------------------------------------------------
2291         //+                      the closing of the tabular                    +
2292         //+---------------------------------------------------------------------
2293
2294         if (is_long_tabular)
2295                 os << "\\end{longtable}";
2296         else
2297                 os << "\\end{tabular}";
2298         if (rotate) {
2299                 os << "\n\\end{sideways}";
2300                 ++ret;
2301         }
2302
2303         return ret;
2304 }
2305
2306
2307 int Tabular::docbookRow(odocstream & os, row_type row,
2308                            OutputParams const & runparams) const
2309 {
2310         int ret = 0;
2311         idx_type cell = getFirstCellInRow(row);
2312
2313         os << "<row>\n";
2314         for (col_type j = 0; j < column_info.size(); ++j) {
2315                 if (isPartOfMultiColumn(row, j))
2316                         continue;
2317
2318                 os << "<entry align=\"";
2319                 switch (getAlignment(cell)) {
2320                 case LYX_ALIGN_LEFT:
2321                         os << "left";
2322                         break;
2323                 case LYX_ALIGN_RIGHT:
2324                         os << "right";
2325                         break;
2326                 default:
2327                         os << "center";
2328                         break;
2329                 }
2330
2331                 os << "\" valign=\"";
2332                 switch (getVAlignment(cell)) {
2333                 case LYX_VALIGN_TOP:
2334                         os << "top";
2335                         break;
2336                 case LYX_VALIGN_BOTTOM:
2337                         os << "bottom";
2338                         break;
2339                 case LYX_VALIGN_MIDDLE:
2340                         os << "middle";
2341                 }
2342                 os << '"';
2343
2344                 if (isMultiColumn(cell)) {
2345                         os << " namest=\"col" << j << "\" ";
2346                         os << "nameend=\"col" << j + columnSpan(cell) - 1<< '"';
2347                 }
2348
2349                 os << '>';
2350                 ret += cellInset(cell)->docbook(os, runparams);
2351                 os << "</entry>\n";
2352                 ++cell;
2353         }
2354         os << "</row>\n";
2355         return ret;
2356 }
2357
2358
2359 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2360 {
2361         int ret = 0;
2362
2363         //+---------------------------------------------------------------------
2364         //+                      first the opening preamble                    +
2365         //+---------------------------------------------------------------------
2366
2367         os << "<tgroup cols=\"" << column_info.size()
2368            << "\" colsep=\"1\" rowsep=\"1\">\n";
2369
2370         for (col_type i = 0; i < column_info.size(); ++i) {
2371                 os << "<colspec colname=\"col" << i << "\" align=\"";
2372                 switch (column_info[i].alignment) {
2373                 case LYX_ALIGN_LEFT:
2374                         os << "left";
2375                         break;
2376                 case LYX_ALIGN_RIGHT:
2377                         os << "right";
2378                         break;
2379                 default:
2380                         os << "center";
2381                         break;
2382                 }
2383                 os << '"';
2384                 if (runparams.flavor == OutputParams::XML)
2385                         os << '/';
2386                 os << ">\n";
2387                 ++ret;
2388         }
2389
2390         //+---------------------------------------------------------------------
2391         //+                      Long Tabular case                             +
2392         //+---------------------------------------------------------------------
2393
2394         // output header info
2395         if (haveLTHead() || haveLTFirstHead()) {
2396                 os << "<thead>\n";
2397                 ++ret;
2398                 for (row_type i = 0; i < row_info.size(); ++i) {
2399                         if (row_info[i].endhead || row_info[i].endfirsthead) {
2400                                 ret += docbookRow(os, i, runparams);
2401                         }
2402                 }
2403                 os << "</thead>\n";
2404                 ++ret;
2405         }
2406         // output footer info
2407         if (haveLTFoot() || haveLTLastFoot()) {
2408                 os << "<tfoot>\n";
2409                 ++ret;
2410                 for (row_type i = 0; i < row_info.size(); ++i) {
2411                         if (row_info[i].endfoot || row_info[i].endlastfoot) {
2412                                 ret += docbookRow(os, i, runparams);
2413                         }
2414                 }
2415                 os << "</tfoot>\n";
2416                 ++ret;
2417         }
2418
2419         //+---------------------------------------------------------------------
2420         //+                      the single row and columns (cells)            +
2421         //+---------------------------------------------------------------------
2422
2423         os << "<tbody>\n";
2424         ++ret;
2425         for (row_type i = 0; i < row_info.size(); ++i) {
2426                 if (isValidRow(i)) {
2427                         ret += docbookRow(os, i, runparams);
2428                 }
2429         }
2430         os << "</tbody>\n";
2431         ++ret;
2432         //+---------------------------------------------------------------------
2433         //+                      the closing of the tabular                    +
2434         //+---------------------------------------------------------------------
2435
2436         os << "</tgroup>";
2437         ++ret;
2438
2439         return ret;
2440 }
2441
2442
2443 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2444                                    vector<unsigned int> const & clen) const
2445 {
2446         idx_type const fcell = getFirstCellInRow(row);
2447         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2448         idx_type tmp = 0;
2449
2450         for (idx_type i = fcell; i < n; ++i) {
2451                 if (topLine(i)) {
2452                         ++tmp;
2453                         break;
2454                 }
2455         }
2456         if (!tmp)
2457                 return false;
2458
2459         char_type ch;
2460         for (idx_type i = fcell; i < n; ++i) {
2461                 if (topLine(i)) {
2462                         if (leftLine(i))
2463                                 os << "+-";
2464                         else
2465                                 os << "--";
2466                         ch = '-';
2467                 } else {
2468                         os << "  ";
2469                         ch = ' ';
2470                 }
2471                 col_type column = cellColumn(i);
2472                 int len = clen[column];
2473                 while (column < column_info.size() - 1
2474                        && isPartOfMultiColumn(row, ++column))
2475                         len += clen[column] + 4;
2476                 os << docstring(len, ch);
2477                 if (topLine(i)) {
2478                         if (rightLine(i))
2479                                 os << "-+";
2480                         else
2481                                 os << "--";
2482                 } else {
2483                         os << "  ";
2484                 }
2485         }
2486         os << endl;
2487         return true;
2488 }
2489
2490
2491 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2492                                       vector<unsigned int> const & clen) const
2493 {
2494         idx_type const fcell = getFirstCellInRow(row);
2495         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2496         idx_type tmp = 0;
2497
2498         for (idx_type i = fcell; i < n; ++i) {
2499                 if (bottomLine(i)) {
2500                         ++tmp;
2501                         break;
2502                 }
2503         }
2504         if (!tmp)
2505                 return false;
2506
2507         char_type ch;
2508         for (idx_type i = fcell; i < n; ++i) {
2509                 if (bottomLine(i)) {
2510                         if (leftLine(i))
2511                                 os << "+-";
2512                         else
2513                                 os << "--";
2514                         ch = '-';
2515                 } else {
2516                         os << "  ";
2517                         ch = ' ';
2518                 }
2519                 col_type column = cellColumn(i);
2520                 int len = clen[column];
2521                 while (column < column_info.size() -1
2522                        && isPartOfMultiColumn(row, ++column))
2523                         len += clen[column] + 4;
2524                 os << docstring(len, ch);
2525                 if (bottomLine(i)) {
2526                         if (rightLine(i))
2527                                 os << "-+";
2528                         else
2529                                 os << "--";
2530                 } else {
2531                         os << "  ";
2532                 }
2533         }
2534         os << endl;
2535         return true;
2536 }
2537
2538
2539 void Tabular::plaintextPrintCell(odocstream & os,
2540                                OutputParams const & runparams,
2541                                idx_type cell, row_type row, col_type column,
2542                                vector<unsigned int> const & clen,
2543                                bool onlydata) const
2544 {
2545         odocstringstream sstr;
2546         cellInset(cell)->plaintext(sstr, runparams);
2547
2548         if (onlydata) {
2549                 os << sstr.str();
2550                 return;
2551         }
2552
2553         if (leftLine(cell))
2554                 os << "| ";
2555         else
2556                 os << "  ";
2557
2558         unsigned int len1 = sstr.str().length();
2559         unsigned int len2 = clen[column];
2560         while (column < column_info.size() -1
2561                && isPartOfMultiColumn(row, ++column))
2562                 len2 += clen[column] + 4;
2563         len2 -= len1;
2564
2565         switch (getAlignment(cell)) {
2566         default:
2567         case LYX_ALIGN_LEFT:
2568                 len1 = 0;
2569                 break;
2570         case LYX_ALIGN_RIGHT:
2571                 len1 = len2;
2572                 len2 = 0;
2573                 break;
2574         case LYX_ALIGN_CENTER:
2575                 len1 = len2 / 2;
2576                 len2 -= len1;
2577                 break;
2578         }
2579
2580         os << docstring(len1, ' ') << sstr.str()
2581            << docstring(len2, ' ');
2582
2583         if (rightLine(cell))
2584                 os << " |";
2585         else
2586                 os << "  ";
2587 }
2588
2589
2590 void Tabular::plaintext(odocstream & os,
2591                            OutputParams const & runparams, int const depth,
2592                            bool onlydata, char_type delim) const
2593 {
2594         // first calculate the width of the single columns
2595         vector<unsigned int> clen(column_info.size());
2596
2597         if (!onlydata) {
2598                 // first all non (real) multicolumn cells!
2599                 for (col_type j = 0; j < column_info.size(); ++j) {
2600                         clen[j] = 0;
2601                         for (row_type i = 0; i < row_info.size(); ++i) {
2602                                 idx_type cell = cellIndex(i, j);
2603                                 if (isMultiColumnReal(cell))
2604                                         continue;
2605                                 odocstringstream sstr;
2606                                 cellInset(cell)->plaintext(sstr, runparams);
2607                                 if (clen[j] < sstr.str().length())
2608                                         clen[j] = sstr.str().length();
2609                         }
2610                 }
2611                 // then all (real) multicolumn cells!
2612                 for (col_type j = 0; j < column_info.size(); ++j) {
2613                         for (row_type i = 0; i < row_info.size(); ++i) {
2614                                 idx_type cell = cellIndex(i, j);
2615                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2616                                         continue;
2617                                 odocstringstream sstr;
2618                                 cellInset(cell)->plaintext(sstr, runparams);
2619                                 int len = int(sstr.str().length());
2620                                 idx_type const n = columnSpan(cell);
2621                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2622                                         len -= clen[k];
2623                                 if (len > int(clen[j + n - 1]))
2624                                         clen[j + n - 1] = len;
2625                         }
2626                 }
2627         }
2628         idx_type cell = 0;
2629         for (row_type i = 0; i < row_info.size(); ++i) {
2630                 if (!onlydata && plaintextTopHLine(os, i, clen))
2631                         os << docstring(depth * 2, ' ');
2632                 for (col_type j = 0; j < column_info.size(); ++j) {
2633                         if (isPartOfMultiColumn(i, j))
2634                                 continue;
2635                         if (onlydata && j > 0)
2636                                 // we don't use operator<< for single UCS4 character.
2637                                 // see explanation in docstream.h
2638                                 os.put(delim);
2639                         plaintextPrintCell(os, runparams, cell, i, j, clen, onlydata);
2640                         ++cell;
2641                 }
2642                 os << endl;
2643                 if (!onlydata) {
2644                         os << docstring(depth * 2, ' ');
2645                         if (plaintextBottomHLine(os, i, clen))
2646                                 os << docstring(depth * 2, ' ');
2647                 }
2648         }
2649 }
2650
2651
2652 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
2653 {
2654         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2655 }
2656
2657
2658 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
2659                                                col_type column) const
2660 {
2661         return cell_info[row][column].inset;
2662 }
2663
2664
2665 void Tabular::setCellInset(row_type row, col_type column,
2666                               shared_ptr<InsetTableCell> ins) const
2667 {
2668         CellData & cd = cell_info[row][column];
2669         cd.inset = ins;
2670 }
2671
2672
2673 void Tabular::validate(LaTeXFeatures & features) const
2674 {
2675         features.require("NeedTabularnewline");
2676         if (use_booktabs)
2677                 features.require("booktabs");
2678         if (is_long_tabular)
2679                 features.require("longtable");
2680         if (needRotating())
2681                 features.require("rotating");
2682         for (idx_type cell = 0; cell < numberofcells; ++cell) {
2683                 if (getVAlignment(cell) != LYX_VALIGN_TOP ||
2684                      (!getPWidth(cell).zero() && !isMultiColumn(cell)))
2685                         features.require("array");
2686                 cellInset(cell)->validate(features);
2687         }
2688 }
2689
2690
2691 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2692 {
2693         ParagraphList const & parlist = cellInset(cell)->paragraphs();
2694         ParagraphList::const_iterator cit = parlist.begin();
2695         ParagraphList::const_iterator end = parlist.end();
2696
2697         for (; cit != end; ++cit)
2698                 for (int i = 0; i < cit->size(); ++i)
2699                         if (cit->isNewline(i))
2700                                 return BOX_PARBOX;
2701
2702         return BOX_NONE;
2703 }
2704
2705
2706 /////////////////////////////////////////////////////////////////////
2707 //
2708 // InsetTableCell
2709 //
2710 /////////////////////////////////////////////////////////////////////
2711
2712 InsetTableCell::InsetTableCell(Buffer & buf)
2713         : InsetText(buf), isFixedWidth(false)
2714 {}
2715
2716
2717 bool InsetTableCell::forcePlainLayout(idx_type) const
2718 {
2719         return !isFixedWidth;
2720 }
2721
2722 bool InsetTableCell::allowParagraphCustomization(idx_type) const
2723 {
2724         return isFixedWidth;
2725 }
2726
2727 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
2728         FuncStatus & status) const
2729 {
2730         bool enabled;
2731         switch (cmd.action) {
2732         case LFUN_LAYOUT:
2733                 enabled = !forcePlainLayout();
2734                 break;
2735         case LFUN_LAYOUT_PARAGRAPH:
2736                 enabled = allowParagraphCustomization();
2737                 break;
2738         default:
2739                 return InsetText::getStatus(cur, cmd, status);
2740         }
2741         status.setEnabled(enabled);
2742         return true;
2743 }
2744
2745 /////////////////////////////////////////////////////////////////////
2746 //
2747 // InsetTabular
2748 //
2749 /////////////////////////////////////////////////////////////////////
2750
2751 InsetTabular::InsetTabular(Buffer & buf, row_type rows,
2752                            col_type columns)
2753         : tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
2754         rowselect_(false), colselect_(false)
2755 {
2756         setBuffer(buf); // FIXME: remove later
2757 }
2758
2759
2760 InsetTabular::InsetTabular(InsetTabular const & tab)
2761         : Inset(tab), tabular(tab.tabular),  scx_(0)
2762 {
2763 }
2764
2765
2766 InsetTabular::~InsetTabular()
2767 {
2768         hideDialogs("tabular", this);
2769 }
2770
2771
2772 bool InsetTabular::insetAllowed(InsetCode code) const
2773 {
2774         if (code == MATHMACRO_CODE)
2775                 return false;
2776
2777         return true;
2778 }
2779
2780
2781 void InsetTabular::write(ostream & os) const
2782 {
2783         os << "Tabular" << endl;
2784         tabular.write(os);
2785 }
2786
2787
2788 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
2789 {
2790         // FIXME: depending on the selection state, we could offer a different menu.
2791         return from_ascii("context-tabular");
2792 }
2793
2794
2795 void InsetTabular::read(Lexer & lex)
2796 {
2797         //bool const old_format = (lex.getString() == "\\LyXTable");
2798
2799         tabular.read(lex);
2800
2801         //if (old_format)
2802         //      return;
2803
2804         lex.next();
2805         string token = lex.getString();
2806         while (lex && token != "\\end_inset") {
2807                 lex.next();
2808                 token = lex.getString();
2809         }
2810         if (!lex)
2811                 lex.printError("Missing \\end_inset at this point. ");
2812 }
2813
2814
2815 int InsetTabular::rowFromY(Cursor & cur, int y) const
2816 {
2817         // top y coordinate of tabular
2818         int h = yo(cur.bv()) - tabular.rowAscent(0);
2819         size_t nrows = tabular.row_info.size();
2820         row_type r = 0;
2821         for (; r < nrows && y > h; ++r) {
2822                 h += tabular.rowAscent(r);
2823                 h += tabular.rowDescent(r);
2824                 h += tabular.getAdditionalHeight(r);
2825         }
2826         return r - 1;
2827 }
2828
2829
2830 int InsetTabular::columnFromX(Cursor & cur, int x) const
2831 {
2832         // left x coordinate of tabular
2833         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
2834         size_t ncols = tabular.column_info.size();
2835         col_type c = 0;
2836         for (; c < ncols && x > w; ++c)
2837                 w += tabular.columnWidth(c);
2838         return c - 1;
2839 }
2840
2841
2842 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
2843 {
2844         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
2845         //      mi.base.textwidth << "\n";
2846         if (!mi.base.bv) {
2847                 LYXERR0("need bv");
2848                 LASSERT(false, /**/);
2849         }
2850
2851         row_type i = 0;
2852         for (idx_type cell = 0; i < tabular.row_info.size(); ++i) {
2853                 int maxAsc = 0;
2854                 int maxDesc = 0;
2855                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
2856                         if (tabular.isPartOfMultiColumn(i, j))
2857                                 // Multicolumn cell, but not first one
2858                                 continue;
2859                         Dimension dim;
2860                         MetricsInfo m = mi;
2861                         Length p_width;
2862                         if (tabular.cell_info[i][j].multicolumn ==
2863                                 Tabular::CELL_BEGIN_OF_MULTICOLUMN)
2864                                 p_width = tabular.cellInfo(cell).p_width;
2865                         else
2866                                 p_width = tabular.column_info[j].p_width;
2867                         if (!p_width.zero())
2868                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
2869                         tabular.cellInset(cell)->metrics(m, dim);
2870                         if (!p_width.zero())
2871                                 dim.wid = m.base.textwidth;
2872                         tabular.setCellWidth(cell, dim.wid);
2873                         maxAsc  = max(maxAsc, dim.asc);
2874                         maxDesc = max(maxDesc, dim.des);
2875                         ++cell;
2876                 }
2877                 int const top_space = tabular.row_info[i].top_space_default ?
2878                         default_line_space :
2879                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
2880                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
2881                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
2882                         default_line_space :
2883                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
2884                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
2885         }
2886         tabular.updateColumnWidths();
2887         dim.asc = tabular.rowAscent(0);
2888         dim.des = tabular.height() - dim.asc;
2889         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
2890 }
2891
2892
2893 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
2894 {
2895         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
2896         BufferView * bv = pi.base.bv;
2897
2898         // FIXME: As the full backrgound is painted in drawSelection(),
2899         // we have no choice but to do a full repaint for the Text cells.
2900         pi.full_repaint = true;
2901
2902         resetPos(bv->cursor());
2903
2904         x += scx_;
2905         x += ADD_TO_TABULAR_WIDTH;
2906
2907         bool const original_drawing_state = pi.pain.isDrawingEnabled();
2908
2909         idx_type idx = 0;
2910         first_visible_cell = Tabular::npos;
2911         for (row_type i = 0; i < tabular.row_info.size(); ++i) {
2912                 int nx = x;
2913                 int const a = tabular.rowAscent(i);
2914                 int const d = tabular.rowDescent(i);
2915                 idx = tabular.cellIndex(i, 0);
2916                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
2917                         if (tabular.isPartOfMultiColumn(i, j))
2918                                 continue;
2919                         if (first_visible_cell == Tabular::npos)
2920                                 first_visible_cell = idx;
2921
2922                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
2923                         // Cache the Inset position.
2924                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
2925                         if (nx + tabular.columnWidth(idx) < 0
2926                             || nx > bv->workWidth()
2927                             || y + d < 0
2928                             || y - a > bv->workHeight()) {
2929                                 pi.pain.setDrawingEnabled(false);
2930                                 cell(idx)->draw(pi, cx, y);
2931                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
2932                                 pi.pain.setDrawingEnabled(original_drawing_state);
2933                         } else {
2934                                 cell(idx)->draw(pi, cx, y);
2935                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
2936                         }
2937                         nx += tabular.columnWidth(idx);
2938                         ++idx;
2939                 }
2940
2941                 if (i + 1 < tabular.row_info.size())
2942                         y += d + tabular.rowAscent(i + 1) +
2943                                 tabular.getAdditionalHeight(i + 1);
2944         }
2945 }
2946
2947
2948 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
2949 {
2950         Cursor & cur = pi.base.bv->cursor();
2951
2952         x += scx_ + ADD_TO_TABULAR_WIDTH;
2953
2954         // FIXME: it is wrong to completely paint the background
2955         // if we want to do single row painting.
2956
2957         // Paint background of current tabular
2958         int const w = tabular.width();
2959         int const h = tabular.height();
2960         int yy = y - tabular.rowAscent(0);
2961         pi.pain.fillRectangle(x, yy, w, h, backgroundColor());
2962
2963         if (!cur.selection())
2964                 return;
2965         if (&cur.inset() != this)
2966                 return;
2967
2968         //resetPos(cur);
2969
2970
2971         if (tablemode(cur)) {
2972                 row_type rs, re;
2973                 col_type cs, ce;
2974                 getSelection(cur, rs, re, cs, ce);
2975                 y -= tabular.rowAscent(0);
2976                 for (row_type j = 0; j < tabular.row_info.size(); ++j) {
2977                         int const a = tabular.rowAscent(j);
2978                         int const h = a + tabular.rowDescent(j);
2979                         int xx = x;
2980                         y += tabular.getAdditionalHeight(j);
2981                         for (col_type i = 0; i < tabular.column_info.size(); ++i) {
2982                                 if (tabular.isPartOfMultiColumn(j, i))
2983                                         continue;
2984                                 idx_type const cell =
2985                                         tabular.cellIndex(j, i);
2986                                 int const w = tabular.columnWidth(cell);
2987                                 if (i >= cs && i <= ce && j >= rs && j <= re)
2988                                         pi.pain.fillRectangle(xx, y, w, h,
2989                                                               Color_selection);
2990                                 xx += w;
2991                         }
2992                         y += h;
2993                 }
2994
2995         } else {
2996                 x += cellXPos(cur.idx());
2997                 x += tabular.getBeginningOfTextInCell(cur.idx());
2998                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
2999         }
3000 }
3001
3002
3003 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
3004                                  row_type row, idx_type cell, bool erased) const
3005 {
3006         int x2 = x + tabular.columnWidth(cell);
3007         bool on_off = false;
3008         ColorCode col = Color_tabularline;
3009         ColorCode onoffcol = Color_tabularonoffline;
3010
3011         if (erased) {
3012                 col = Color_deletedtext;
3013                 onoffcol = Color_deletedtext;
3014         }
3015
3016         if (!tabular.topAlreadyDrawn(cell)) {
3017                 on_off = !tabular.topLine(cell);
3018                 pain.line(x, y - tabular.rowAscent(row),
3019                           x2, y -  tabular.rowAscent(row),
3020                           on_off ? onoffcol : col,
3021                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3022         }
3023         on_off = !tabular.bottomLine(cell);
3024         pain.line(x, y + tabular.rowDescent(row),
3025                   x2, y + tabular.rowDescent(row),
3026                   on_off ? onoffcol : col,
3027                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3028         if (!tabular.leftAlreadyDrawn(cell)) {
3029                 on_off = !tabular.leftLine(cell);
3030                 pain.line(x, y -  tabular.rowAscent(row),
3031                           x, y +  tabular.rowDescent(row),
3032                           on_off ? onoffcol : col,
3033                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3034         }
3035         on_off = !tabular.rightLine(cell);
3036         pain.line(x2 - tabular.getAdditionalWidth(cell),
3037                   y -  tabular.rowAscent(row),
3038                   x2 - tabular.getAdditionalWidth(cell),
3039                   y +  tabular.rowDescent(row),
3040                   on_off ? onoffcol : col,
3041                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3042 }
3043
3044
3045 docstring InsetTabular::editMessage() const
3046 {
3047         return _("Opened table");
3048 }
3049
3050
3051 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3052 {
3053         //lyxerr << "InsetTabular::edit: " << this << endl;
3054         cur.finishUndo();
3055         cur.selection() = false;
3056         cur.push(*this);
3057         if (front) {
3058                 if (isRightToLeft(cur))
3059                         cur.idx() = tabular.getLastCellInRow(0);
3060                 else
3061                         cur.idx() = 0;
3062                 cur.pit() = 0;
3063                 cur.pos() = 0;
3064         } else {
3065                 if (isRightToLeft(cur))
3066                         cur.idx() = tabular.getFirstCellInRow(tabular.row_info.size() - 1);
3067                 else
3068                         cur.idx() = tabular.numberofcells - 1;
3069                 cur.pit() = 0;
3070                 cur.pos() = cur.lastpos(); // FIXME crude guess
3071         }
3072         // FIXME: this accesses the position cache before it is initialized
3073         //resetPos(cur);
3074         //cur.bv().fitCursor();
3075 }
3076
3077
3078 void InsetTabular::updateLabels(ParIterator const & it)
3079 {
3080         // In a longtable, tell captions what the current float is
3081         Counters & cnts = buffer().params().documentClass().counters();
3082         string const saveflt = cnts.current_float();
3083         if (tabular.is_long_tabular)
3084                 cnts.current_float("table");
3085
3086         ParIterator it2 = it;
3087         it2.forwardPos();
3088         size_t const end = it2.nargs();
3089         for ( ; it2.idx() < end; it2.top().forwardIdx())
3090                 lyx::updateLabels(buffer(), it2);
3091
3092         //reset afterwards
3093         if (tabular.is_long_tabular)
3094                 cnts.current_float(saveflt);
3095 }
3096
3097
3098 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3099 {
3100         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3101                              << "\n  cur:" << cur);
3102         CursorSlice sl = cur.top();
3103         Cursor & bvcur = cur.bv().cursor();
3104
3105         switch (cmd.action) {
3106
3107         case LFUN_MOUSE_PRESS: {
3108                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3109                 // select row
3110                 if (cmd.x < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3111                         || cmd.x > xo(cur.bv()) + tabular.width()) {
3112                         row_type r = rowFromY(cur, cmd.y);
3113                         cur.idx() = tabular.getFirstCellInRow(r);
3114                         cur.pos() = 0;
3115                         cur.resetAnchor();
3116                         cur.idx() = tabular.getLastCellInRow(r);
3117                         cur.pos() = cur.lastpos();
3118                         cur.selection() = true;
3119                         bvcur = cur; 
3120                         rowselect_ = true;
3121                         break;
3122                 }
3123                 // select column
3124                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3125                 if (cmd.y < y0 + ADD_TO_TABULAR_WIDTH 
3126                         || cmd.y > y0 + tabular.height()) {
3127                         col_type c = columnFromX(cur, cmd.x);
3128                         cur.idx() = tabular.cellIndex(0, c);
3129                         cur.pos() = 0;
3130                         cur.resetAnchor();
3131                         cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3132                         cur.pos() = cur.lastpos();
3133                         cur.selection() = true;
3134                         bvcur = cur; 
3135                         colselect_ = true;
3136                         break;
3137                 }
3138                 // do not reset cursor/selection if we have selected
3139                 // some cells (bug 2715).
3140                 if (cmd.button() == mouse_button::button3
3141                     && &bvcur.selBegin().inset() == this 
3142                     && tablemode(bvcur)) 
3143                         ;
3144                 else
3145                         // Let InsetTableCell do it
3146                         cell(cur.idx())->dispatch(cur, cmd);
3147                 break;
3148         }
3149         case LFUN_MOUSE_MOTION:
3150                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3151                 if (cmd.button() == mouse_button::button1) {
3152                         // only accept motions to places not deeper nested than the real anchor
3153                         if (!bvcur.anchor_.hasPart(cur)) {
3154                                 cur.undispatched();
3155                                 break;
3156                         }
3157                         // select (additional) row
3158                         if (rowselect_) {
3159                                 row_type r = rowFromY(cur, cmd.y);
3160                                 cur.idx() = tabular.getLastCellInRow(r);
3161                                 bvcur.setCursor(cur);
3162                                 bvcur.selection() = true;
3163                                 break;
3164                         }
3165                         // select (additional) column
3166                         if (colselect_) {
3167                                 col_type c = columnFromX(cur, cmd.x);
3168                                 cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3169                                 bvcur.setCursor(cur);
3170                                 bvcur.selection() = true;
3171                                 break;
3172                         }
3173                         // only update if selection changes
3174                         if (bvcur.idx() == cur.idx() &&
3175                                 !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3176                                 cur.noUpdate();
3177                         setCursorFromCoordinates(cur, cmd.x, cmd.y);
3178                         bvcur.setCursor(cur);
3179                         bvcur.selection() = true;
3180                 }
3181                 break;
3182
3183         case LFUN_MOUSE_RELEASE:
3184                 rowselect_ = false;
3185                 colselect_ = false;
3186                 break;
3187
3188         case LFUN_CELL_BACKWARD:
3189                 movePrevCell(cur);
3190                 cur.selection() = false;
3191                 break;
3192
3193         case LFUN_CELL_FORWARD:
3194                 moveNextCell(cur);
3195                 cur.selection() = false;
3196                 break;
3197         case LFUN_CHAR_FORWARD_SELECT:
3198         case LFUN_CHAR_FORWARD:
3199         case LFUN_CHAR_BACKWARD_SELECT:
3200         case LFUN_CHAR_BACKWARD:
3201         case LFUN_CHAR_RIGHT_SELECT:
3202         case LFUN_CHAR_RIGHT:
3203         case LFUN_CHAR_LEFT_SELECT:
3204         case LFUN_CHAR_LEFT: {
3205
3206                 // determine whether we move to next or previous cell, where to enter 
3207                 // the new cell from, and which command to "finish" (i.e., exit the
3208                 // inset) with:
3209                 bool next_cell;
3210                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3211                 FuncCode finish_lfun;
3212
3213                 if (cmd.action == LFUN_CHAR_FORWARD 
3214                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
3215                         next_cell = true;
3216                         finish_lfun = LFUN_FINISHED_FORWARD;
3217                 }
3218                 else if (cmd.action == LFUN_CHAR_BACKWARD
3219                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
3220                         next_cell = false;
3221                         finish_lfun = LFUN_FINISHED_BACKWARD;
3222                 }
3223                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3224                 // table's direction.
3225                 else {
3226                         bool right = (cmd.action == LFUN_CHAR_RIGHT
3227                                                         || cmd.action == LFUN_CHAR_RIGHT_SELECT);
3228                         next_cell = (isRightToLeft(cur) != right);
3229                         
3230                         if (lyxrc.visual_cursor) {
3231                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3232                         }
3233
3234                         if (right)
3235                                 finish_lfun = LFUN_FINISHED_RIGHT;
3236                         else
3237                                 finish_lfun = LFUN_FINISHED_LEFT;
3238                 }
3239                 
3240
3241                 // finally, now that we know what we want to do, do it!
3242                 cell(cur.idx())->dispatch(cur, cmd);
3243                 if (!cur.result().dispatched()) {
3244                         // move to next/prev cell, as appropriate
3245                         LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3246                                 << " cell from: " << int(entry_from));
3247                         if (next_cell)
3248                                 moveNextCell(cur, entry_from);
3249                         else
3250                                 movePrevCell(cur, entry_from);
3251                         // if we're exiting the table, call the appropriate FINISHED lfun
3252                         if (sl == cur.top())
3253                                 cmd = FuncRequest(finish_lfun);
3254                         else
3255                                 cur.dispatched();
3256                 }
3257                 break;
3258
3259         }
3260
3261         case LFUN_DOWN_SELECT:
3262         case LFUN_DOWN:
3263                 cell(cur.idx())->dispatch(cur, cmd);
3264                 cur.dispatched(); // override the cell's decision
3265                 if (sl == cur.top())
3266                         // if our Text didn't do anything to the cursor
3267                         // then we try to put the cursor into the cell below
3268                         // setting also the right targetX.
3269                         if (tabular.cellRow(cur.idx()) != tabular.row_info.size() - 1) {
3270                                 cur.idx() = tabular.cellBelow(cur.idx());
3271                                 cur.pit() = 0;
3272                                 TextMetrics const & tm =
3273                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3274                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3275                         }
3276                 if (sl == cur.top()) {
3277                         // we trick it to go to forward after leaving the
3278                         // tabular.
3279                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3280                         cur.undispatched();
3281                 }
3282                 break;
3283
3284         case LFUN_UP_SELECT:
3285         case LFUN_UP:
3286                 cell(cur.idx())->dispatch(cur, cmd);
3287                 cur.dispatched(); // override the cell's decision
3288                 if (sl == cur.top())
3289                         // if our Text didn't do anything to the cursor
3290                         // then we try to put the cursor into the cell above
3291                         // setting also the right targetX.
3292                         if (tabular.cellRow(cur.idx()) != 0) {
3293                                 cur.idx() = tabular.cellAbove(cur.idx());
3294                                 cur.pit() = cur.lastpit();
3295                                 Text const * text = cell(cur.idx())->getText(0);
3296                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3297                                 ParagraphMetrics const & pm =
3298                                         tm.parMetrics(cur.lastpit());
3299                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3300                         }
3301                 if (sl == cur.top()) {
3302                         cmd = FuncRequest(LFUN_UP);
3303                         cur.undispatched();
3304                 }
3305                 break;
3306
3307 //      case LFUN_SCREEN_DOWN: {
3308 //              //if (hasSelection())
3309 //              //      cur.selection() = false;
3310 //              col_type const col = tabular.cellColumn(cur.idx());
3311 //              int const t =   cur.bv().top_y() + cur.bv().height();
3312 //              if (t < yo() + tabular.getHeightOfTabular()) {
3313 //                      cur.bv().scrollDocView(t);
3314 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3315 //              } else {
3316 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3317 //              }
3318 //              cur.par() = 0;
3319 //              cur.pos() = 0;
3320 //              break;
3321 //      }
3322 //
3323 //      case LFUN_SCREEN_UP: {
3324 //              //if (hasSelection())
3325 //              //      cur.selection() = false;
3326 //              col_type const col = tabular.cellColumn(cur.idx());
3327 //              int const t =   cur.bv().top_y() + cur.bv().height();
3328 //              if (yo() < 0) {
3329 //                      cur.bv().scrollDocView(t);
3330 //                      if (yo() > 0)
3331 //                              cur.idx() = col;
3332 //                      else
3333 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3334 //              } else {
3335 //                      cur.idx() = col;
3336 //              }
3337 //              cur.par() = cur.lastpar();
3338 //              cur.pos() = cur.lastpos();
3339 //              break;
3340 //      }
3341
3342         case LFUN_LAYOUT_TABULAR:
3343                 cur.bv().showDialog("tabular", params2string(*this), this);
3344                 break;
3345
3346         case LFUN_INSET_DIALOG_UPDATE:
3347                 cur.bv().updateDialog("tabular", params2string(*this));
3348                 break;
3349
3350         case LFUN_TABULAR_FEATURE:
3351                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3352                         cur.undispatched();
3353                 break;
3354
3355         // insert file functions
3356         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3357         case LFUN_FILE_INSERT_PLAINTEXT: {
3358                 // FIXME UNICODE
3359                 docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3360                         FileName(to_utf8(cmd.argument())));
3361                 if (tmpstr.empty())
3362                         break;
3363                 cur.recordUndoInset(INSERT_UNDO);
3364                 if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3365                         // content has been replaced,
3366                         // so cursor might be invalid
3367                         cur.pos() = cur.lastpos();
3368                         cur.pit() = cur.lastpit();
3369                         bvcur.setCursor(cur);
3370                 } else
3371                         cur.undispatched();
3372                 break;
3373         }
3374
3375         case LFUN_CUT:
3376                 if (tablemode(cur)) {
3377                         if (copySelection(cur)) {
3378                                 cur.recordUndoInset(DELETE_UNDO);
3379                                 cutSelection(cur);
3380                         }
3381                 }
3382                 else
3383                         cell(cur.idx())->dispatch(cur, cmd);
3384                 break;
3385
3386         case LFUN_CHAR_DELETE_BACKWARD:
3387         case LFUN_CHAR_DELETE_FORWARD:
3388                 if (tablemode(cur)) {
3389                         cur.recordUndoInset(DELETE_UNDO);
3390                         cutSelection(cur);
3391                 }
3392                 else
3393                         cell(cur.idx())->dispatch(cur, cmd);
3394                 break;
3395
3396         case LFUN_COPY:
3397                 if (!cur.selection())
3398                         break;
3399                 if (tablemode(cur)) {
3400                         cur.finishUndo();
3401                         copySelection(cur);
3402                 } else
3403                         cell(cur.idx())->dispatch(cur, cmd);
3404                 break;
3405
3406         case LFUN_CLIPBOARD_PASTE:
3407         case LFUN_PRIMARY_SELECTION_PASTE: {
3408                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3409                         theClipboard().getAsText() :
3410                         theSelection().get();
3411                 if (clip.empty())
3412                         break;
3413                 // pass to InsertPlaintextString, but
3414                 // only if we have multi-cell content
3415                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3416                         cur.recordUndoInset(INSERT_UNDO);
3417                         if (insertPlaintextString(cur.bv(), clip, false)) {
3418                                 // content has been replaced,
3419                                 // so cursor might be invalid
3420                                 cur.pos() = cur.lastpos();
3421                                 cur.pit() = cur.lastpit();
3422                                 bvcur.setCursor(cur);
3423                                 break;
3424                         }
3425                 }
3426                 // Let the cell handle normal text
3427                 cell(cur.idx())->dispatch(cur, cmd);
3428                 break;
3429         }
3430
3431         case LFUN_PASTE:
3432                 if (!tabularStackDirty()) {
3433                         cell(cur.idx())->dispatch(cur, cmd);
3434                         break;
3435                 }
3436                 if (theClipboard().isInternal() ||
3437                     !theClipboard().hasInternal() && theClipboard().hasLyXContents()) {
3438                         cur.recordUndoInset(INSERT_UNDO);
3439                         pasteClipboard(cur);
3440                 }
3441                 break;
3442
3443         case LFUN_FONT_EMPH:
3444         case LFUN_FONT_BOLD:
3445         case LFUN_FONT_ROMAN:
3446         case LFUN_FONT_NOUN:
3447         case LFUN_FONT_ITAL:
3448         case LFUN_FONT_FRAK:
3449         case LFUN_FONT_TYPEWRITER:
3450         case LFUN_FONT_SANS:
3451         case LFUN_TEXTSTYLE_APPLY:
3452         case LFUN_TEXTSTYLE_UPDATE:
3453         case LFUN_FONT_SIZE:
3454         case LFUN_FONT_UNDERLINE:
3455         case LFUN_LANGUAGE:
3456         case LFUN_WORD_CAPITALIZE:
3457         case LFUN_WORD_UPCASE:
3458         case LFUN_WORD_LOWCASE:
3459         case LFUN_CHARS_TRANSPOSE:
3460                 if (tablemode(cur)) {
3461                         row_type rs, re;
3462                         col_type cs, ce;
3463                         getSelection(cur, rs, re, cs, ce);
3464                         Cursor tmpcur = cur;
3465                         for (row_type i = rs; i <= re; ++i) {
3466                                 for (col_type j = cs; j <= ce; ++j) {
3467                                         // cursor follows cell:
3468                                         tmpcur.idx() = tabular.cellIndex(i, j);
3469                                         // select this cell only:
3470                                         tmpcur.pit() = 0;
3471                                         tmpcur.pos() = 0;
3472                                         tmpcur.resetAnchor();
3473                                         tmpcur.pit() = tmpcur.lastpit();
3474                                         tmpcur.pos() = tmpcur.top().lastpos();
3475                                         tmpcur.setCursor(tmpcur);
3476                                         tmpcur.setSelection();
3477                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3478                                 }
3479                         }
3480                         break;
3481                 } else {
3482                         cell(cur.idx())->dispatch(cur, cmd);
3483                         break;
3484                 }
3485         default:
3486                 // we try to handle this event in the insets dispatch function.
3487                 cell(cur.idx())->dispatch(cur, cmd);
3488                 break;
3489         }
3490 }
3491
3492
3493 // function sets an object as defined in func_status.h:
3494 // states OK, Unknown, Disabled, On, Off.
3495 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3496         FuncStatus & status) const
3497 {
3498         switch (cmd.action) {
3499         case LFUN_TABULAR_FEATURE: {
3500                 int action = Tabular::LAST_ACTION;
3501                 int i = 0;
3502                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3503                         string const tmp = tabularFeature[i].feature;
3504                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3505                                 action = tabularFeature[i].action;
3506                                 break;
3507                         }
3508                 }
3509                 if (action == Tabular::LAST_ACTION) {
3510                         status.clear();
3511                         status.unknown(true);
3512                         return true;
3513                 }
3514
3515                 string const argument
3516                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3517
3518                 row_type sel_row_start = 0;
3519                 row_type sel_row_end = 0;
3520                 col_type sel_col_start = 0;
3521                 col_type sel_col_end = 0;
3522                 Tabular::ltType dummyltt;
3523                 bool flag = true;
3524
3525                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3526
3527                 switch (action) {
3528                 case Tabular::SET_PWIDTH:
3529                 case Tabular::SET_MPWIDTH:
3530                 case Tabular::SET_SPECIAL_COLUMN:
3531                 case Tabular::SET_SPECIAL_MULTI:
3532                 case Tabular::APPEND_ROW:
3533                 case Tabular::APPEND_COLUMN:
3534                 case Tabular::DELETE_ROW:
3535                 case Tabular::DELETE_COLUMN:
3536                 case Tabular::COPY_ROW:
3537                 case Tabular::COPY_COLUMN:
3538                 case Tabular::SET_TOP_SPACE:
3539                 case Tabular::SET_BOTTOM_SPACE:
3540                 case Tabular::SET_INTERLINE_SPACE:
3541                         status.clear();
3542                         return true;
3543
3544                 case Tabular::MULTICOLUMN:
3545                         status.setEnabled(sel_row_start == sel_row_end);
3546                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3547                         break;
3548
3549                 case Tabular::SET_ALL_LINES:
3550                 case Tabular::UNSET_ALL_LINES:
3551                 case Tabular::SET_BORDER_LINES:
3552                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3553                         break;
3554
3555                 case Tabular::TOGGLE_LINE_TOP:
3556                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3557                         status.setOnOff(tabular.topLine(cur.idx()));
3558                         break;
3559
3560                 case Tabular::TOGGLE_LINE_BOTTOM:
3561                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3562                         status.setOnOff(tabular.bottomLine(cur.idx()));
3563                         break;
3564
3565                 case Tabular::TOGGLE_LINE_LEFT:
3566                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3567                         status.setOnOff(tabular.leftLine(cur.idx()));
3568                         break;
3569
3570                 case Tabular::TOGGLE_LINE_RIGHT:
3571                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3572                         status.setOnOff(tabular.rightLine(cur.idx()));
3573                         break;
3574
3575                 case Tabular::M_ALIGN_LEFT:
3576                         flag = false;
3577                 case Tabular::ALIGN_LEFT:
3578                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3579                         break;
3580
3581                 case Tabular::M_ALIGN_RIGHT:
3582                         flag = false;
3583                 case Tabular::ALIGN_RIGHT:
3584                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3585                         break;
3586
3587                 case Tabular::M_ALIGN_CENTER:
3588                         flag = false;
3589                 case Tabular::ALIGN_CENTER:
3590                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3591                         break;
3592
3593                 case Tabular::ALIGN_BLOCK:
3594                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
3595                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3596                         break;
3597
3598                 case Tabular::M_VALIGN_TOP:
3599                         flag = false;
3600                 case Tabular::VALIGN_TOP:
3601                         status.setOnOff(
3602                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3603                         break;
3604
3605                 case Tabular::M_VALIGN_BOTTOM:
3606                         flag = false;
3607                 case Tabular::VALIGN_BOTTOM:
3608                         status.setOnOff(
3609                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3610                         break;
3611
3612                 case Tabular::M_VALIGN_MIDDLE:
3613                         flag = false;
3614                 case Tabular::VALIGN_MIDDLE:
3615                         status.setOnOff(
3616                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3617                         break;
3618
3619                 case Tabular::SET_LONGTABULAR:
3620                         status.setOnOff(tabular.is_long_tabular);
3621                         break;
3622
3623                 case Tabular::UNSET_LONGTABULAR:
3624                         status.setOnOff(!tabular.is_long_tabular);
3625                         break;
3626
3627                 case Tabular::TOGGLE_ROTATE_TABULAR:
3628                 case Tabular::SET_ROTATE_TABULAR:
3629                         status.setOnOff(tabular.rotate);
3630                         break;
3631
3632                 case Tabular::UNSET_ROTATE_TABULAR:
3633                         status.setOnOff(!tabular.rotate);
3634                         break;
3635
3636                 case Tabular::TOGGLE_ROTATE_CELL:
3637                 case Tabular::SET_ROTATE_CELL:
3638                         status.setOnOff(!oneCellHasRotationState(false,
3639                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3640                         break;
3641
3642                 case Tabular::UNSET_ROTATE_CELL:
3643                         status.setOnOff(!oneCellHasRotationState(true,
3644                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3645                         break;
3646
3647                 case Tabular::SET_USEBOX:
3648                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
3649                         break;
3650
3651                 case Tabular::SET_LTFIRSTHEAD:
3652                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3653                         break;
3654
3655                 case Tabular::UNSET_LTFIRSTHEAD:
3656                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3657                         break;
3658
3659                 case Tabular::SET_LTHEAD:
3660                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3661                         break;
3662
3663                 case Tabular::UNSET_LTHEAD:
3664                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3665                         break;
3666
3667                 case Tabular::SET_LTFOOT:
3668                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3669                         break;
3670
3671                 case Tabular::UNSET_LTFOOT:
3672                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3673                         break;
3674
3675                 case Tabular::SET_LTLASTFOOT:
3676                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3677                         break;
3678
3679                 case Tabular::UNSET_LTLASTFOOT:
3680                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3681                         break;
3682
3683                 case Tabular::SET_LTNEWPAGE:
3684                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
3685                         break;
3686
3687                 case Tabular::TOGGLE_LTCAPTION:
3688                         status.setEnabled(sel_row_start == sel_row_end);
3689                         status.setOnOff(tabular.ltCaption(sel_row_start));
3690                         break;
3691
3692                 case Tabular::SET_BOOKTABS:
3693                         status.setOnOff(tabular.use_booktabs);
3694                         break;
3695
3696                 case Tabular::UNSET_BOOKTABS:
3697                         status.setOnOff(!tabular.use_booktabs);
3698                         break;
3699
3700                 default:
3701                         status.clear();
3702                         status.setEnabled(false);
3703                         break;
3704                 }
3705                 return true;
3706         }
3707
3708         // These are only enabled inside tabular
3709         case LFUN_CELL_BACKWARD:
3710         case LFUN_CELL_FORWARD:
3711                 status.setEnabled(true);
3712                 return true;
3713
3714         // disable these with multiple cells selected
3715         case LFUN_INSET_INSERT:
3716         case LFUN_TABULAR_INSERT:
3717         case LFUN_FLEX_INSERT:
3718         case LFUN_FLOAT_INSERT:
3719         case LFUN_FLOAT_WIDE_INSERT:
3720         case LFUN_FOOTNOTE_INSERT:
3721         case LFUN_MARGINALNOTE_INSERT:
3722         case LFUN_MATH_INSERT:
3723         case LFUN_MATH_MODE:
3724         case LFUN_MATH_MUTATE:
3725         case LFUN_MATH_DISPLAY:
3726         case LFUN_NOTE_INSERT:
3727         case LFUN_OPTIONAL_INSERT:
3728         case LFUN_BOX_INSERT:
3729         case LFUN_BRANCH_INSERT:
3730         case LFUN_WRAP_INSERT:
3731         case LFUN_ERT_INSERT: {
3732                 if (tablemode(cur)) {
3733                         status.setEnabled(false);
3734                         return true;
3735                 } else
3736                         return cell(cur.idx())->getStatus(cur, cmd, status);
3737         }
3738
3739         // disable in non-fixed-width cells
3740         case LFUN_NEWLINE_INSERT:
3741         case LFUN_BREAK_PARAGRAPH: {
3742                 if (tabular.getPWidth(cur.idx()).zero()) {
3743                         status.setEnabled(false);
3744                         return true;
3745                 } else
3746                         return cell(cur.idx())->getStatus(cur, cmd, status);
3747         }
3748
3749         case LFUN_PASTE:
3750                 if (tabularStackDirty() && theClipboard().isInternal()) {
3751                         status.setEnabled(true);
3752                         return true;
3753                 } else
3754                         return cell(cur.idx())->getStatus(cur, cmd, status);
3755
3756         case LFUN_INSET_MODIFY:
3757                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
3758                         status.setEnabled(true);
3759                         return true;
3760                 }
3761                 // Fall through
3762
3763         default:
3764                 // we try to handle this event in the insets dispatch function.
3765                 return cell(cur.idx())->getStatus(cur, cmd, status);
3766         }
3767 }
3768
3769
3770 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
3771 {
3772         return tabular.latex(os, runparams);
3773 }
3774
3775
3776 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
3777 {
3778         os << '\n'; // output table on a new line
3779         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
3780         tabular.plaintext(os, runparams, dp, false, 0);
3781         return PLAINTEXT_NEWLINE;
3782 }
3783
3784
3785 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
3786 {
3787         int ret = 0;
3788         Inset * master = 0;
3789
3790         // FIXME: Why not pass a proper DocIterator here?
3791 #if 0
3792         // if the table is inside a float it doesn't need the informaltable
3793         // wrapper. Search for it.
3794         for (master = owner(); master; master = master->owner())
3795                 if (master->lyxCode() == FLOAT_CODE)
3796                         break;
3797 #endif
3798
3799         if (!master) {
3800                 os << "<informaltable>";
3801                 ++ret;
3802         }
3803         ret += tabular.docbook(os, runparams);
3804         if (!master) {
3805                 os << "</informaltable>";
3806                 ++ret;
3807         }
3808         return ret;
3809 }
3810
3811
3812 void InsetTabular::validate(LaTeXFeatures & features) const
3813 {
3814         tabular.validate(features);
3815 }
3816
3817
3818 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
3819 {
3820         return tabular.cellInset(idx);
3821 }
3822
3823
3824 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
3825 {
3826         return tabular.cellInset(idx);
3827 }
3828
3829
3830 void InsetTabular::cursorPos(BufferView const & bv,
3831                 CursorSlice const & sl, bool boundary, int & x, int & y) const
3832 {
3833         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
3834
3835         // y offset     correction
3836         int const row = tabular.cellRow(sl.idx());
3837         for (int i = 0; i <= row; ++i) {
3838                 if (i != 0) {
3839                         y += tabular.rowAscent(i);
3840                         y += tabular.getAdditionalHeight(i);
3841                 }
3842                 if (i != row)
3843                         y += tabular.rowDescent(i);
3844         }
3845
3846         // x offset correction
3847         int const col = tabular.cellColumn(sl.idx());
3848         int idx = tabular.cellIndex(row, 0);
3849         for (int j = 0; j < col; ++j) {
3850                 if (tabular.isPartOfMultiColumn(row, j))
3851                         continue;
3852                 x += tabular.columnWidth(idx);
3853                 ++idx;
3854         }
3855         x += tabular.getBeginningOfTextInCell(idx);
3856         x += ADD_TO_TABULAR_WIDTH;
3857         x += scx_;
3858 }
3859
3860
3861 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
3862 {
3863         int xx = 0;
3864         int yy = 0;
3865         Inset const & inset = *tabular.cellInset(cell);
3866         Point o = bv.coordCache().getInsets().xy(&inset);
3867         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
3868         int const xend = xbeg + tabular.columnWidth(cell);
3869         row_type const row = tabular.cellRow(cell);
3870         int const ybeg = o.y_ - tabular.rowAscent(row) -
3871                          tabular.getAdditionalHeight(row);
3872         int const yend = o.y_ + tabular.rowDescent(row);
3873
3874         if (x < xbeg)
3875                 xx = xbeg - x;
3876         else if (x > xend)
3877                 xx = x - xend;
3878
3879         if (y < ybeg)
3880                 yy = ybeg - y;
3881         else if (y > yend)
3882                 yy = y - yend;
3883
3884         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
3885         //       << " ybeg=" << ybeg << " yend=" << yend
3886         //       << " xx=" << xx << " yy=" << yy
3887         //       << " dist=" << xx + yy << endl;
3888         return xx + yy;
3889 }
3890
3891
3892 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
3893 {
3894         //lyxerr << "InsetTabular::editXY: " << this << endl;
3895         cur.selection() = false;
3896         cur.push(*this);
3897         cur.idx() = getNearestCell(cur.bv(), x, y);
3898         resetPos(cur);
3899         return cur.bv().textMetrics(&cell(cur.idx())->text_).editXY(cur, x, y);
3900 }
3901
3902
3903 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
3904 {
3905         cur.idx() = getNearestCell(cur.bv(), x, y);
3906         cur.bv().textMetrics(&cell(cur.idx())->text_).setCursorFromCoordinates(cur, x, y);
3907 }
3908
3909
3910 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
3911 {
3912         idx_type idx_min = 0;
3913         int dist_min = numeric_limits<int>::max();
3914         for (idx_type i = 0, n = nargs(); i != n; ++i) {
3915                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
3916                         int const d = dist(bv, i, x, y);
3917                         if (d < dist_min) {
3918                                 dist_min = d;
3919                                 idx_min = i;
3920                         }
3921                 }
3922         }
3923         return idx_min;
3924 }
3925
3926
3927 int InsetTabular::cellXPos(idx_type const cell) const
3928 {
3929         idx_type c = cell;
3930
3931         for (; !tabular.isFirstCellInRow(c); --c)
3932                 ;
3933         int lx = 0;
3934         for (; c < cell; ++c)
3935                 lx += tabular.columnWidth(c);
3936
3937         return lx;
3938 }
3939
3940
3941 void InsetTabular::resetPos(Cursor & cur) const
3942 {
3943         BufferView & bv = cur.bv();
3944         int const maxwidth = bv.workWidth();
3945
3946         if (&cur.inset() != this) {
3947                 scx_ = 0;
3948         } else {
3949                 int const X1 = 0;
3950                 int const X2 = maxwidth;
3951                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
3952                 int const x1 = xo(cur.bv()) + cellXPos(cur.idx()) + offset;
3953                 int const x2 = x1 + tabular.columnWidth(cur.idx());
3954
3955                 if (x1 < X1)
3956                         scx_ = X1 + 20 - x1;
3957                 else if (x2 > X2)
3958                         scx_ = X2 - 20 - x2;
3959                 else
3960                         scx_ = 0;
3961         }
3962
3963         cur.updateFlags(Update::Force | Update::FitCursor);
3964 }
3965
3966
3967 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
3968 {
3969         if (isRightToLeft(cur)) {
3970                 if (tabular.isFirstCellInRow(cur.idx())) {
3971                         row_type const row = tabular.cellRow(cur.idx());
3972                         if (row == tabular.row_info.size() - 1)
3973                                 return;
3974                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
3975                 } else {
3976                         if (cur.idx() == 0)
3977                                 return;
3978                         --cur.idx();
3979                 }
3980         } else {
3981                 if (tabular.isLastCell(cur.idx()))
3982                         return;
3983                 ++cur.idx();
3984         }
3985         cur.pit() = 0;
3986         cur.pos() = 0;
3987         cur.boundary(false);
3988
3989         // in visual mode, place cursor at extreme left or right
3990         
3991         switch(entry_from) {
3992
3993         case ENTRY_DIRECTION_RIGHT:
3994                 cur.posVisToRowExtremity(false /* !left */);
3995                 break;
3996         case ENTRY_DIRECTION_LEFT:
3997                 cur.posVisToRowExtremity(true /* left */);
3998                 break;
3999         case ENTRY_DIRECTION_IGNORE:
4000                 // nothing to do in this case
4001                 break;
4002
4003         }
4004
4005         resetPos(cur);
4006 }
4007
4008
4009 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
4010 {
4011         if (isRightToLeft(cur)) {
4012                 if (tabular.isLastCellInRow(cur.idx())) {
4013                         row_type const row = tabular.cellRow(cur.idx());
4014                         if (row == 0)
4015                                 return;
4016                         cur.idx() = tabular.getFirstCellInRow(row);
4017                         cur.idx() = tabular.cellAbove(cur.idx());
4018                 } else {
4019                         if (tabular.isLastCell(cur.idx()))
4020                                 return;
4021                         ++cur.idx();
4022                 }
4023         } else {
4024                 if (cur.idx() == 0) // first cell
4025                         return;
4026                 --cur.idx();
4027         }
4028         cur.pit() = cur.lastpit();
4029         cur.pos() = cur.lastpos();
4030
4031         // in visual mode, place cursor at extreme left or right
4032         
4033         switch(entry_from) {
4034
4035         case ENTRY_DIRECTION_RIGHT:
4036                 cur.posVisToRowExtremity(false /* !left */);
4037                 break;
4038         case ENTRY_DIRECTION_LEFT:
4039                 cur.posVisToRowExtremity(true /* left */);
4040                 break;
4041         case ENTRY_DIRECTION_IGNORE:
4042                 // nothing to do in this case
4043                 break;
4044
4045         }
4046
4047         // FIXME: this accesses the position cache before it is initialized
4048         //resetPos(cur);
4049 }
4050
4051
4052 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4053 {
4054         Tabular::Feature action = Tabular::LAST_ACTION;
4055
4056         int i = 0;
4057         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4058                 string const tmp = tabularFeature[i].feature;
4059
4060                 if (tmp == what.substr(0, tmp.length())) {
4061                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4062                         //tabularFeatures[i].feature.length()))
4063                         action = tabularFeature[i].action;
4064                         break;
4065                 }
4066         }
4067         if (action == Tabular::LAST_ACTION)
4068                 return false;
4069
4070         string const val =
4071                 ltrim(what.substr(tabularFeature[i].feature.length()));
4072         tabularFeatures(cur, action, val);
4073         return true;
4074 }
4075
4076
4077 static void checkLongtableSpecial(Tabular::ltType & ltt,
4078                           string const & special, bool & flag)
4079 {
4080         if (special == "dl_above") {
4081                 ltt.topDL = flag;
4082                 ltt.set = false;
4083         } else if (special == "dl_below") {
4084                 ltt.bottomDL = flag;
4085                 ltt.set = false;
4086         } else if (special == "empty") {
4087                 ltt.empty = flag;
4088                 ltt.set = false;
4089         } else if (flag) {
4090                 ltt.empty = false;
4091                 ltt.set = true;
4092         }
4093 }
4094
4095 bool InsetTabular::oneCellHasRotationState(bool rotated,
4096                 row_type row_start, row_type row_end,
4097                 col_type col_start, col_type col_end) const {
4098
4099         for (row_type i = row_start; i <= row_end; ++i) {
4100                 for (col_type j = col_start; j <= col_end; ++j) {
4101                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4102                                 == rotated) {
4103                                 return true;
4104                         }
4105                 }
4106         }
4107         return false;
4108 }
4109
4110 void InsetTabular::tabularFeatures(Cursor & cur,
4111         Tabular::Feature feature, string const & value)
4112 {
4113         col_type sel_col_start;
4114         col_type sel_col_end;
4115         row_type sel_row_start;
4116         row_type sel_row_end;
4117         bool setLines = false;
4118         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4119         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4120
4121         switch (feature) {
4122
4123         case Tabular::M_ALIGN_LEFT:
4124         case Tabular::ALIGN_LEFT:
4125                 setAlign = LYX_ALIGN_LEFT;
4126                 break;
4127
4128         case Tabular::M_ALIGN_RIGHT:
4129         case Tabular::ALIGN_RIGHT:
4130                 setAlign = LYX_ALIGN_RIGHT;
4131                 break;
4132
4133         case Tabular::M_ALIGN_CENTER:
4134         case Tabular::ALIGN_CENTER:
4135                 setAlign = LYX_ALIGN_CENTER;
4136                 break;
4137
4138         case Tabular::ALIGN_BLOCK:
4139                 setAlign = LYX_ALIGN_BLOCK;
4140                 break;
4141
4142         case Tabular::M_VALIGN_TOP:
4143         case Tabular::VALIGN_TOP:
4144                 setVAlign = Tabular::LYX_VALIGN_TOP;
4145                 break;
4146
4147         case Tabular::M_VALIGN_BOTTOM:
4148         case Tabular::VALIGN_BOTTOM:
4149                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4150                 break;
4151
4152         case Tabular::M_VALIGN_MIDDLE:
4153         case Tabular::VALIGN_MIDDLE:
4154                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4155                 break;
4156
4157         default:
4158                 break;
4159         }
4160
4161         cur.recordUndoInset(ATOMIC_UNDO);
4162
4163         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4164         row_type const row = tabular.cellRow(cur.idx());
4165         col_type const column = tabular.cellColumn(cur.idx());
4166         bool flag = true;
4167         Tabular::ltType ltt;
4168
4169         switch (feature) {
4170
4171         case Tabular::SET_PWIDTH: {
4172                 Length const len(value);
4173                 tabular.setColumnPWidth(cur, cur.idx(), len);
4174                 if (len.zero()
4175                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4176                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4177                 break;
4178         }
4179
4180         case Tabular::SET_MPWIDTH:
4181                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4182                 break;
4183
4184         case Tabular::SET_SPECIAL_COLUMN:
4185         case Tabular::SET_SPECIAL_MULTI:
4186                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4187                 break;
4188
4189         case Tabular::APPEND_ROW:
4190                 // append the row into the tabular
4191                 tabular.appendRow(cur.idx());
4192                 break;
4193
4194         case Tabular::APPEND_COLUMN:
4195                 // append the column into the tabular
4196                 tabular.appendColumn(cur.idx());
4197                 cur.idx() = tabular.cellIndex(row, column);
4198                 break;
4199
4200         case Tabular::DELETE_ROW:
4201                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4202                         tabular.deleteRow(sel_row_start);
4203                 if (sel_row_start >= tabular.row_info.size())
4204                         --sel_row_start;
4205                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4206                 cur.pit() = 0;
4207                 cur.pos() = 0;
4208                 cur.selection() = false;
4209                 break;
4210
4211         case Tabular::DELETE_COLUMN:
4212                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4213                         tabular.deleteColumn(sel_col_start);
4214                 if (sel_col_start >= tabular.column_info.size())
4215                         --sel_col_start;
4216                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4217                 cur.pit() = 0;
4218                 cur.pos() = 0;
4219                 cur.selection() = false;
4220                 break;
4221
4222         case Tabular::COPY_ROW:
4223                 tabular.copyRow(row);
4224                 break;
4225
4226         case Tabular::COPY_COLUMN:
4227                 tabular.copyColumn(column);
4228                 cur.idx() = tabular.cellIndex(row, column);
4229                 break;
4230
4231         case Tabular::TOGGLE_LINE_TOP: {
4232                 bool lineSet = !tabular.topLine(cur.idx());
4233                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4234                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4235                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4236                 break;
4237         }
4238
4239         case Tabular::TOGGLE_LINE_BOTTOM: {
4240                 bool lineSet = !tabular.bottomLine(cur.idx());
4241                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4242                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4243                                 tabular.setBottomLine(tabular.cellIndex(i, j), lineSet);
4244                 break;
4245         }
4246
4247         case Tabular::TOGGLE_LINE_LEFT: {
4248                 bool lineSet = !tabular.leftLine(cur.idx());
4249                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4250                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4251                                 tabular.setLeftLine(tabular.cellIndex(i, j), lineSet);
4252                 break;
4253         }
4254
4255         case Tabular::TOGGLE_LINE_RIGHT: {
4256                 bool lineSet = !tabular.rightLine(cur.idx());
4257                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4258                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4259                                 tabular.setRightLine(tabular.cellIndex(i, j), lineSet);
4260                 break;
4261         }
4262
4263         case Tabular::M_ALIGN_LEFT:
4264         case Tabular::M_ALIGN_RIGHT:
4265         case Tabular::M_ALIGN_CENTER:
4266                 flag = false;
4267         case Tabular::ALIGN_LEFT:
4268         case Tabular::ALIGN_RIGHT:
4269         case Tabular::ALIGN_CENTER:
4270         case Tabular::ALIGN_BLOCK:
4271                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4272                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4273                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4274                 break;
4275
4276         case Tabular::M_VALIGN_TOP:
4277         case Tabular::M_VALIGN_BOTTOM:
4278         case Tabular::M_VALIGN_MIDDLE:
4279                 flag = false;
4280         case Tabular::VALIGN_TOP:
4281         case Tabular::VALIGN_BOTTOM:
4282         case Tabular::VALIGN_MIDDLE:
4283                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4284                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4285                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4286                 break;
4287
4288         case Tabular::MULTICOLUMN: {
4289                 if (!cur.selection()) {
4290                         // just multicol for one single cell
4291                         // check whether we are completely in a multicol
4292                         if (tabular.isMultiColumn(cur.idx()))
4293                                 tabular.unsetMultiColumn(cur.idx());
4294                         else
4295                                 tabular.setMultiColumn(cur.idx(), 1);
4296                         break;
4297                 }
4298                 // we have a selection so this means we just add all this
4299                 // cells to form a multicolumn cell
4300                 idx_type const s_start = cur.selBegin().idx();
4301                 idx_type const s_end = cur.selEnd().idx();
4302                 tabular.setMultiColumn(s_start, s_end - s_start + 1);
4303                 cur.idx() = s_start;
4304                 cur.pit() = 0;
4305                 cur.pos() = 0;
4306                 cur.selection() = false;
4307                 break;
4308         }
4309
4310         case Tabular::SET_ALL_LINES:
4311                 setLines = true;
4312         case Tabular::UNSET_ALL_LINES:
4313                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4314                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4315                                 tabular.setAllLines(
4316                                         tabular.cellIndex(i,j), setLines);
4317                 break;
4318
4319         case Tabular::SET_BORDER_LINES:
4320                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4321                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
4322                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
4323                 }
4324                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
4325                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
4326                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
4327                 }
4328                 break;
4329
4330         case Tabular::SET_LONGTABULAR:
4331                 tabular.is_long_tabular = true;
4332                 break;
4333
4334         case Tabular::UNSET_LONGTABULAR:
4335                 tabular.is_long_tabular = false;
4336                 break;
4337
4338         case Tabular::SET_ROTATE_TABULAR:
4339                 tabular.rotate = true;
4340                 break;
4341
4342         case Tabular::UNSET_ROTATE_TABULAR:
4343                 tabular.rotate = false;
4344                 break;
4345
4346         case Tabular::TOGGLE_ROTATE_TABULAR:
4347                 tabular.rotate = !tabular.rotate;
4348                 break;
4349
4350         case Tabular::SET_ROTATE_CELL:
4351                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4352                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4353                                 tabular.setRotateCell(
4354                                         tabular.cellIndex(i, j), true);
4355                 break;
4356
4357         case Tabular::UNSET_ROTATE_CELL:
4358                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4359                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4360                                 tabular.setRotateCell(tabular.cellIndex(i, j), false);
4361                 break;
4362
4363         case Tabular::TOGGLE_ROTATE_CELL:
4364                 {
4365                 bool oneNotRotated = oneCellHasRotationState(false,
4366                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4367
4368                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4369                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4370                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4371                                                                           oneNotRotated);
4372                 }
4373                 break;
4374
4375         case Tabular::SET_USEBOX: {
4376                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4377                 if (val == tabular.getUsebox(cur.idx()))
4378                         val = Tabular::BOX_NONE;
4379                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4380                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4381                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4382                 break;
4383         }
4384
4385         case Tabular::UNSET_LTFIRSTHEAD:
4386                 flag = false;
4387         case Tabular::SET_LTFIRSTHEAD:
4388                 tabular.getRowOfLTFirstHead(row, ltt);
4389                 checkLongtableSpecial(ltt, value, flag);
4390                 tabular.setLTHead(row, flag, ltt, true);
4391                 break;
4392
4393         case Tabular::UNSET_LTHEAD:
4394                 flag = false;
4395         case Tabular::SET_LTHEAD:
4396                 tabular.getRowOfLTHead(row, ltt);
4397                 checkLongtableSpecial(ltt, value, flag);
4398                 tabular.setLTHead(row, flag, ltt, false);
4399                 break;
4400
4401         case Tabular::UNSET_LTFOOT:
4402                 flag = false;
4403         case Tabular::SET_LTFOOT:
4404                 tabular.getRowOfLTFoot(row, ltt);
4405                 checkLongtableSpecial(ltt, value, flag);
4406                 tabular.setLTFoot(row, flag, ltt, false);
4407                 break;
4408
4409         case Tabular::UNSET_LTLASTFOOT:
4410                 flag = false;
4411         case Tabular::SET_LTLASTFOOT:
4412                 tabular.getRowOfLTLastFoot(row, ltt);
4413                 checkLongtableSpecial(ltt, value, flag);
4414                 tabular.setLTFoot(row, flag, ltt, true);
4415                 break;
4416
4417         case Tabular::SET_LTNEWPAGE:
4418                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4419                 break;
4420
4421         case Tabular::TOGGLE_LTCAPTION:
4422                 cur.idx() = tabular.setLTCaption(row, !tabular.ltCaption(row));
4423                 cur.pit() = 0;
4424                 cur.pos() = 0;
4425                 cur.selection() = false;
4426                 break;
4427
4428         case Tabular::SET_BOOKTABS:
4429                 tabular.use_booktabs = true;
4430                 break;
4431
4432         case Tabular::UNSET_BOOKTABS:
4433                 tabular.use_booktabs = false;
4434                 break;
4435
4436         case Tabular::SET_TOP_SPACE: {
4437                 Length len;
4438                 if (value == "default")
4439                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4440                                 tabular.row_info[i].top_space_default = true;
4441                 else if (isValidLength(value, &len))
4442                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4443                                 tabular.row_info[i].top_space_default = false;
4444                                 tabular.row_info[i].top_space = len;
4445                         }
4446                 else
4447                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4448                                 tabular.row_info[i].top_space_default = false;
4449                                 tabular.row_info[i].top_space = len;
4450                         }
4451                 break;
4452         }
4453
4454         case Tabular::SET_BOTTOM_SPACE: {
4455                 Length len;
4456                 if (value == "default")
4457                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4458                                 tabular.row_info[i].bottom_space_default = true;
4459                 else if (isValidLength(value, &len))
4460                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4461                                 tabular.row_info[i].bottom_space_default = false;
4462                                 tabular.row_info[i].bottom_space = len;
4463                         }
4464                 else
4465                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4466                                 tabular.row_info[i].bottom_space_default = false;
4467                                 tabular.row_info[i].bottom_space = len;
4468                         }
4469                 break;
4470         }
4471
4472         case Tabular::SET_INTERLINE_SPACE: {
4473                 Length len;
4474                 if (value == "default")
4475                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4476                                 tabular.row_info[i].interline_space_default = true;
4477                 else if (isValidLength(value, &len))
4478                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4479                                 tabular.row_info[i].interline_space_default = false;
4480                                 tabular.row_info[i].interline_space = len;
4481                         }
4482                 else
4483                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4484                                 tabular.row_info[i].interline_space_default = false;
4485                                 tabular.row_info[i].interline_space = len;
4486                         }
4487                 break;
4488         }
4489
4490         // dummy stuff just to avoid warnings
4491         case Tabular::LAST_ACTION:
4492                 break;
4493         }
4494 }
4495
4496
4497 bool InsetTabular::showInsetDialog(BufferView * bv) const
4498 {
4499         bv->showDialog("tabular", params2string(*this),
4500                 const_cast<InsetTabular *>(this));
4501         return true;
4502 }
4503
4504
4505 void InsetTabular::openLayoutDialog(BufferView * bv) const
4506 {
4507         bv->showDialog("tabular", params2string(*this),
4508                 const_cast<InsetTabular *>(this));
4509 }
4510
4511
4512 bool InsetTabular::copySelection(Cursor & cur)
4513 {
4514         if (!cur.selection())
4515                 return false;
4516
4517         row_type rs, re;
4518         col_type cs, ce;
4519         getSelection(cur, rs, re, cs, ce);
4520
4521         paste_tabular.reset(new Tabular(tabular));
4522
4523         for (row_type i = 0; i < rs; ++i)
4524                 paste_tabular->deleteRow(0);
4525
4526         row_type const rows = re - rs + 1;
4527         while (paste_tabular->row_info.size() > rows)
4528                 paste_tabular->deleteRow(rows);
4529
4530         for (col_type i = 0; i < cs; ++i)
4531                 paste_tabular->deleteColumn(0);
4532
4533         col_type const columns = ce - cs + 1;
4534         while (paste_tabular->column_info.size() > columns)
4535                 paste_tabular->deleteColumn(columns);
4536
4537         paste_tabular->setBuffer(tabular.buffer());
4538
4539         odocstringstream os;
4540         OutputParams const runparams(0);
4541         paste_tabular->plaintext(os, runparams, 0, true, '\t');
4542         // Needed for the "Edit->Paste recent" menu and the system clipboard.
4543         cap::copySelection(cur, os.str());
4544
4545         // mark tabular stack dirty
4546         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
4547         // when we (hopefully) have a one-for-all paste mechanism.
4548         // This must be called after cap::copySelection.
4549         dirtyTabularStack(true);
4550
4551         return true;
4552 }
4553
4554
4555 bool InsetTabular::pasteClipboard(Cursor & cur)
4556 {
4557         if (!paste_tabular)
4558                 return false;
4559         col_type const actcol = tabular.cellColumn(cur.idx());
4560         row_type const actrow = tabular.cellRow(cur.idx());
4561         for (row_type r1 = 0, r2 = actrow;
4562              r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
4563              ++r1, ++r2) {
4564                 for (col_type c1 = 0, c2 = actcol;
4565                     c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
4566                     ++c1, ++c2) {
4567                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
4568                             tabular.isPartOfMultiColumn(r2, c2))
4569                                 continue;
4570                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
4571                                 --c2;
4572                                 continue;
4573                         }
4574                         if (tabular.isPartOfMultiColumn(r2, c2)) {
4575                                 --c1;
4576                                 continue;
4577                         }
4578                         shared_ptr<InsetTableCell> inset(
4579                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
4580                         tabular.setCellInset(r2, c2, inset);
4581                         // FIXME: change tracking (MG)
4582                         inset->setChange(Change(cur.buffer().params().trackChanges ?
4583                                                 Change::INSERTED : Change::UNCHANGED));
4584                         cur.pos() = 0;
4585                 }
4586         }
4587         return true;
4588 }
4589
4590
4591 void InsetTabular::cutSelection(Cursor & cur)
4592 {
4593         if (!cur.selection())
4594                 return;
4595
4596         row_type rs, re;
4597         col_type cs, ce;
4598         getSelection(cur, rs, re, cs, ce);
4599         for (row_type i = rs; i <= re; ++i) {
4600                 for (col_type j = cs; j <= ce; ++j) {
4601                         shared_ptr<InsetTableCell> t
4602                                 = cell(tabular.cellIndex(i, j));
4603                         if (cur.buffer().params().trackChanges)
4604                                 // FIXME: Change tracking (MG)
4605                                 t->setChange(Change(Change::DELETED));
4606                         else
4607                                 t->clear();
4608                 }
4609         }
4610
4611         // cursor position might be invalid now
4612         if (cur.pit() > cur.lastpit())
4613                 cur.pit() = cur.lastpit();
4614         if (cur.pos() > cur.lastpos())
4615                 cur.pos() = cur.lastpos();
4616         cur.clearSelection();
4617 }
4618
4619
4620 bool InsetTabular::isRightToLeft(Cursor & cur) const
4621 {
4622         LASSERT(cur.depth() > 1, /**/);
4623         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
4624         pos_type const parentpos = cur[cur.depth() - 2].pos();
4625         return parentpar.getFontSettings(cur.bv().buffer().params(),
4626                                          parentpos).language()->rightToLeft();
4627 }
4628
4629
4630 void InsetTabular::getSelection(Cursor & cur,
4631         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
4632 {
4633         CursorSlice const & beg = cur.selBegin();
4634         CursorSlice const & end = cur.selEnd();
4635         cs = tabular.cellColumn(beg.idx());
4636         ce = tabular.cellColumn(end.idx());
4637         if (cs > ce) {
4638                 ce = cs;
4639                 cs = tabular.cellColumn(end.idx());
4640         } else {
4641                 ce = tabular.cellRightColumn(end.idx());
4642         }
4643
4644         rs = tabular.cellRow(beg.idx());
4645         re = tabular.cellRow(end.idx());
4646         if (rs > re)
4647                 swap(rs, re);
4648 }
4649
4650
4651 Text * InsetTabular::getText(int idx) const
4652 {
4653         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
4654 }
4655
4656
4657 void InsetTabular::setChange(Change const & change)
4658 {
4659         for (idx_type idx = 0; idx < nargs(); ++idx)
4660                 cell(idx)->setChange(change);
4661 }
4662
4663
4664 void InsetTabular::acceptChanges(BufferParams const & bparams)
4665 {
4666         for (idx_type idx = 0; idx < nargs(); ++idx)
4667                 cell(idx)->acceptChanges(bparams);
4668 }
4669
4670
4671 void InsetTabular::rejectChanges(BufferParams const & bparams)
4672 {
4673         for (idx_type idx = 0; idx < nargs(); ++idx)
4674                 cell(idx)->rejectChanges(bparams);
4675 }
4676
4677
4678 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
4679 {
4680         return tabular.getPWidth(cell).zero();
4681 }
4682
4683
4684 bool InsetTabular::forcePlainLayout(idx_type cell) const
4685 {
4686         return !tabular.getPWidth(cell).zero();
4687 }
4688
4689
4690 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
4691                                      bool usePaste)
4692 {
4693         if (buf.length() <= 0)
4694                 return true;
4695
4696         col_type cols = 1;
4697         row_type rows = 1;
4698         col_type maxCols = 1;
4699         size_t const len = buf.length();
4700         size_t p = 0;
4701
4702         while (p < len &&
4703                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
4704                 switch (buf[p]) {
4705                 case '\t':
4706                         ++cols;
4707                         break;
4708                 case '\n':
4709                         if (p + 1 < len)
4710                                 ++rows;
4711                         maxCols = max(cols, maxCols);
4712                         cols = 1;
4713                         break;
4714                 }
4715                 ++p;
4716         }
4717         maxCols = max(cols, maxCols);
4718         Tabular * loctab;
4719         idx_type cell = 0;
4720         col_type ocol = 0;
4721         row_type row = 0;
4722         if (usePaste) {
4723                 paste_tabular.reset(new Tabular(buffer(), rows, maxCols));
4724                 loctab = paste_tabular.get();
4725                 cols = 0;
4726                 dirtyTabularStack(true);
4727         } else {
4728                 loctab = &tabular;
4729                 cell = bv.cursor().idx();
4730                 ocol = tabular.cellColumn(cell);
4731                 row = tabular.cellRow(cell);
4732         }
4733
4734         size_t op = 0;
4735         idx_type const cells = loctab->numberofcells;
4736         p = 0;
4737         cols = ocol;
4738         rows = loctab->row_info.size();
4739         col_type const columns = loctab->column_info.size();
4740
4741         while (cell < cells && p < len && row < rows &&
4742                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
4743         {
4744                 if (p >= len)
4745                         break;
4746                 switch (buf[p]) {
4747                 case '\t':
4748                         // we can only set this if we are not too far right
4749                         if (cols < columns) {
4750                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
4751                                 Font const font = bv.textMetrics(&inset->text_).
4752                                         displayFont(0, 0);
4753                                 inset->setText(buf.substr(op, p - op), font,
4754                                                buffer().params().trackChanges);
4755                                 ++cols;
4756                                 ++cell;
4757                         }
4758                         break;
4759                 case '\n':
4760                         // we can only set this if we are not too far right
4761                         if (cols < columns) {
4762                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
4763                                 Font const font = bv.textMetrics(&inset->text_).
4764                                         displayFont(0, 0);
4765                                 inset->setText(buf.substr(op, p - op), font,
4766                                                buffer().params().trackChanges);
4767                         }
4768                         cols = ocol;
4769                         ++row;
4770                         if (row < rows)
4771                                 cell = loctab->cellIndex(row, cols);
4772                         break;
4773                 }
4774                 ++p;
4775                 op = p;
4776         }
4777         // check for the last cell if there is no trailing '\n'
4778         if (cell < cells && op < len) {
4779                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
4780                 Font const font = bv.textMetrics(&inset->text_).displayFont(0, 0);
4781                 inset->setText(buf.substr(op, len - op), font,
4782                         buffer().params().trackChanges);
4783         }
4784         return true;
4785 }
4786
4787
4788 void InsetTabular::addPreview(PreviewLoader & loader) const
4789 {
4790         row_type const rows = tabular.row_info.size();
4791         col_type const columns = tabular.column_info.size();
4792         for (row_type i = 0; i < rows; ++i) {
4793                 for (col_type j = 0; j < columns; ++j)
4794                         tabular.cellInset(i, j)->addPreview(loader);
4795         }
4796 }
4797
4798
4799 bool InsetTabular::tablemode(Cursor & cur) const
4800 {
4801         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
4802 }
4803
4804
4805 bool InsetTabular::completionSupported(Cursor const & cur) const
4806 {
4807         Cursor const & bvCur = cur.bv().cursor();
4808         if (&bvCur.inset() != this)
4809                 return false;
4810         return cur.text()->completionSupported(cur);
4811 }
4812
4813
4814 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
4815 {
4816         return completionSupported(cur);
4817 }
4818
4819
4820 bool InsetTabular::automaticInlineCompletion() const
4821 {
4822         return lyxrc.completion_inline_text;
4823 }
4824
4825
4826 bool InsetTabular::automaticPopupCompletion() const
4827 {
4828         return lyxrc.completion_popup_text;
4829 }
4830
4831
4832 bool InsetTabular::showCompletionCursor() const
4833 {
4834         return lyxrc.completion_cursor_text;
4835 }
4836
4837
4838 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
4839 {
4840         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
4841 }
4842
4843
4844 docstring InsetTabular::completionPrefix(Cursor const & cur) const
4845 {
4846         if (!completionSupported(cur))
4847                 return docstring();
4848         return cur.text()->completionPrefix(cur);
4849 }
4850
4851
4852 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
4853 {
4854         if (!completionSupported(cur))
4855                 return false;
4856
4857         return cur.text()->insertCompletion(cur, s, finished);
4858 }
4859
4860
4861 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
4862                                     Dimension & dim) const
4863 {
4864         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
4865         tm.completionPosAndDim(cur, x, y, dim);
4866 }
4867
4868
4869 void InsetTabular::string2params(string const & in, InsetTabular & inset)
4870 {
4871         istringstream data(in);
4872         Lexer lex;
4873         lex.setStream(data);
4874
4875         if (in.empty())
4876                 return;
4877
4878         string token;
4879         lex >> token;
4880         if (!lex || token != "tabular") {
4881                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
4882                 return;
4883         }
4884
4885         // This is part of the inset proper that is usually swallowed
4886         // by Buffer::readInset
4887         lex >> token;
4888         if (!lex || token != "Tabular") {
4889                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
4890                 return;
4891         }
4892
4893         inset.read(lex);
4894 }
4895
4896
4897 string InsetTabular::params2string(InsetTabular const & inset)
4898 {
4899         ostringstream data;
4900         data << "tabular" << ' ';
4901         inset.write(data);
4902         data << "\\end_inset\n";
4903         return data.str();
4904 }
4905
4906
4907 } // namespace lyx