]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
4eb85c6df570933dadbdd2ef3758cf37a775a26b
[lyx.git] / src / insets / insettext.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1998-2001 The LyX Team.
7  *
8  * ======================================================
9  */
10
11 #include <config.h>
12
13 #ifdef __GNUG__
14 #pragma implementation
15 #endif
16
17 #include "insettext.h"
18 #include "paragraph.h"
19 #include "lyxlex.h"
20 #include "debug.h"
21 #include "lyxfont.h"
22 #include "commandtags.h"
23 #include "buffer.h"
24 #include "LyXView.h"
25 #include "BufferView.h"
26 #include "lyxtextclasslist.h"
27 #include "LaTeXFeatures.h"
28 #include "Painter.h"
29 #include "lyxtext.h"
30 #include "lyxcursor.h"
31 #include "CutAndPaste.h"
32 #include "font.h"
33 #include "LColor.h"
34 #include "lyxrow.h"
35 #include "lyxrc.h"
36 #include "intl.h"
37 #include "trans_mgr.h"
38 #include "lyxscreen.h"
39 #include "gettext.h"
40 #include "lyxfunc.h"
41 #include "ParagraphParameters.h"
42 #include "undo_funcs.h"
43 #include "lyxfind.h"
44
45 #include "frontends/Alert.h"
46 #include "frontends/Dialogs.h"
47
48 #include "support/textutils.h"
49 #include "support/LAssert.h"
50 #include "support/lstrings.h"
51 #include "support/lyxalgo.h" // lyx::count
52
53 #include <fstream>
54 #include <algorithm>
55 #include <cstdlib>
56 //#include <csignal>
57
58 using std::ostream;
59 using std::ifstream;
60 using std::endl;
61 using std::min;
62 using std::max;
63 using std::make_pair;
64 using std::vector;
65 using std::pair;
66
67 using lyx::pos_type;
68 using lyx::textclass_type;
69
70 extern unsigned char getCurrentTextClass(Buffer *);
71 extern bool math_insert_greek(BufferView *, char);
72 extern int greek_kb_flag;
73
74
75 // These functions should probably go into bufferview_funcs somehow (Jug)
76
77 void InsetText::saveLyXTextState(LyXText * t) const
78 {
79         // check if my paragraphs are still valid
80         Paragraph * p = par;
81         while (p) {
82                 if (p == t->cursor.par())
83                         break;
84                 p = p->next();
85         }
86
87         if (p && t->cursor.pos() <= p->size()) {
88                 sstate.lpar = t->cursor.par();
89                 sstate.pos = t->cursor.pos();
90                 sstate.boundary = t->cursor.boundary();
91                 sstate.selstartpar = t->selection.start.par();
92                 sstate.selstartpos = t->selection.start.pos();
93                 sstate.selstartboundary = t->selection.start.boundary();
94                 sstate.selendpar = t->selection.end.par();
95                 sstate.selendpos = t->selection.end.pos();
96                 sstate.selendboundary = t->selection.end.boundary();
97                 sstate.selection = t->selection.set();
98                 sstate.mark_set = t->selection.mark();
99                 sstate.refresh = t->refresh_row != 0;
100         } else {
101                 sstate.lpar = 0;
102         }
103 }
104
105 void InsetText::restoreLyXTextState(BufferView * bv, LyXText * t) const
106 {
107         if (sstate.lpar) {
108                 t->selection.set(true);
109                 /* at this point just to avoid the Delete-Empty-Paragraph
110                  * Mechanism when setting the cursor */
111                 t->selection.mark(sstate.mark_set);
112                 if (sstate.selection) {
113                         t->setCursor(bv, sstate.selstartpar, sstate.selstartpos,
114                                      true, sstate.selstartboundary);
115                         t->selection.cursor = t->cursor;
116                         t->setCursor(bv, sstate.selendpar, sstate.selendpos,
117                                      true, sstate.selendboundary);
118                         t->setSelection(bv);
119                         t->setCursor(bv, sstate.lpar, sstate.pos);
120                 } else {
121                         t->setCursor(bv, sstate.lpar, sstate.pos, true, sstate.boundary);
122                         t->selection.cursor = t->cursor;
123                         t->selection.set(false);
124                 }
125                 if (sstate.refresh) {
126                 }
127         }
128 }
129
130
131 InsetText::InnerCache::InnerCache(boost::shared_ptr<LyXText> t)
132 {
133         text = t;
134         remove = false;
135 }
136
137
138 InsetText::InsetText(BufferParams const & bp)
139         : UpdatableInset(), lt(0), in_update(false), do_resize(0),
140           do_reinit(false)
141 {
142         par = new Paragraph;
143         par->layout(textclasslist[bp.textclass].defaultLayoutName());
144
145         init();
146 }
147
148
149 InsetText::InsetText(InsetText const & in, bool same_id)
150         : UpdatableInset(in, same_id), lt(0), in_update(false), do_resize(0),
151           do_reinit(false)
152 {
153         par = 0;
154         init(&in, same_id);
155 }
156
157
158 InsetText & InsetText::operator=(InsetText const & it)
159 {
160         init(&it);
161         return * this;
162 }
163
164
165 void InsetText::init(InsetText const * ins, bool same_id)
166 {
167         if (ins) {
168                 setParagraphData(ins->par, same_id);
169                 autoBreakRows = ins->autoBreakRows;
170                 drawFrame_ = ins->drawFrame_;
171                 frame_color = ins->frame_color;
172                 if (same_id)
173                         id_ = ins->id_;
174         } else {
175                 Paragraph * p = par;
176                 while (p) {
177                         p->setInsetOwner(this);
178                         p = p->next();
179                 }
180                 the_locking_inset = 0;
181                 drawFrame_ = NEVER;
182                 frame_color = LColor::insetframe;
183                 autoBreakRows = false;
184         }
185         top_y = 0;
186         insetAscent = 0;
187         insetDescent = 0;
188         insetWidth = 0;
189         old_max_width = 0;
190         no_selection = false;
191         need_update = FULL;
192         drawTextXOffset = 0;
193         drawTextYOffset = 0;
194         xpos = 0.0;
195         locked = false;
196         old_par = 0;
197         last_drawn_width = -1;
198         frame_is_visible = false;
199         cached_bview = 0;
200         sstate.lpar = 0;
201         in_insetAllowed = false;
202 }
203
204
205 InsetText::~InsetText()
206 {
207         cached_bview = 0;
208
209         // NOTE
210
211         while (par) {
212                 Paragraph * tmp = par->next();
213                 delete par;
214                 par = tmp;
215         }
216 }
217
218
219 void InsetText::clear()
220 {
221         // This is a gross hack...
222         string old_layout = par->layout();
223
224         while (par) {
225                 Paragraph * tmp = par->next();
226                 delete par;
227                 par = tmp;
228         }
229         par = new Paragraph;
230         par->setInsetOwner(this);
231         par->layout(old_layout);
232
233         reinitLyXText();
234         need_update = INIT;
235 }
236
237
238 Inset * InsetText::clone(Buffer const &, bool same_id) const
239 {
240         return new InsetText(*this, same_id);
241 }
242
243
244 void InsetText::write(Buffer const * buf, ostream & os) const
245 {
246         os << "Text\n";
247         writeParagraphData(buf, os);
248 }
249
250
251 void InsetText::writeParagraphData(Buffer const * buf, ostream & os) const
252 {
253         par->writeFile(buf, os, buf->params, 0);
254 }
255
256
257 void InsetText::read(Buffer const * buf, LyXLex & lex)
258 {
259         string token;
260         int pos = 0;
261         Paragraph * return_par = 0;
262         Paragraph::depth_type depth = 0;
263         LyXFont font(LyXFont::ALL_INHERIT);
264
265         clear();
266
267         while (lex.isOK()) {
268                 lex.nextToken();
269                 token = lex.getString();
270                 if (token.empty())
271                         continue;
272                 if (token == "\\end_inset") {
273 #ifndef NO_COMPABILITY
274                         const_cast<Buffer*>(buf)->insertErtContents(par, pos, false);
275 #endif
276                         break;
277                 }
278
279                 if (const_cast<Buffer*>(buf)->
280                         parseSingleLyXformat2Token(lex, par, return_par,
281                                                    token, pos, depth, font)) {
282                         // the_end read this should NEVER happen
283                         lex.printError("\\the_end read in inset! Error in document!");
284                         return;
285                 }
286         }
287         if (!return_par)
288                 return_par = par;
289         par = return_par;
290         while (return_par) {
291                 return_par->setInsetOwner(this);
292                 return_par = return_par->next();
293         }
294
295         if (token != "\\end_inset") {
296                 lex.printError("Missing \\end_inset at this point. "
297                                            "Read: `$$Token'");
298         }
299         need_update = FULL;
300 }
301
302
303 int InsetText::ascent(BufferView * bv, LyXFont const &) const
304 {
305         insetAscent = getLyXText(bv)->firstRow()->ascent_of_text() +
306                 TEXT_TO_INSET_OFFSET;
307         return insetAscent;
308 }
309
310
311 int InsetText::descent(BufferView * bv, LyXFont const &) const
312 {
313         LyXText * llt = getLyXText(bv);
314         insetDescent = llt->height - llt->firstRow()->ascent_of_text() +
315                 TEXT_TO_INSET_OFFSET;
316         return insetDescent;
317 }
318
319
320 int InsetText::width(BufferView * bv, LyXFont const &) const
321 {
322         insetWidth = max(textWidth(bv), (int)getLyXText(bv)->width) +
323                 (2 * TEXT_TO_INSET_OFFSET);
324         insetWidth = max(insetWidth, 10);
325         return insetWidth;
326 }
327
328
329 int InsetText::textWidth(BufferView * bv, bool fordraw) const
330 {
331         int w;
332         if (!autoBreakRows) {
333                 w = -1;
334         } else {
335                 w = getMaxWidth(bv, this);
336         }
337         if (fordraw) {
338                 return max(w - (2 * TEXT_TO_INSET_OFFSET),
339                            (int)getLyXText(bv)->width);
340         } else if (w < 0) {
341             return -1;
342         }
343         return w - (2 * TEXT_TO_INSET_OFFSET);
344 }
345
346
347 void InsetText::draw(BufferView * bv, LyXFont const & f,
348                      int baseline, float & x, bool cleared) const
349 {
350         if (nodraw())
351                 return;
352
353         Painter & pain = bv->painter();
354
355         // this is the first thing we have to ask because if the x pos
356         // changed we have to do a complete rebreak of the text as we
357         // may have few space to draw in. Well we should check on this too
358         int old_x = top_x;
359         if (top_x != int(x)) {
360                 top_x = int(x);
361                 topx_set = true;
362                 int nw = getMaxWidth(bv, this);
363                 if (nw > 0 && old_max_width != nw) {
364                         need_update = INIT;
365                         old_max_width = nw;
366                         bv->text->status(bv, LyXText::CHANGED_IN_DRAW);
367                         return;
368                 }
369         }
370
371         // call these methods so that insetWidth, insetAscent and
372         // insetDescent have the right values.
373         width(bv, f);
374         ascent(bv, f);
375         descent(bv, f);
376
377         // repaint the background if needed
378         if (cleared && backgroundColor() != LColor::background) {
379                 clearInset(bv, baseline, cleared);
380         }
381
382         // no draw is necessary !!!
383         if ((drawFrame_ == LOCKED) && !locked && !par->size()) {
384                 top_baseline = baseline;
385                 x += width(bv, f);
386                 if (need_update & CLEAR_FRAME)
387                         clearFrame(pain, cleared);
388                 need_update = NONE;
389                 return;
390         }
391
392         xpos = x;
393         if (!owner())
394                 x += static_cast<float>(scroll());
395
396         // if top_x differs we did it already
397         if (!cleared && (old_x == int(x))
398             && ((need_update&(INIT|FULL)) || (top_baseline != baseline)
399                 ||(last_drawn_width != insetWidth)))
400         {
401                 // Condition necessary to eliminate bug 59 attachment 37
402                 if (baseline > 0)
403                         clearInset(bv, baseline, cleared);
404         }
405
406         if (cleared)
407                 frame_is_visible = false;
408
409         if (!cleared && (need_update == NONE)) {
410                 if (locked)
411                         drawFrame(pain, cleared);
412                 return;
413         }
414
415         top_baseline = baseline;
416         top_y = baseline - insetAscent;
417
418         if (last_drawn_width != insetWidth) {
419                 if (!cleared)
420                         clearInset(bv, baseline, cleared);
421                 need_update |= FULL;
422                 last_drawn_width = insetWidth;
423         }
424
425         if (the_locking_inset && (cpar(bv) == inset_par)
426                 && (cpos(bv) == inset_pos)) {
427                 inset_x = cx(bv) - top_x + drawTextXOffset;
428                 inset_y = cy(bv) + drawTextYOffset;
429         }
430         if (!cleared && (need_update == CURSOR)
431             && !getLyXText(bv)->selection.set()) {
432                 drawFrame(pain, cleared);
433                 x += insetWidth;
434                 need_update = NONE;
435                 return;
436         }
437         bool clear = false;
438         if (!lt) {
439                 lt = getLyXText(bv);
440                 clear = true;
441         }
442         x += TEXT_TO_INSET_OFFSET;
443
444         Row * row = lt->firstRow();
445         int y_offset = baseline - row->ascent_of_text();
446         int ph = pain.paperHeight();
447         int first = 0;
448         int y = y_offset;
449         while ((row != 0) && ((y+row->height()) <= 0)) {
450                 y += row->height();
451                 first += row->height();
452                 row = row->next();
453         }
454         if (y_offset < 0)
455                 y_offset = y;
456         lt->first_y = first;
457         if (cleared || (need_update&(INIT|FULL))) {
458                 int yf = y_offset;
459                 y = 0;
460                 while ((row != 0) && (yf < ph)) {
461                         lt->getVisibleRow(bv, y+y_offset, int(x), row,
462                                                 y+first, cleared);
463                         y += row->height();
464                         yf += row->height();
465                         row = row->next();
466                 }
467         } else if (!locked) {
468                 if (need_update & CURSOR) {
469                         bv->screen()->toggleSelection(lt, bv, true, y_offset,int(x));
470                         lt->clearSelection();
471                         lt->selection.cursor = lt->cursor;
472                 }
473                 bv->screen()->update(lt, bv, y_offset, int(x));
474         } else {
475                 locked = false;
476                 if (need_update & SELECTION) {
477                         bv->screen()->toggleToggle(lt, bv, y_offset, int(x));
478                 } else if (need_update & CURSOR) {
479                         bv->screen()->toggleSelection(lt, bv, true, y_offset,int(x));
480                         lt->clearSelection();
481                         lt->selection.cursor = lt->cursor;
482                 }
483                 bv->screen()->update(lt, bv, y_offset, int(x));
484                 locked = true;
485         }
486
487         lt->refresh_y = 0;
488         lt->status(bv, LyXText::UNCHANGED);
489         if ((drawFrame_ == ALWAYS) ||
490                 ((cleared || (need_update != CURSOR_PAR)) &&
491                  (drawFrame_ == LOCKED) && locked))
492         {
493                 drawFrame(pain, cleared);
494         } else if (need_update & CLEAR_FRAME) {
495                 clearFrame(pain, cleared);
496         }
497
498         x += insetWidth - TEXT_TO_INSET_OFFSET;
499
500         if (bv->text->status() == LyXText::CHANGED_IN_DRAW) {
501                 need_update |= FULL;
502         } else if (need_update != INIT) {
503                 need_update = NONE;
504         }
505         if (clear)
506                 lt = 0;
507 }
508
509
510 void InsetText::drawFrame(Painter & pain, bool cleared) const
511 {
512         static int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
513         if (!frame_is_visible || cleared) {
514                 frame_x = top_x + ttoD2;
515                 frame_y = top_baseline - insetAscent + ttoD2;
516                 frame_w = insetWidth - TEXT_TO_INSET_OFFSET;
517                 frame_h = insetAscent + insetDescent - TEXT_TO_INSET_OFFSET;
518                 pain.rectangle(frame_x, frame_y, frame_w, frame_h,
519                                frame_color);
520                 frame_is_visible = true;
521         }
522 }
523
524
525 void InsetText::clearFrame(Painter & pain, bool cleared) const
526 {
527         if (frame_is_visible) {
528                 if (!cleared) {
529                         pain.rectangle(frame_x, frame_y, frame_w, frame_h,
530                                        backgroundColor());
531                 }
532                 frame_is_visible = false;
533         }
534 }
535
536
537 void InsetText::update(BufferView * bv, LyXFont const & font, bool reinit)
538 {
539         if (in_update) {
540                 if (reinit && owner()) {
541                         reinitLyXText();
542                         owner()->update(bv, font, true);
543                 }
544                 return;
545         }
546         in_update = true;
547         if (reinit || need_update == INIT) {
548                 need_update = FULL;
549                 // we should put this call where we set need_update to INIT!
550                 reinitLyXText();
551                 if (owner())
552                         owner()->update(bv, font, true);
553                 in_update = false;
554                 return;
555         }
556
557         if (!autoBreakRows && par->next())
558                 collapseParagraphs(bv->buffer()->params);
559
560         if (the_locking_inset) {
561                 inset_x = cx(bv) - top_x + drawTextXOffset;
562                 inset_y = cy(bv) + drawTextYOffset;
563                 the_locking_inset->update(bv, font, reinit);
564         }
565
566         bool clear = false;
567         if (!lt) {
568                 lt = getLyXText(bv);
569                 clear = true;
570         }
571         if ((need_update & CURSOR_PAR) && (lt->status() == LyXText::UNCHANGED) &&
572                 the_locking_inset)
573         {
574                 lt->updateInset(bv, the_locking_inset);
575         }
576         if (lt->status() == LyXText::NEED_MORE_REFRESH)
577                 need_update |= FULL;
578         if (clear)
579                 lt = 0;
580         in_update = false;
581 }
582
583
584 void InsetText::setUpdateStatus(BufferView * bv, int what) const
585 {
586         // this does nothing dangerous so use only a localized buffer
587         LyXText * llt = getLyXText(bv);
588
589         need_update |= what;
590         // we have to redraw us full if our LyXText NEEDS_MORE_REFRES or
591         // if we don't break row so that we only have one row to update!
592         if ((llt->status() == LyXText::NEED_MORE_REFRESH) ||
593             (!autoBreakRows &&
594              (llt->status() == LyXText::NEED_VERY_LITTLE_REFRESH)))
595         {
596                 need_update |= FULL;
597         } else if (llt->status() == LyXText::NEED_VERY_LITTLE_REFRESH) {
598                 need_update |= CURSOR_PAR;
599         }
600
601         // this to not draw a selection when we redraw all of it!
602         if (need_update & CURSOR && !(need_update & SELECTION)) {
603                 if (llt->selection.set())
604                         need_update = FULL;
605                 llt->clearSelection();
606         }
607 }
608
609
610 void InsetText::updateLocal(BufferView * bv, int what, bool mark_dirty) const
611 {
612         if (!autoBreakRows && par->next())
613                 collapseParagraphs(bv->buffer()->params);
614         bool clear = false;
615         if (!lt) {
616                 lt = getLyXText(bv);
617                 clear = true;
618         }
619         lt->fullRebreak(bv);
620         setUpdateStatus(bv, what);
621         bool flag = (((need_update != CURSOR) && (need_update != NONE)) ||
622                      (lt->status() != LyXText::UNCHANGED) || lt->selection.set());
623         if (!lt->selection.set())
624                 lt->selection.cursor = lt->cursor;
625         if (clear)
626                 lt = 0;
627         if (flag)
628                 bv->updateInset(const_cast<InsetText *>(this), mark_dirty);
629         else
630                 bv->fitCursor();
631
632         if (need_update == CURSOR)
633                 need_update = NONE;
634         bv->owner()->showState();
635         bv->owner()->updateMenubar();
636         bv->owner()->updateToolbar();
637         if (old_par != cpar(bv)) {
638                 bv->owner()->setLayout(cpar(bv)->layout());
639                 old_par = cpar(bv);
640         }
641 }
642
643
644 string const InsetText::editMessage() const
645 {
646         return _("Opened Text Inset");
647 }
648
649
650 void InsetText::edit(BufferView * bv, int x, int y, unsigned int button)
651 {
652         UpdatableInset::edit(bv, x, y, button);
653
654         if (!bv->lockInset(this)) {
655                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
656                 return;
657         }
658         locked = true;
659         the_locking_inset = 0;
660         inset_pos = inset_x = inset_y = 0;
661         inset_boundary = false;
662         inset_par = 0;
663         old_par = 0;
664         int tmp_y = (y < 0) ? 0 : y;
665         bool clear = false;
666         if (!lt) {
667                 lt = getLyXText(bv);
668                 clear = true;
669         }
670         if (!checkAndActivateInset(bv, x, tmp_y, button))
671                 lt->setCursorFromCoordinates(bv, x - drawTextXOffset,
672                                             y + insetAscent);
673         lt->clearSelection();
674         finishUndo();
675         // If the inset is empty set the language of the current font to the
676         // language to the surronding text (if different).
677         if (par->size() == 0 && !par->next() &&
678                 bv->getParentLanguage(this) != lt->current_font.language())
679         {
680                 LyXFont font(LyXFont::ALL_IGNORE);
681                 font.setLanguage(bv->getParentLanguage(this));
682                 setFont(bv, font, false);
683         }
684 //      showInsetCursor(bv);
685         if (clear)
686                 lt = 0;
687
688         int code = CURSOR;
689         if (drawFrame_ == LOCKED)
690                 code = CURSOR|DRAW_FRAME;
691         updateLocal(bv, code, false);
692
693         // Tell the paragraph dialog that we've entered an insettext.
694         bv->owner()->getDialogs()->updateParagraph();
695 }
696
697
698 void InsetText::edit(BufferView * bv, bool front)
699 {
700         UpdatableInset::edit(bv, front);
701
702         if (!bv->lockInset(this)) {
703                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
704                 return;
705         }
706         locked = true;
707         the_locking_inset = 0;
708         inset_pos = inset_x = inset_y = 0;
709         inset_boundary = false;
710         inset_par = 0;
711         old_par = 0;
712         bool clear = false;
713         if (!lt) {
714                 lt = getLyXText(bv);
715                 clear = true;
716         }
717         if (front)
718                 lt->setCursor(bv, par, 0);
719         else {
720                 Paragraph * p = par;
721                 while (p->next())
722                         p = p->next();
723 //              int const pos = (p->size() ? p->size()-1 : p->size());
724                 lt->setCursor(bv, p, p->size());
725         }
726         lt->clearSelection();
727         finishUndo();
728         // If the inset is empty set the language of the current font to the
729         // language to the surronding text (if different).
730         if (par->size() == 0 && !par->next() &&
731                 bv->getParentLanguage(this) != lt->current_font.language()) {
732                 LyXFont font(LyXFont::ALL_IGNORE);
733                 font.setLanguage(bv->getParentLanguage(this));
734                 setFont(bv, font, false);
735         }
736 //      showInsetCursor(bv);
737         if (clear)
738                 lt = 0;
739         int code = CURSOR;
740         if (drawFrame_ == LOCKED)
741                 code = CURSOR|DRAW_FRAME;
742         updateLocal(bv, code, false);
743 }
744
745
746 void InsetText::insetUnlock(BufferView * bv)
747 {
748         if (the_locking_inset) {
749                 the_locking_inset->insetUnlock(bv);
750                 the_locking_inset = 0;
751         }
752         hideInsetCursor(bv);
753         no_selection = false;
754         locked = false;
755         int code;
756         if (drawFrame_ == LOCKED)
757                 code = CURSOR|CLEAR_FRAME;
758         else
759                 code = CURSOR;
760         bool clear = false;
761         if (!lt) {
762                 lt = getLyXText(bv);
763                 clear = true;
764         }
765         if (lt->selection.set()) {
766                 lt->clearSelection();
767                 code = FULL;
768         } else if (owner()) {
769                 bv->owner()->setLayout(owner()->getLyXText(bv)
770                                        ->cursor.par()->layout());
771         } else
772                 bv->owner()->setLayout(bv->text->cursor.par()->layout());
773         // hack for deleteEmptyParMech
774         if (par->size()) {
775                 lt->setCursor(bv, par, 0);
776         } else if (par->next()) {
777                 lt->setCursor(bv, par->next(), 0);
778         }
779         if (clear)
780                 lt = 0;
781         updateLocal(bv, code, false);
782 }
783
784 void InsetText::lockInset(BufferView * bv, UpdatableInset * inset)
785 {
786         the_locking_inset = inset;
787         inset_x = cx(bv) - top_x + drawTextXOffset;
788         inset_y = cy(bv) + drawTextYOffset;
789         inset_pos = cpos(bv);
790         inset_par = cpar(bv);
791         inset_boundary = cboundary(bv);
792         updateLocal(bv, CURSOR, false);
793 }
794
795
796 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
797 {
798         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
799                               << inset << "): ";
800         if (!inset)
801                 return false;
802         if (!the_locking_inset) {
803                 Paragraph * p = par;
804                 int const id = inset->id();
805                 while(p) {
806                         Paragraph::inset_iterator it =
807                                 p->inset_iterator_begin();
808                         Paragraph::inset_iterator const end =
809                                 p->inset_iterator_end();
810                         for (; it != end; ++it) {
811                                 if ((*it) == inset) {
812                                         getLyXText(bv)->setCursorIntern(bv, p, it.getPos());
813                                         lockInset(bv, inset);
814                                         return true;
815                                 }
816                                 if ((*it)->getInsetFromID(id)) {
817                                         getLyXText(bv)->setCursorIntern(bv, p, it.getPos());
818                                         (*it)->edit(bv);
819                                         return the_locking_inset->lockInsetInInset(bv, inset);
820                                 }
821                         }
822                         p = p->next();
823                 }
824                 return false;
825         }
826         if (inset == cpar(bv)->getInset(cpos(bv))) {
827                 lyxerr[Debug::INSETS] << "OK" << endl;
828                 lockInset(bv, inset);
829                 return true;
830         } else if (the_locking_inset && (the_locking_inset == inset)) {
831                 if (cpar(bv) == inset_par && cpos(bv) == inset_pos) {
832                         lyxerr[Debug::INSETS] << "OK" << endl;
833                         inset_x = cx(bv) - top_x + drawTextXOffset;
834                         inset_y = cy(bv) + drawTextYOffset;
835                 } else {
836                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
837                 }
838         } else if (the_locking_inset) {
839                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
840                 return the_locking_inset->lockInsetInInset(bv, inset);
841         }
842         lyxerr[Debug::INSETS] << "NOT OK" << endl;
843         return false;
844 }
845
846
847 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
848                                    bool lr)
849 {
850         if (!the_locking_inset)
851                 return false;
852         if (the_locking_inset == inset) {
853                 the_locking_inset->insetUnlock(bv);
854                 getLyXText(bv)->updateInset(bv, inset);
855                 the_locking_inset = 0;
856                 if (lr)
857                         moveRight(bv, false);
858                 old_par = 0; // force layout setting
859                 if (scroll())
860                         scroll(bv, 0.0F);
861                 else
862                         updateLocal(bv, CURSOR, false);
863                 return true;
864         }
865         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
866 }
867
868
869 bool InsetText::updateInsetInInset(BufferView * bv, Inset * inset)
870 {
871         if (!autoBreakRows && par->next())
872                 collapseParagraphs(bv->buffer()->params);
873         if (inset == this)
874                 return true;
875         bool clear = false;
876         if (!lt) {
877                 lt = getLyXText(bv);
878                 clear = true;
879         }
880         if (inset->owner() != this) {
881                 int ustat = CURSOR_PAR;
882                 bool found = false;
883                 UpdatableInset * tl_inset = the_locking_inset;
884                 if (tl_inset)
885                         found = tl_inset->updateInsetInInset(bv, inset);
886                 if (!found) {
887                         tl_inset = static_cast<UpdatableInset *>(inset);
888                         while(tl_inset->owner() && tl_inset->owner() != this)
889                                 tl_inset = static_cast<UpdatableInset *>(tl_inset->owner());
890                         if (!tl_inset->owner())
891                                 return false;
892                         found = tl_inset->updateInsetInInset(bv, inset);
893                         ustat = FULL;
894                 }
895                 if (found)
896                         lt->updateInset(bv, tl_inset);
897                 if (clear)
898                         lt = 0;
899                 if (found)
900                         setUpdateStatus(bv, ustat);
901                 return found;
902         }
903         bool found = lt->updateInset(bv, inset);
904         if (clear)
905                 lt = 0;
906         if (found) {
907                 setUpdateStatus(bv, CURSOR_PAR);
908                 if (the_locking_inset &&
909                     cpar(bv) == inset_par && cpos(bv) == inset_pos)
910                 {
911                         inset_x = cx(bv) - top_x + drawTextXOffset;
912                         inset_y = cy(bv) + drawTextYOffset;
913                 }
914         }
915         return found;
916 }
917
918
919 void InsetText::insetButtonPress(BufferView * bv, int x, int y, int button)
920 {
921         no_selection = true;
922
923         // use this to check mouse motion for selection!
924         mouse_x = x;
925         mouse_y = y;
926
927         int tmp_x = x - drawTextXOffset;
928         int tmp_y = y + insetAscent - getLyXText(bv)->first_y;
929         Inset * inset = bv->checkInsetHit(getLyXText(bv), tmp_x, tmp_y);
930
931         hideInsetCursor(bv);
932         if (the_locking_inset) {
933                 if (the_locking_inset == inset) {
934                         the_locking_inset->insetButtonPress(bv,
935                                                             x - inset_x,
936                                                             y - inset_y,
937                                                             button);
938                         no_selection = false;
939                         return;
940                 } else if (inset) {
941                         // otherwise unlock the_locking_inset and lock the new inset
942                         the_locking_inset->insetUnlock(bv);
943                         inset_x = cx(bv) - top_x + drawTextXOffset;
944                         inset_y = cy(bv) + drawTextYOffset;
945                         the_locking_inset = 0;
946                         inset->insetButtonPress(bv, x - inset_x,
947                                                 y - inset_y, button);
948 //                      inset->edit(bv, x - inset_x, y - inset_y, button);
949                         if (the_locking_inset)
950                                 updateLocal(bv, CURSOR, false);
951                         no_selection = false;
952                         return;
953                 }
954                 // otherwise only unlock the_locking_inset
955                 the_locking_inset->insetUnlock(bv);
956                 the_locking_inset = 0;
957         }
958         if (bv->theLockingInset()) {
959                 if (isHighlyEditableInset(inset)) {
960                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
961                         inset_x = cx(bv) - top_x + drawTextXOffset;
962                         inset_y = cy(bv) + drawTextYOffset;
963                         inset_pos = cpos(bv);
964                         inset_par = cpar(bv);
965                         inset_boundary = cboundary(bv);
966                         the_locking_inset = uinset;
967                         uinset->insetButtonPress(bv, x - inset_x, y - inset_y,
968                                                  button);
969                         uinset->edit(bv, x - inset_x, y - inset_y, 0);
970                         if (the_locking_inset)
971                                 updateLocal(bv, CURSOR, false);
972                         no_selection = false;
973                         return;
974                 }
975         }
976         if (!inset) { // && (button == 2)) {
977                 bool paste_internally = false;
978                 if ((button == 2) && getLyXText(bv)->selection.set()) {
979                         localDispatch(bv, LFUN_COPY, "");
980                         paste_internally = true;
981                 }
982                 bool clear = false;
983                 if (!lt) {
984                         lt = getLyXText(bv);
985                         clear = true;
986                 }
987
988                 lt->setCursorFromCoordinates(bv, x - drawTextXOffset,
989                                              y + insetAscent);
990                 // set the selection cursor!
991                 lt->selection.cursor = lt->cursor;
992                 lt->cursor.x_fix(lt->cursor.x());
993
994                 if (lt->selection.set()) {
995                         lt->clearSelection();
996                         if (clear)
997                                 lt = 0;
998                         updateLocal(bv, FULL, false);
999                 } else {
1000                         lt->clearSelection();
1001                         if (clear)
1002                                 lt = 0;
1003                         updateLocal(bv, CURSOR, false);
1004                 }
1005                 bv->owner()->setLayout(cpar(bv)->layout());
1006                 old_par = cpar(bv);
1007                 // Insert primary selection with middle mouse
1008                 // if there is a local selection in the current buffer,
1009                 // insert this
1010                 if (button == 2) {
1011                         if (paste_internally)
1012                                 localDispatch(bv, LFUN_PASTE, "");
1013                         else
1014                                 localDispatch(bv, LFUN_PASTESELECTION,
1015                                               "paragraph");
1016                 }
1017         } else {
1018                 getLyXText(bv)->clearSelection();
1019         }
1020         showInsetCursor(bv);
1021         no_selection = false;
1022 }
1023
1024
1025 bool InsetText::insetButtonRelease(BufferView * bv, int x, int y, int button)
1026 {
1027         if (the_locking_inset) {
1028                 return the_locking_inset->insetButtonRelease(bv,
1029                                                              x - inset_x, y - inset_y,
1030                                                              button);
1031         }
1032         int tmp_x = x - drawTextXOffset;
1033         int tmp_y = y + insetAscent - getLyXText(bv)->first_y;
1034         Inset * inset = bv->checkInsetHit(getLyXText(bv), tmp_x, tmp_y);
1035         bool ret = false;
1036         if (inset) {
1037                 if (isHighlyEditableInset(inset)) {
1038                         ret = inset->insetButtonRelease(bv, x - inset_x,
1039                                                         y - inset_y, button);
1040                 } else {
1041                         inset_x = cx(bv) - top_x + drawTextXOffset;
1042                         inset_y = cy(bv) + drawTextYOffset;
1043                         ret = inset->insetButtonRelease(bv, x - inset_x,
1044                                                         y - inset_y, button);
1045                         inset->edit(bv, x - inset_x,
1046                                     y - inset_y, button);
1047                 }
1048                 updateLocal(bv, CURSOR_PAR, false);
1049         }
1050         return ret;
1051 }
1052
1053
1054 void InsetText::insetMotionNotify(BufferView * bv, int x, int y, int state)
1055 {
1056         if (no_selection || ((mouse_x == x) && (mouse_y == y)))
1057                 return;
1058         if (the_locking_inset) {
1059                 the_locking_inset->insetMotionNotify(bv, x - inset_x,
1060                                                      y - inset_y,state);
1061                 return;
1062         }
1063         bool clear = false;
1064         if (!lt) {
1065                 lt = getLyXText(bv);
1066                 clear = true;
1067         }
1068         hideInsetCursor(bv);
1069         LyXCursor cur = lt->cursor;
1070         lt->setCursorFromCoordinates(bv, x - drawTextXOffset, y + insetAscent);
1071         if (cur == lt->cursor) {
1072                 if (clear)
1073                         lt = 0;
1074                 return;
1075         }
1076         lt->setSelection(bv);
1077         bool flag = (lt->toggle_cursor.par() != lt->toggle_end_cursor.par() ||
1078                                  lt->toggle_cursor.pos() != lt->toggle_end_cursor.pos());
1079         if (clear)
1080                 lt = 0;
1081         if (flag) {
1082                 updateLocal(bv, SELECTION, false);
1083         }
1084         showInsetCursor(bv);
1085 }
1086
1087
1088 void InsetText::insetKeyPress(XKeyEvent * xke)
1089 {
1090         if (the_locking_inset) {
1091                 the_locking_inset->insetKeyPress(xke);
1092                 return;
1093         }
1094 }
1095
1096
1097 UpdatableInset::RESULT
1098 InsetText::localDispatch(BufferView * bv,
1099                          kb_action action, string const & arg)
1100 {
1101         bool was_empty = par->size() == 0 && !par->next();
1102         no_selection = false;
1103         UpdatableInset::RESULT
1104                 result= UpdatableInset::localDispatch(bv, action, arg);
1105         if (result != UNDISPATCHED) {
1106                 return DISPATCHED;
1107         }
1108
1109         result = DISPATCHED;
1110         if ((action < 0) && arg.empty())
1111                 return FINISHED;
1112
1113         if (the_locking_inset) {
1114                 result = the_locking_inset->localDispatch(bv, action, arg);
1115                 if (result == DISPATCHED_NOUPDATE)
1116                         return result;
1117                 else if (result == DISPATCHED) {
1118                         updateLocal(bv, CURSOR_PAR, false);
1119                         return result;
1120                 } else if (result >= FINISHED) {
1121                         switch (result) {
1122                         case FINISHED_RIGHT:
1123                                 moveRightIntern(bv, false, false);
1124                                 result = DISPATCHED;
1125                                 break;
1126                         case FINISHED_UP:
1127                                 if ((result = moveUp(bv)) >= FINISHED) {
1128                                         updateLocal(bv, CURSOR, false);
1129                                         bv->unlockInset(this);
1130                                 }
1131                                 break;
1132                         case FINISHED_DOWN:
1133                                 if ((result = moveDown(bv)) >= FINISHED) {
1134                                         updateLocal(bv, CURSOR, false);
1135                                         bv->unlockInset(this);
1136                                 }
1137                                 break;
1138                         default:
1139                                 result = DISPATCHED;
1140                                 break;
1141                         }
1142                         the_locking_inset = 0;
1143 #ifdef WITH_WARNINGS
1144 #warning I changed this to always return Dispatched maybe it is wrong (20011001 Jug)
1145 #endif
1146                         return result;
1147                 }
1148         }
1149         hideInsetCursor(bv);
1150         bool clear = false;
1151         if (!lt) {
1152                 lt = getLyXText(bv);
1153                 clear = true;
1154         }
1155         int updwhat = 0;
1156         int updflag = false;
1157         switch (action) {
1158         // Normal chars
1159         case LFUN_SELFINSERT:
1160                 if (bv->buffer()->isReadonly()) {
1161 //          setErrorMessage(N_("Document is read only"));
1162                         break;
1163                 }
1164                 if (!arg.empty()) {
1165                         /* Automatically delete the currently selected
1166                          * text and replace it with what is being
1167                          * typed in now. Depends on lyxrc settings
1168                          * "auto_region_delete", which defaults to
1169                          * true (on). */
1170
1171                         setUndo(bv, Undo::INSERT,
1172                                 lt->cursor.par(), lt->cursor.par()->next());
1173                         bv->setState();
1174                         if (lyxrc.auto_region_delete) {
1175                                 if (lt->selection.set()) {
1176                                         lt->cutSelection(bv, false);
1177                                 }
1178                         }
1179                         lt->clearSelection();
1180                         for (string::size_type i = 0; i < arg.length(); ++i) {
1181                                 bv->owner()->getIntl()->getTrans().TranslateAndInsert(arg[i], lt);
1182                         }
1183                 }
1184                 lt->selection.cursor = lt->cursor;
1185                 updwhat = CURSOR_PAR;
1186                 updflag = true;
1187                 result = DISPATCHED_NOUPDATE;
1188                 break;
1189                 // --- Cursor Movements -----------------------------------
1190         case LFUN_RIGHTSEL:
1191                 finishUndo();
1192                 moveRight(bv, false, true);
1193                 lt->setSelection(bv);
1194                 updwhat = SELECTION;
1195                 break;
1196         case LFUN_RIGHT:
1197                 result = moveRight(bv);
1198                 finishUndo();
1199                 updwhat = CURSOR;
1200                 break;
1201         case LFUN_LEFTSEL:
1202                 finishUndo();
1203                 moveLeft(bv, false, true);
1204                 lt->setSelection(bv);
1205                 updwhat = SELECTION;
1206                 break;
1207         case LFUN_LEFT:
1208                 finishUndo();
1209                 result = moveLeft(bv);
1210                 updwhat = CURSOR;
1211                 break;
1212         case LFUN_DOWNSEL:
1213                 finishUndo();
1214                 moveDown(bv);
1215                 lt->setSelection(bv);
1216                 updwhat = SELECTION;
1217                 break;
1218         case LFUN_DOWN:
1219                 finishUndo();
1220                 result = moveDown(bv);
1221                 updwhat = CURSOR;
1222                 break;
1223         case LFUN_UPSEL:
1224                 finishUndo();
1225                 moveUp(bv);
1226                 lt->setSelection(bv);
1227                 updwhat = SELECTION;
1228                 break;
1229         case LFUN_UP:
1230                 finishUndo();
1231                 result = moveUp(bv);
1232                 updwhat = CURSOR;
1233                 break;
1234         case LFUN_HOME:
1235                 finishUndo();
1236                 lt->cursorHome(bv);
1237                 updwhat = CURSOR;
1238                 break;
1239         case LFUN_END:
1240                 lt->cursorEnd(bv);
1241                 updwhat = CURSOR;
1242                 break;
1243         case LFUN_BACKSPACE: {
1244                 setUndo(bv, Undo::DELETE,
1245                         lt->cursor.par(), lt->cursor.par()->next());
1246                 if (lt->selection.set())
1247                         lt->cutSelection(bv);
1248                 else
1249                         lt->backspace(bv);
1250                 updwhat = CURSOR_PAR;
1251                 updflag = true;
1252         }
1253         break;
1254
1255         case LFUN_DELETE: {
1256                 setUndo(bv, Undo::DELETE,
1257                         lt->cursor.par(), lt->cursor.par()->next());
1258                 if (lt->selection.set()) {
1259                         lt->cutSelection(bv);
1260                 } else {
1261                         lt->Delete(bv);
1262                 }
1263                 updwhat = CURSOR_PAR;
1264                 updflag = true;
1265         }
1266         break;
1267
1268         case LFUN_CUT: {
1269                 setUndo(bv, Undo::DELETE,
1270                         lt->cursor.par(), lt->cursor.par()->next());
1271                 lt->cutSelection(bv);
1272                 updwhat = CURSOR_PAR;
1273                 updflag = true;
1274         }
1275         break;
1276
1277         case LFUN_COPY:
1278                 finishUndo();
1279                 lt->copySelection(bv);
1280                 updwhat = CURSOR_PAR;
1281                 break;
1282         case LFUN_PASTESELECTION:
1283         {
1284                 string const clip(bv->getClipboard());
1285
1286                 if (clip.empty())
1287                         break;
1288                 if (arg == "paragraph") {
1289                         lt->insertStringAsParagraphs(bv, clip);
1290                 } else {
1291                         lt->insertStringAsLines(bv, clip);
1292                 }
1293                 updwhat = CURSOR_PAR;
1294                 updflag = true;
1295                 break;
1296         }
1297         case LFUN_PASTE: {
1298                 if (!autoBreakRows) {
1299
1300                         if (CutAndPaste::nrOfParagraphs() > 1) {
1301                                 Alert::alert(_("Impossible operation"),
1302                                                    _("Cannot include more than one paragraph!"),
1303                                                    _("Sorry."));
1304                                 break;
1305                         }
1306                 }
1307                 setUndo(bv, Undo::INSERT,
1308                         lt->cursor.par(), lt->cursor.par()->next());
1309                 lt->pasteSelection(bv);
1310                 updwhat = CURSOR_PAR;
1311                 updflag = true;
1312         }
1313         break;
1314
1315         case LFUN_BREAKPARAGRAPH:
1316                 if (!autoBreakRows) {
1317                         result = DISPATCHED;
1318                         break;
1319                 }
1320                 lt->breakParagraph(bv, 0);
1321                 updwhat = FULL;
1322                 updflag = true;
1323                 break;
1324         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1325                 if (!autoBreakRows) {
1326                         result = DISPATCHED;
1327                         break;
1328                 }
1329                 lt->breakParagraph(bv, 1);
1330                 updwhat = FULL;
1331                 updflag = true;
1332                 break;
1333
1334         case LFUN_BREAKLINE: {
1335                 if (!autoBreakRows) {
1336                         result = DISPATCHED;
1337                         break;
1338                 }
1339                 setUndo(bv, Undo::INSERT,
1340                         lt->cursor.par(), lt->cursor.par()->next());
1341                 lt->insertChar(bv, Paragraph::META_NEWLINE);
1342                 updwhat = CURSOR_PAR;
1343                 updflag = true;
1344         }
1345         break;
1346
1347         case LFUN_LAYOUT:
1348                 // do not set layouts on non breakable textinsets
1349                 if (autoBreakRows) {
1350                         string cur_layout = cpar(bv)->layout();
1351
1352                         // Derive layout number from given argument (string)
1353                         // and current buffer's textclass (number). */
1354                         textclass_type tclass = bv->buffer()->params.textclass;
1355                         string layout = arg;
1356                         bool hasLayout = textclasslist[tclass].hasLayout(layout);
1357
1358                         // If the entry is obsolete, use the new one instead.
1359                         if (hasLayout) {
1360                                 string const & obs =
1361                                         textclasslist[tclass][layout].
1362                                         obsoleted_by();
1363                                 if (!obs.empty())
1364                                         layout = obs;
1365                         }
1366
1367                         // see if we found the layout number:
1368                         if (!hasLayout) {
1369                                 string const msg = string(N_("Layout ")) + arg + N_(" not known");
1370                                 bv->owner()->getLyXFunc()->dispatch(LFUN_MESSAGE, msg);
1371                                 break;
1372                         }
1373
1374                         if (cur_layout != layout) {
1375                                 cur_layout = layout;
1376                                 lt->setLayout(bv, layout);
1377                                 bv->owner()->setLayout(cpar(bv)->layout());
1378                                 updwhat = CURSOR_PAR;
1379                                 updflag = true;
1380                         }
1381                 } else {
1382                         // reset the layout box
1383                         bv->owner()->setLayout(cpar(bv)->layout());
1384                 }
1385                 break;
1386         case LFUN_PARAGRAPH_SPACING:
1387                 // This one is absolutely not working. When fiddling with this
1388                 // it also seems to me that the paragraphs inside the insettext
1389                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1390         {
1391                 Paragraph * par = lt->cursor.par();
1392                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
1393                 float cur_value = 1.0;
1394                 if (cur_spacing == Spacing::Other) {
1395                         cur_value = par->params().spacing().getValue();
1396                 }
1397
1398                 istringstream istr(arg.c_str());
1399                 string tmp;
1400                 istr >> tmp;
1401                 Spacing::Space new_spacing = cur_spacing;
1402                 float new_value = cur_value;
1403                 if (tmp.empty()) {
1404                         lyxerr << "Missing argument to `paragraph-spacing'"
1405                                    << endl;
1406                 } else if (tmp == "single") {
1407                         new_spacing = Spacing::Single;
1408                 } else if (tmp == "onehalf") {
1409                         new_spacing = Spacing::Onehalf;
1410                 } else if (tmp == "double") {
1411                         new_spacing = Spacing::Double;
1412                 } else if (tmp == "other") {
1413                         new_spacing = Spacing::Other;
1414                         float tmpval = 0.0;
1415                         istr >> tmpval;
1416                         lyxerr << "new_value = " << tmpval << endl;
1417                         if (tmpval != 0.0)
1418                                 new_value = tmpval;
1419                 } else if (tmp == "default") {
1420                         new_spacing = Spacing::Default;
1421                 } else {
1422                         lyxerr << _("Unknown spacing argument: ")
1423                                    << arg << endl;
1424                 }
1425                 if (cur_spacing != new_spacing || cur_value != new_value) {
1426                         par->params().spacing(Spacing(new_spacing, new_value));
1427                         updwhat = CURSOR_PAR;
1428                         updflag = true;
1429                 }
1430         }
1431         break;
1432
1433         default:
1434                 if (!bv->Dispatch(action, arg))
1435                         result = UNDISPATCHED;
1436                 break;
1437         }
1438
1439         if (clear)
1440                 lt = 0;
1441         if (updwhat > 0)
1442                 updateLocal(bv, updwhat, updflag);
1443         /// If the action has deleted all text in the inset, we need to change the
1444         // language to the language of the surronding text.
1445         if (!was_empty && par->size() == 0 && !par->next()) {
1446                 LyXFont font(LyXFont::ALL_IGNORE);
1447                 font.setLanguage(bv->getParentLanguage(this));
1448                 setFont(bv, font, false);
1449         }
1450
1451         if (result >= FINISHED)
1452                 bv->unlockInset(this);
1453         return result;
1454 }
1455
1456
1457 int InsetText::latex(Buffer const * buf, ostream & os, bool, bool) const
1458 {
1459         TexRow texrow;
1460         buf->latexParagraphs(os, par, 0, texrow);
1461         return texrow.rows();
1462 }
1463
1464
1465 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1466 {
1467         Paragraph * p = par;
1468         unsigned int lines = 0;
1469
1470         while (p) {
1471                 string const tmp = buf->asciiParagraph(p, linelen, p->previous()==0);
1472                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1473                 os << tmp;
1474                 p = p->next();
1475         }
1476         return lines;
1477 }
1478
1479
1480 int InsetText::docbook(Buffer const * buf, ostream & os) const
1481 {
1482         Paragraph * p = par;
1483         unsigned int lines = 0;
1484
1485         vector<string> environment_stack(10);
1486         vector<string> environment_inner(10);
1487
1488         int const command_depth = 0;
1489         string item_name;
1490
1491         Paragraph::depth_type depth = 0; // paragraph depth
1492
1493         while (p) {
1494                 string sgmlparam;
1495                 int desc_on = 0; // description mode
1496
1497                 LyXLayout const & style =
1498                         textclasslist[buf->params.textclass][p->layout()];
1499
1500                 // environment tag closing
1501                 for (; depth > p->params().depth(); --depth) {
1502                         if (environment_inner[depth] != "!-- --") {
1503                                 item_name = "listitem";
1504                                 buf->sgmlCloseTag(os, command_depth + depth,
1505                                              item_name);
1506                                 if (environment_inner[depth] == "varlistentry")
1507                                         buf->sgmlCloseTag(os, depth+command_depth,
1508                                                      environment_inner[depth]);
1509                         }
1510                         buf->sgmlCloseTag(os, depth + command_depth,
1511                                      environment_stack[depth]);
1512                         environment_stack[depth].erase();
1513                         environment_inner[depth].erase();
1514                 }
1515
1516                 if (depth == p->params().depth()
1517                    && environment_stack[depth] != style.latexname()
1518                    && !environment_stack[depth].empty()) {
1519                         if (environment_inner[depth] != "!-- --") {
1520                                 item_name= "listitem";
1521                                 buf->sgmlCloseTag(os, command_depth+depth,
1522                                                   item_name);
1523                                 if (environment_inner[depth] == "varlistentry")
1524                                         buf->sgmlCloseTag(os,
1525                                                           depth + command_depth,
1526                                                           environment_inner[depth]);
1527                         }
1528
1529                         buf->sgmlCloseTag(os, depth + command_depth,
1530                                           environment_stack[depth]);
1531
1532                         environment_stack[depth].erase();
1533                         environment_inner[depth].erase();
1534                 }
1535
1536                 // Write opening SGML tags.
1537                 switch (style.latextype) {
1538                 case LATEX_PARAGRAPH:
1539                         buf->sgmlOpenTag(os, depth + command_depth,
1540                                          style.latexname());
1541                         break;
1542
1543                 case LATEX_COMMAND:
1544                         buf->sgmlError(p, 0,
1545                                        _("Error : LatexType Command not allowed here.\n"));
1546                         return -1;
1547                         break;
1548
1549                 case LATEX_ENVIRONMENT:
1550                 case LATEX_ITEM_ENVIRONMENT:
1551                         if (depth < p->params().depth()) {
1552                                 depth = p->params().depth();
1553                                 environment_stack[depth].erase();
1554                         }
1555
1556                         if (environment_stack[depth] != style.latexname()) {
1557                                 if (environment_stack.size() == depth + 1) {
1558                                         environment_stack.push_back("!-- --");
1559                                         environment_inner.push_back("!-- --");
1560                                 }
1561                                 environment_stack[depth] = style.latexname();
1562                                 environment_inner[depth] = "!-- --";
1563                                 buf->sgmlOpenTag(os, depth + command_depth,
1564                                                  environment_stack[depth]);
1565                         } else {
1566                                 if (environment_inner[depth] != "!-- --") {
1567                                         item_name= "listitem";
1568                                         buf->sgmlCloseTag(os,
1569                                                           command_depth + depth,
1570                                                           item_name);
1571                                         if (environment_inner[depth] == "varlistentry")
1572                                                 buf->sgmlCloseTag(os,
1573                                                                   depth + command_depth,
1574                                                                   environment_inner[depth]);
1575                                 }
1576                         }
1577
1578                         if (style.latextype == LATEX_ENVIRONMENT) {
1579                                 if (!style.latexparam().empty()) {
1580                                         if (style.latexparam() == "CDATA")
1581                                                 os << "<![CDATA[";
1582                                         else
1583                                                 buf->sgmlOpenTag(os, depth + command_depth,
1584                                                                  style.latexparam());
1585                                 }
1586                                 break;
1587                         }
1588
1589                         desc_on = (style.labeltype == LABEL_MANUAL);
1590
1591                         if (desc_on)
1592                                 environment_inner[depth]= "varlistentry";
1593                         else
1594                                 environment_inner[depth]= "listitem";
1595
1596                         buf->sgmlOpenTag(os, depth + 1 + command_depth,
1597                                          environment_inner[depth]);
1598
1599                         if (desc_on) {
1600                                 item_name= "term";
1601                                 buf->sgmlOpenTag(os, depth + 1 + command_depth,
1602                                                  item_name);
1603                         } else {
1604                                 item_name= "para";
1605                                 buf->sgmlOpenTag(os, depth + 1 + command_depth,
1606                                                  item_name);
1607                         }
1608                         break;
1609                 default:
1610                         buf->sgmlOpenTag(os, depth + command_depth,
1611                                          style.latexname());
1612                         break;
1613                 }
1614
1615                 buf->simpleDocBookOnePar(os, p, desc_on,
1616                                          depth + 1 + command_depth);
1617                 p = p->next();
1618
1619                 string end_tag;
1620                 // write closing SGML tags
1621                 switch (style.latextype) {
1622                 case LATEX_ENVIRONMENT:
1623                         if (!style.latexparam().empty()) {
1624                                 if (style.latexparam() == "CDATA")
1625                                         os << "]]>";
1626                                 else
1627                                         buf->sgmlCloseTag(os, depth + command_depth,
1628                                                           style.latexparam());
1629                         }
1630                         break;
1631                 case LATEX_ITEM_ENVIRONMENT:
1632                         if (desc_on == 1) break;
1633                         end_tag= "para";
1634                         buf->sgmlCloseTag(os, depth + 1 + command_depth, end_tag);
1635                         break;
1636                 case LATEX_PARAGRAPH:
1637                         buf->sgmlCloseTag(os, depth + command_depth, style.latexname());
1638                         break;
1639                 default:
1640                         buf->sgmlCloseTag(os, depth + command_depth, style.latexname());
1641                         break;
1642                 }
1643         }
1644
1645         // Close open tags
1646         for (int d = depth; d >= 0; --d) {
1647                 if (!environment_stack[depth].empty()) {
1648                         if (environment_inner[depth] != "!-- --") {
1649                                 item_name = "listitem";
1650                                 buf->sgmlCloseTag(os, command_depth + depth,
1651                                                   item_name);
1652                                if (environment_inner[depth] == "varlistentry")
1653                                        buf->sgmlCloseTag(os, depth + command_depth,
1654                                                          environment_inner[depth]);
1655                         }
1656
1657                         buf->sgmlCloseTag(os, depth + command_depth,
1658                                           environment_stack[depth]);
1659                 }
1660         }
1661
1662         return lines;
1663 }
1664
1665
1666 void InsetText::validate(LaTeXFeatures & features) const
1667 {
1668         Paragraph * p = par;
1669         while (p) {
1670                 p->validate(features);
1671                 p = p->next();
1672         }
1673 }
1674
1675
1676 int InsetText::beginningOfMainBody(Buffer const * buf, Paragraph * p) const
1677 {
1678         if (textclasslist[buf->params.textclass][p->layout()].labeltype != LABEL_MANUAL)
1679                 return 0;
1680         else
1681                 return p->beginningOfMainBody();
1682 }
1683
1684
1685 void InsetText::getCursorPos(BufferView * bv,
1686                              int & x, int & y) const
1687 {
1688         if (the_locking_inset) {
1689                 the_locking_inset->getCursorPos(bv, x, y);
1690                 return;
1691         }
1692         x = cx(bv);
1693         y = cy(bv);
1694 }
1695
1696
1697 unsigned int InsetText::insetInInsetY()
1698 {
1699         if (!the_locking_inset)
1700                 return 0;
1701
1702         return (inset_y + the_locking_inset->insetInInsetY());
1703 }
1704
1705
1706 void InsetText::toggleInsetCursor(BufferView * bv)
1707 {
1708         if (the_locking_inset) {
1709                 the_locking_inset->toggleInsetCursor(bv);
1710                 return;
1711         }
1712
1713         LyXFont const font(getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv)));
1714
1715         int const asc = lyxfont::maxAscent(font);
1716         int const desc = lyxfont::maxDescent(font);
1717
1718         if (isCursorVisible())
1719                 bv->hideLockedInsetCursor();
1720         else
1721                 bv->showLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1722         toggleCursorVisible();
1723 }
1724
1725
1726 void InsetText::showInsetCursor(BufferView * bv, bool show)
1727 {
1728         if (the_locking_inset) {
1729                 the_locking_inset->showInsetCursor(bv, show);
1730                 return;
1731         }
1732         if (!isCursorVisible()) {
1733                 LyXFont const font =
1734                         getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1735
1736                 int const asc = lyxfont::maxAscent(font);
1737                 int const desc = lyxfont::maxDescent(font);
1738
1739                 bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1740                 if (show)
1741                         bv->showLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1742                 setCursorVisible(true);
1743         }
1744 }
1745
1746
1747 void InsetText::hideInsetCursor(BufferView * bv)
1748 {
1749         if (isCursorVisible()) {
1750                 bv->hideLockedInsetCursor();
1751                 setCursorVisible(false);
1752         }
1753         if (the_locking_inset)
1754                 the_locking_inset->hideInsetCursor(bv);
1755 }
1756
1757
1758 void InsetText::fitInsetCursor(BufferView * bv) const
1759 {
1760         if (the_locking_inset) {
1761                 the_locking_inset->fitInsetCursor(bv);
1762                 return;
1763         }
1764         LyXFont const font =
1765                 getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1766
1767         int const asc = lyxfont::maxAscent(font);
1768         int const desc = lyxfont::maxDescent(font);
1769
1770         bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1771 }
1772
1773
1774 UpdatableInset::RESULT
1775 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1776 {
1777         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1778                 return moveLeftIntern(bv, false, activate_inset, selecting);
1779         else
1780                 return moveRightIntern(bv, false, activate_inset, selecting);
1781 }
1782
1783
1784 UpdatableInset::RESULT
1785 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1786 {
1787         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1788                 return moveRightIntern(bv, true, activate_inset, selecting);
1789         else
1790                 return moveLeftIntern(bv, true, activate_inset, selecting);
1791 }
1792
1793
1794 UpdatableInset::RESULT
1795 InsetText::moveRightIntern(BufferView * bv, bool behind,
1796                            bool activate_inset, bool selecting)
1797 {
1798         if (!cpar(bv)->next() && (cpos(bv) >= cpar(bv)->size()))
1799                 return FINISHED_RIGHT;
1800         if (activate_inset && checkAndActivateInset(bv, behind))
1801                 return DISPATCHED;
1802         getLyXText(bv)->cursorRight(bv);
1803         if (!selecting)
1804                 getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
1805         return DISPATCHED_NOUPDATE;
1806 }
1807
1808
1809 UpdatableInset::RESULT
1810 InsetText::moveLeftIntern(BufferView * bv, bool behind,
1811                           bool activate_inset, bool selecting)
1812 {
1813         if (!cpar(bv)->previous() && (cpos(bv) <= 0))
1814                 return FINISHED;
1815         getLyXText(bv)->cursorLeft(bv);
1816         if (!selecting)
1817                 getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
1818         if (activate_inset && checkAndActivateInset(bv, behind))
1819                 return DISPATCHED;
1820         return DISPATCHED_NOUPDATE;
1821 }
1822
1823
1824 UpdatableInset::RESULT
1825 InsetText::moveUp(BufferView * bv)
1826 {
1827         if (!crow(bv)->previous())
1828                 return FINISHED_UP;
1829         getLyXText(bv)->cursorUp(bv);
1830         return DISPATCHED_NOUPDATE;
1831 }
1832
1833
1834 UpdatableInset::RESULT
1835 InsetText::moveDown(BufferView * bv)
1836 {
1837         if (!crow(bv)->next())
1838                 return FINISHED_DOWN;
1839         getLyXText(bv)->cursorDown(bv);
1840         return DISPATCHED_NOUPDATE;
1841 }
1842
1843
1844 bool InsetText::insertInset(BufferView * bv, Inset * inset)
1845 {
1846         if (the_locking_inset) {
1847                 if (the_locking_inset->insetAllowed(inset))
1848                         return the_locking_inset->insertInset(bv, inset);
1849                 return false;
1850         }
1851         bool clear = false;
1852         if (!lt) {
1853                 lt = getLyXText(bv);
1854                 clear = true;
1855         }
1856         setUndo(bv, Undo::FINISH, lt->cursor.par(), lt->cursor.par()->next());
1857         freezeUndo();
1858         inset->setOwner(this);
1859         hideInsetCursor(bv);
1860         lt->insertInset(bv, inset);
1861         bv->fitCursor();
1862         if (clear)
1863                 lt = 0;
1864         updateLocal(bv, CURSOR_PAR|CURSOR, true);
1865         unFreezeUndo();
1866         return true;
1867 }
1868
1869
1870 bool InsetText::insetAllowed(Inset::Code code) const
1871 {
1872         // in_insetAllowed is a really gross hack,
1873         // to allow us to call the owner's insetAllowed
1874         // without stack overflow, which can happen
1875         // when the owner uses InsetCollapsable::insetAllowed()
1876         bool ret = true;
1877         if (in_insetAllowed)
1878                 return ret;
1879         in_insetAllowed = true;
1880         if (the_locking_inset)
1881                 ret = the_locking_inset->insetAllowed(code);
1882         else if (owner())
1883                 ret = owner()->insetAllowed(code);
1884         in_insetAllowed = false;
1885         return ret;
1886 }
1887
1888
1889 UpdatableInset * InsetText::getLockingInset() const
1890 {
1891         return the_locking_inset ? the_locking_inset->getLockingInset() :
1892                 const_cast<InsetText *>(this);
1893 }
1894
1895
1896 UpdatableInset * InsetText::getFirstLockingInsetOfType(Inset::Code c)
1897 {
1898         if (c == lyxCode())
1899                 return this;
1900         if (the_locking_inset)
1901                 return the_locking_inset->getFirstLockingInsetOfType(c);
1902         return 0;
1903 }
1904
1905
1906 bool InsetText::showInsetDialog(BufferView * bv) const
1907 {
1908         if (the_locking_inset)
1909                 return the_locking_inset->showInsetDialog(bv);
1910         return false;
1911 }
1912
1913
1914 vector<string> const InsetText::getLabelList() const
1915 {
1916         vector<string> label_list;
1917
1918         Paragraph * tpar = par;
1919         while (tpar) {
1920                 Paragraph::inset_iterator beg = tpar->inset_iterator_begin();
1921                 Paragraph::inset_iterator end = tpar->inset_iterator_end();
1922                 for (; beg != end; ++beg) {
1923                         vector<string> const l = (*beg)->getLabelList();
1924                         label_list.insert(label_list.end(), l.begin(), l.end());
1925                 }
1926                 tpar = tpar->next();
1927         }
1928         return label_list;
1929 }
1930
1931
1932 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1933                         bool selectall)
1934 {
1935         if (the_locking_inset) {
1936                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1937                 return;
1938         }
1939         if ((!par->next() && !par->size()) || !cpar(bv)->size()) {
1940                 getLyXText(bv)->setFont(bv, font, toggleall);
1941                 return;
1942         }
1943         bool clear = false;
1944         if (!lt) {
1945                 lt = getLyXText(bv);
1946                 clear = true;
1947         }
1948         if (lt->selection.set()) {
1949                 setUndo(bv, Undo::EDIT, lt->cursor.par(), lt->cursor.par()->next());
1950         }
1951         if (selectall)
1952                 selectAll(bv);
1953         lt->toggleFree(bv, font, toggleall);
1954         if (selectall)
1955                 lt->clearSelection();
1956         bv->fitCursor();
1957         bool flag = (selectall || lt->selection.set());
1958         if (clear)
1959                 lt = 0;
1960         if (flag)
1961                 updateLocal(bv, FULL, true);
1962         else
1963                 updateLocal(bv, CURSOR_PAR, true);
1964 }
1965
1966
1967 bool InsetText::checkAndActivateInset(BufferView * bv, bool behind)
1968 {
1969         if (cpar(bv)->isInset(cpos(bv))) {
1970                 unsigned int x;
1971                 unsigned int y;
1972                 Inset * inset =
1973                         static_cast<UpdatableInset*>(cpar(bv)->getInset(cpos(bv)));
1974                 if (!isHighlyEditableInset(inset))
1975                         return false;
1976                 LyXFont const font =
1977                         getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1978                 if (behind) {
1979                         x = inset->width(bv, font);
1980                         y = font.isRightToLeft() ? 0 : inset->descent(bv, font);
1981                 } else {
1982                         x = 0;
1983                         y = font.isRightToLeft() ? inset->descent(bv, font) : 0;
1984                 }
1985                 //inset_x = cx(bv) - top_x + drawTextXOffset;
1986                 //inset_y = cy(bv) + drawTextYOffset;
1987                 inset->edit(bv, x, y, 0);
1988                 if (!the_locking_inset)
1989                         return false;
1990                 updateLocal(bv, CURSOR, false);
1991                 return true;
1992         }
1993         return false;
1994 }
1995
1996
1997 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1998                                       int button)
1999 {
2000         x -= drawTextXOffset;
2001         int dummyx = x;
2002         int dummyy = y + insetAscent;
2003         Inset * inset = bv->checkInsetHit(getLyXText(bv), dummyx, dummyy);
2004
2005         if (inset) {
2006                 if (x < 0)
2007                         x = insetWidth;
2008                 if (y < 0)
2009                         y = insetDescent;
2010                 inset_x = cx(bv) - top_x + drawTextXOffset;
2011                 inset_y = cy(bv) + drawTextYOffset;
2012                 inset->edit(bv, x - inset_x, y - inset_y, button);
2013                 if (!the_locking_inset)
2014                         return false;
2015                 updateLocal(bv, CURSOR, false);
2016                 return true;
2017         }
2018         return false;
2019 }
2020
2021
2022 int InsetText::getMaxWidth(BufferView * bv, UpdatableInset const * inset) const
2023 {
2024 #if 0
2025         int w = UpdatableInset::getMaxWidth(bv, inset);
2026         if (w < 0) {
2027                 return -1;
2028         }
2029         if (owner()) {
2030                 w = w - top_x + owner()->x();
2031                 return w;
2032         }
2033         w -= (2 * TEXT_TO_INSET_OFFSET);
2034         return w - top_x;
2035 #else
2036         return UpdatableInset::getMaxWidth(bv, inset);
2037 #endif
2038 }
2039
2040
2041 void InsetText::setParagraphData(Paragraph * p, bool same_id)
2042 {
2043         // we have to unlock any locked inset otherwise we're in troubles
2044         the_locking_inset = 0;
2045         while (par) {
2046                 Paragraph * tmp = par->next();
2047                 delete par;
2048                 par = tmp;
2049         }
2050
2051         par = new Paragraph(*p, same_id);
2052         par->setInsetOwner(this);
2053         Paragraph * np = par;
2054         while (p->next()) {
2055                 p = p->next();
2056                 np->next(new Paragraph(*p, same_id));
2057                 np->next()->previous(np);
2058                 np = np->next();
2059                 np->setInsetOwner(this);
2060         }
2061         reinitLyXText();
2062         need_update = INIT;
2063 }
2064
2065
2066 void InsetText::setText(string const & data, LyXFont const & font)
2067 {
2068         clear();
2069         for (unsigned int i=0; i < data.length(); ++i)
2070                 par->insertChar(i, data[i], font);
2071         reinitLyXText();
2072 }
2073
2074
2075 void InsetText::setAutoBreakRows(bool flag)
2076 {
2077         if (flag != autoBreakRows) {
2078                 autoBreakRows = flag;
2079                 if (!flag)
2080                         removeNewlines();
2081                 need_update = INIT;
2082         }
2083 }
2084
2085
2086 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
2087 {
2088         if (how != drawFrame_) {
2089                 drawFrame_ = how;
2090                 if (bv)
2091                         updateLocal(bv, DRAW_FRAME, false);
2092         }
2093 }
2094
2095
2096 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
2097 {
2098         if (frame_color != col) {
2099                 frame_color = col;
2100                 if (bv)
2101                         updateLocal(bv, DRAW_FRAME, false);
2102         }
2103 }
2104
2105
2106 int InsetText::cx(BufferView * bv) const
2107 {
2108         // we do nothing dangerous so we use a local cache
2109         LyXText * llt = getLyXText(bv);
2110         int x = llt->cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
2111         if (the_locking_inset) {
2112                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2113                                             llt->cursor.pos());
2114                 if (font.isVisibleRightToLeft())
2115                         x -= the_locking_inset->width(bv, font);
2116         }
2117         return x;
2118 }
2119
2120
2121 int InsetText::cy(BufferView * bv) const
2122 {
2123         LyXFont font;
2124         return getLyXText(bv)->cursor.y() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2125 }
2126
2127
2128 pos_type InsetText::cpos(BufferView * bv) const
2129 {
2130         return getLyXText(bv)->cursor.pos();
2131 }
2132
2133
2134 Paragraph * InsetText::cpar(BufferView * bv) const
2135 {
2136         return getLyXText(bv)->cursor.par();
2137 }
2138
2139
2140 bool InsetText::cboundary(BufferView * bv) const
2141 {
2142         return getLyXText(bv)->cursor.boundary();
2143 }
2144
2145
2146 Row * InsetText::crow(BufferView * bv) const
2147 {
2148         return getLyXText(bv)->cursor.row();
2149 }
2150
2151
2152 LyXText * InsetText::getLyXText(BufferView const * lbv,
2153                                 bool const recursive) const
2154 {
2155         if (cached_bview == lbv) {
2156                 if (recursive && the_locking_inset)
2157                         return the_locking_inset->getLyXText(lbv, true);
2158                 LyXText * lt = cached_text.get();
2159                 lyx::Assert(lt && lt->firstRow()->par() == par);
2160                 return lt;
2161         }
2162         // Super UGLY! (Lgb)
2163         BufferView * bv = const_cast<BufferView *>(lbv);
2164
2165         cached_bview = bv;
2166         Cache::iterator it = cache.find(bv);
2167
2168         if (it != cache.end()) {
2169                 if (do_reinit) {
2170                         reinitLyXText();
2171                 } else if (do_resize) {
2172                         resizeLyXText(do_resize);
2173                 } else {
2174                         if (lt || !it->second.remove) {
2175                                 lyx::Assert(it->second.text.get());
2176                                 cached_text = it->second.text;
2177                                 if (recursive && the_locking_inset) {
2178                                         return the_locking_inset->getLyXText(bv, true);
2179                                 }
2180                                 return cached_text.get();
2181                         } else if (it->second.remove) {
2182                                 if (locked) {
2183                                         saveLyXTextState(it->second.text.get());
2184                                 } else {
2185                                         sstate.lpar = 0;
2186                                 }
2187                         }
2188                         //
2189                         // when we have to reinit the existing LyXText!
2190                         //
2191                         it->second.text->init(bv);
2192                         restoreLyXTextState(bv, it->second.text.get());
2193                         it->second.remove = false;
2194                 }
2195                 cached_text = it->second.text;
2196                 if (the_locking_inset && recursive) {
2197                         return the_locking_inset->getLyXText(bv);
2198                 }
2199                 return cached_text.get();
2200         }
2201         ///
2202         // we are here only if we don't have a BufferView * in the cache!!!
2203         ///
2204         cached_text.reset(new LyXText(const_cast<InsetText *>(this)));
2205         cached_text->init(bv);
2206         restoreLyXTextState(bv, cached_text.get());
2207
2208         cache.insert(make_pair(bv, cached_text));
2209
2210         if (the_locking_inset && recursive) {
2211                 return the_locking_inset->getLyXText(bv);
2212         }
2213         return cached_text.get();
2214 }
2215
2216
2217 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
2218 {
2219         cached_bview = 0;
2220
2221         Cache::iterator it = cache.find(bv);
2222
2223         if (it == cache.end()) {
2224                 return;
2225         }
2226
2227         lyx::Assert(it->second.text.get());
2228
2229         it->second.remove = true;
2230         if (recursive) {
2231                 /// then remove all LyXText in text-insets
2232                 Paragraph * p = par;
2233                 for (; p; p = p->next()) {
2234                         p->deleteInsetsLyXText(bv);
2235                 }
2236         }
2237 }
2238
2239
2240 void InsetText::resizeLyXText(BufferView * bv, bool force) const
2241 {
2242         if (lt) {
2243                 // we cannot resize this because we are in use!
2244                 // so do this on the next possible getLyXText()
2245                 do_resize = bv;
2246                 return;
2247         }
2248         do_resize = 0;
2249 //      lyxerr << "InsetText::resizeLyXText\n";
2250         if (!par->next() && !par->size()) { // no data, resize not neccessary!
2251                 // we have to do this as a fixed width may have changed!
2252                 LyXText * t = getLyXText(bv);
2253                 saveLyXTextState(t);
2254                 t->init(bv, true);
2255                 restoreLyXTextState(bv, t);
2256                 return;
2257         }
2258         // one endless line, resize normally not necessary
2259         if (!force && getMaxWidth(bv, this) < 0)
2260                 return;
2261
2262         Cache::iterator it = cache.find(bv);
2263         if (it == cache.end()) {
2264                 return;
2265         }
2266         lyx::Assert(it->second.text.get());
2267
2268         LyXText * t = it->second.text.get();
2269         saveLyXTextState(t);
2270         for (Paragraph * p = par; p; p = p->next()) {
2271                 p->resizeInsetsLyXText(bv);
2272         }
2273         t->init(bv, true);
2274         restoreLyXTextState(bv, t);
2275         if (the_locking_inset) {
2276                 inset_x = cx(bv) - top_x + drawTextXOffset;
2277                 inset_y = cy(bv) + drawTextYOffset;
2278         }
2279
2280         if (bv->screen()) {
2281                 t->first_y = bv->screen()->topCursorVisible(t);
2282         }
2283         if (!owner()) {
2284                 updateLocal(bv, FULL, false);
2285                 // this will scroll the screen such that the cursor becomes visible
2286                 bv->updateScrollbar();
2287         } else {
2288                 need_update |= FULL;
2289         }
2290 }
2291
2292
2293 void InsetText::reinitLyXText() const
2294 {
2295         if (lt) {
2296                 // we cannot resize this because we are in use!
2297                 // so do this on the next possible getLyXText()
2298                 do_reinit = true;
2299                 return;
2300         }
2301         do_reinit = false;
2302         do_resize = 0;
2303 //      lyxerr << "InsetText::reinitLyXText\n";
2304         for(Cache::iterator it = cache.begin(); it != cache.end(); ++it) {
2305                 lyx::Assert(it->second.text.get());
2306
2307                 LyXText * t = it->second.text.get();
2308                 BufferView * bv = it->first;
2309
2310                 saveLyXTextState(t);
2311                 for (Paragraph * p = par; p; p = p->next()) {
2312                         p->resizeInsetsLyXText(bv);
2313                 }
2314                 t->init(bv, true);
2315                 restoreLyXTextState(bv, t);
2316                 if (the_locking_inset) {
2317                         inset_x = cx(bv) - top_x + drawTextXOffset;
2318                         inset_y = cy(bv) + drawTextYOffset;
2319                 }
2320                 if (bv->screen()) {
2321                         t->first_y = bv->screen()->topCursorVisible(t);
2322                 }
2323                 if (!owner()) {
2324                         updateLocal(bv, FULL, false);
2325                         // this will scroll the screen such that the cursor becomes visible
2326                         bv->updateScrollbar();
2327                 } else {
2328                         need_update = FULL;
2329                 }
2330         }
2331 }
2332
2333
2334 void InsetText::removeNewlines()
2335 {
2336         bool changed = false;
2337
2338         for (Paragraph * p = par; p; p = p->next()) {
2339                 for (int i = 0; i < p->size(); ++i) {
2340                         if (p->getChar(i) == Paragraph::META_NEWLINE) {
2341                                 changed = true;
2342                                 p->erase(i);
2343                         }
2344                 }
2345         }
2346         if (changed)
2347                 reinitLyXText();
2348 }
2349
2350
2351 bool InsetText::nodraw() const
2352 {
2353         if (the_locking_inset)
2354                 return the_locking_inset->nodraw();
2355         return UpdatableInset::nodraw();
2356 }
2357
2358
2359 int InsetText::scroll(bool recursive) const
2360 {
2361         int sx = UpdatableInset::scroll(false);
2362
2363         if (recursive && the_locking_inset)
2364                 sx += the_locking_inset->scroll(recursive);
2365
2366         return sx;
2367 }
2368
2369
2370 bool InsetText::doClearArea() const
2371 {
2372         return !locked || (need_update & (FULL|INIT));
2373 }
2374
2375
2376 void InsetText::selectAll(BufferView * bv)
2377 {
2378         getLyXText(bv)->cursorTop(bv);
2379         getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
2380         getLyXText(bv)->cursorBottom(bv);
2381         getLyXText(bv)->setSelection(bv);
2382 }
2383
2384
2385 void InsetText::clearSelection(BufferView * bv)
2386 {
2387         getLyXText(bv)->clearSelection();
2388 }
2389
2390
2391 void InsetText::clearInset(BufferView * bv, int baseline, bool & cleared) const
2392 {
2393         Painter & pain = bv->painter();
2394         int w = insetWidth;
2395         int h = insetAscent + insetDescent;
2396         int ty = baseline - insetAscent;
2397
2398         if (ty < 0) {
2399                 h += ty;
2400                 ty = 0;
2401         }
2402         if ((ty + h) > pain.paperHeight())
2403                 h = pain.paperHeight();
2404         if ((top_x + drawTextXOffset + w) > pain.paperWidth())
2405                 w = pain.paperWidth();
2406 //      w -= TEXT_TO_INSET_OFFSET;
2407         pain.fillRectangle(top_x, ty, w+1, h+1, backgroundColor());
2408         cleared = true;
2409         need_update = FULL;
2410         frame_is_visible = false;
2411 }
2412
2413
2414 Paragraph * InsetText::getParFromID(int id) const
2415 {
2416 #if 0
2417         Paragraph * result = par;
2418         Paragraph * ires = 0;
2419         while (result && result->id() != id) {
2420                 if ((ires = result->getParFromID(id)))
2421                         return ires;
2422                 result = result->next();
2423         }
2424         return result;
2425 #else
2426         Paragraph * tmp = par;
2427         while (tmp) {
2428                 if (tmp->id() == id) {
2429                         return tmp;
2430                 }
2431                 Paragraph * tmp2 = tmp->getParFromID(id);
2432                 if (tmp2 != 0) {
2433                         return tmp2;
2434                 }
2435                 tmp = tmp->next();
2436         }
2437         return 0;
2438 #endif
2439 }
2440
2441
2442 Paragraph * InsetText::firstParagraph() const
2443 {
2444         Paragraph * result;
2445         if (the_locking_inset)
2446                 if ((result = the_locking_inset->firstParagraph()))
2447                         return result;
2448         return par;
2449 }
2450
2451
2452 Paragraph * InsetText::getFirstParagraph(int i) const
2453 {
2454         return (i == 0) ? par : 0;
2455 }
2456
2457
2458 LyXCursor const & InsetText::cursor(BufferView * bv) const
2459 {
2460                 if (the_locking_inset)
2461                                 return the_locking_inset->cursor(bv);
2462                 return getLyXText(bv)->cursor;
2463 }
2464
2465
2466 Paragraph * InsetText::paragraph() const
2467 {
2468         return par;
2469 }
2470
2471
2472 void InsetText::paragraph(Paragraph * p)
2473 {
2474         // GENERAL COMMENT: We don't have to free the old paragraphs as the
2475         // caller of this function has to take care of it. This IS important
2476         // as we could have to insert a paragraph before this one and just
2477         // link the actual to a new ones next and set it with this function
2478         // and are done!
2479         par = p;
2480         // set ourself as owner for all the paragraphs inserted!
2481         Paragraph * np = par;
2482         while (np) {
2483                 np->setInsetOwner(this);
2484                 np = np->next();
2485         }
2486         reinitLyXText();
2487         // redraw myself when asked for
2488         need_update = INIT;
2489 }
2490
2491
2492 Inset * InsetText::getInsetFromID(int id_arg) const
2493 {
2494         if (id_arg == id())
2495                 return const_cast<InsetText *>(this);
2496
2497         Paragraph * lp = par;
2498
2499         while (lp) {
2500                 for (Paragraph::inset_iterator it = lp->inset_iterator_begin(),
2501                          en = lp->inset_iterator_end();
2502                          it != en; ++it)
2503                 {
2504                         if ((*it)->id() == id_arg)
2505                                 return *it;
2506                         Inset * in = (*it)->getInsetFromID(id_arg);
2507                         if (in)
2508                                 return in;
2509                 }
2510                 lp = lp->next();
2511         }
2512         return 0;
2513 }
2514
2515
2516 string const InsetText::selectNextWordToSpellcheck(BufferView * bv, float & value) const
2517 {
2518         bool clear = false;
2519         string str;
2520
2521         if (!lt) {
2522                 lt = getLyXText(bv);
2523                 clear = true;
2524         }
2525         if (the_locking_inset) {
2526                 str = the_locking_inset->selectNextWordToSpellcheck(bv, value);
2527                 if (!str.empty()) {
2528                         value += cy(bv);
2529                         if (clear)
2530                                 lt = 0;
2531                         return str;
2532                 }
2533                 // we have to go on checking so move cusor to the next char
2534                 lt->cursor.pos(lt->cursor.pos() + 1);
2535         }
2536         str = lt->selectNextWordToSpellcheck(bv, value);
2537         if (str.empty())
2538                 bv->unlockInset(const_cast<InsetText *>(this));
2539         else
2540                 value = cy(bv);
2541         if (clear)
2542                 lt = 0;
2543         return str;
2544 }
2545
2546
2547 void InsetText::selectSelectedWord(BufferView * bv)
2548 {
2549         if (the_locking_inset) {
2550                 the_locking_inset->selectSelectedWord(bv);
2551                 return;
2552         }
2553         getLyXText(bv)->selectSelectedWord(bv);
2554         updateLocal(bv, SELECTION, false);
2555 }
2556
2557
2558 void InsetText::toggleSelection(BufferView * bv, bool kill_selection)
2559 {
2560         if (the_locking_inset) {
2561                 the_locking_inset->toggleSelection(bv, kill_selection);
2562         }
2563         bool clear = false;
2564         if (!lt) {
2565                 lt = getLyXText(bv);
2566                 clear = true;
2567         }
2568
2569         int x = top_x + TEXT_TO_INSET_OFFSET;
2570
2571         Row * row = lt->firstRow();
2572         int y_offset = top_baseline - row->ascent_of_text();
2573         int y = y_offset;
2574         while ((row != 0) && ((y+row->height()) <= 0)) {
2575                 y += row->height();
2576                 row = row->next();
2577         }
2578         if (y_offset < 0)
2579                 y_offset = y;
2580
2581         if (need_update & SELECTION)
2582                 need_update = NONE;
2583         bv->screen()->toggleSelection(lt, bv, kill_selection, y_offset, x);
2584         if (clear)
2585                 lt = 0;
2586 }
2587
2588
2589 bool InsetText::searchForward(BufferView * bv, string const & str,
2590                               bool cs, bool mw)
2591 {
2592         if (the_locking_inset) {
2593                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2594                         return true;
2595                 bool clear = false;
2596                 if (!lt) {
2597                         lt = getLyXText(bv);
2598                         clear = true;
2599                 }
2600                 Paragraph * lpar = lt->cursor.par();
2601                 pos_type pos = lt->cursor.pos();
2602                 if (pos < lpar->size() - 1)
2603                         ++pos;
2604                 else {
2605                         pos = 0;
2606                         lpar = lpar->next();
2607                 }
2608                 if (!lpar) {
2609                         if (clear)
2610                                 lt = 0;
2611                         // we have to unlock ourself in this function by default!
2612                         bv->unlockInset(const_cast<InsetText *>(this));
2613                         return false;
2614                 }
2615                 lt->setCursor(bv, lpar, pos);
2616                 if (clear)
2617                         lt = 0;
2618         }
2619         if (LyXFind(bv, str, true, true, cs , mw)) {
2620                 return true;
2621         }
2622         // we have to unlock ourself in this function by default!
2623         bv->unlockInset(const_cast<InsetText *>(this));
2624         return false;
2625 }
2626
2627 bool InsetText::searchBackward(BufferView * bv, string const & str,
2628                                bool cs, bool mw)
2629 {
2630         if (the_locking_inset)
2631                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2632                         return true;
2633         if (LyXFind(bv, str, false, true, cs, mw)) {
2634                 return true;
2635         }
2636         // we have to unlock ourself in this function by default!
2637         bv->unlockInset(const_cast<InsetText *>(this));
2638         return false;
2639 }
2640
2641
2642 bool InsetText::checkInsertChar(LyXFont & font)
2643 {
2644         if (owner())
2645                 return owner()->checkInsertChar(font);
2646         return true;
2647 }
2648
2649
2650 void InsetText::collapseParagraphs(BufferParams const & bparams) const
2651 {
2652         while(par->next()) {
2653                 if (par->size() && par->next()->size() &&
2654                         !par->isSeparator(par->size()-1))
2655                 {
2656                         par->insertChar(par->size(), ' ');
2657                 }
2658                 par->pasteParagraph(bparams);
2659         }
2660         reinitLyXText();
2661 }
2662
2663
2664 void InsetText::getDrawFont(LyXFont & font) const
2665 {
2666         if (!owner())
2667                 return;
2668         owner()->getDrawFont(font);
2669 }
2670
2671
2672 void InsetText::appendParagraphs(BufferParams const & bparams,
2673                                  Paragraph * newpar)
2674 {
2675         Paragraph * buf;
2676         Paragraph * tmpbuf = newpar;
2677         Paragraph * lastbuffer = buf = new Paragraph(*tmpbuf, false);
2678
2679         while (tmpbuf->next()) {
2680                 tmpbuf = tmpbuf->next();
2681                 lastbuffer->next(new Paragraph(*tmpbuf, false));
2682                 lastbuffer->next()->previous(lastbuffer);
2683                 lastbuffer = lastbuffer->next();
2684         }
2685         lastbuffer = par;
2686         while (lastbuffer->next())
2687                 lastbuffer = lastbuffer->next();
2688         if (newpar->size() && lastbuffer->size() &&
2689                 !lastbuffer->isSeparator(lastbuffer->size()-1))
2690         {
2691                 lastbuffer->insertChar(lastbuffer->size(), ' ');
2692         }
2693
2694         // make the buf exactly the same layout than our last paragraph
2695         buf->makeSameLayout(lastbuffer);
2696
2697         // paste it!
2698         lastbuffer->next(buf);
2699         buf->previous(lastbuffer);
2700         lastbuffer->pasteParagraph(bparams);
2701
2702         reinitLyXText();
2703 }