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