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