]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
fix typo that put too many include paths for most people
[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 = true;
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 = mark_dirty ||
622                 (((need_update != CURSOR) && (need_update != NONE)) ||
623                  (lt->status() != LyXText::UNCHANGED) || lt->selection.set());
624         if (!lt->selection.set())
625                 lt->selection.cursor = lt->cursor;
626         if (clear)
627                 lt = 0;
628         if (locked && (need_update & CURSOR) && bv->fitCursor())
629                 need_update |= FULL;
630         if (flag)
631                 bv->updateInset(const_cast<InsetText *>(this), mark_dirty);
632
633         if (need_update == CURSOR)
634                 need_update = NONE;
635         bv->owner()->showState();
636         bv->owner()->updateMenubar();
637         bv->owner()->updateToolbar();
638         if (old_par != cpar(bv)) {
639                 bv->owner()->setLayout(cpar(bv)->layout());
640                 old_par = cpar(bv);
641         }
642 }
643
644
645 string const InsetText::editMessage() const
646 {
647         return _("Opened Text Inset");
648 }
649
650
651 void InsetText::edit(BufferView * bv, int x, int y, unsigned int button)
652 {
653         UpdatableInset::edit(bv, x, y, button);
654
655         if (!bv->lockInset(this)) {
656                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
657                 return;
658         }
659         locked = true;
660         the_locking_inset = 0;
661         inset_pos = inset_x = inset_y = 0;
662         inset_boundary = false;
663         inset_par = 0;
664         old_par = 0;
665         int tmp_y = (y < 0) ? 0 : y;
666         bool clear = false;
667         if (!lt) {
668                 lt = getLyXText(bv);
669                 clear = true;
670         }
671         if (!checkAndActivateInset(bv, x, tmp_y, button))
672                 lt->setCursorFromCoordinates(bv, x - drawTextXOffset,
673                                             y + insetAscent);
674         lt->clearSelection();
675         finishUndo();
676         // If the inset is empty set the language of the current font to the
677         // language to the surronding text (if different).
678         if (par->size() == 0 && !par->next() &&
679                 bv->getParentLanguage(this) != lt->current_font.language())
680         {
681                 LyXFont font(LyXFont::ALL_IGNORE);
682                 font.setLanguage(bv->getParentLanguage(this));
683                 setFont(bv, font, false);
684         }
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         showInsetCursor(bv);
693
694         // Tell the paragraph dialog that we've entered an insettext.
695         bv->owner()->getDialogs()->updateParagraph();
696 }
697
698
699 void InsetText::edit(BufferView * bv, bool front)
700 {
701         UpdatableInset::edit(bv, front);
702
703         if (!bv->lockInset(this)) {
704                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
705                 return;
706         }
707         locked = true;
708         the_locking_inset = 0;
709         inset_pos = inset_x = inset_y = 0;
710         inset_boundary = false;
711         inset_par = 0;
712         old_par = 0;
713         bool clear = false;
714         if (!lt) {
715                 lt = getLyXText(bv);
716                 clear = true;
717         }
718         if (front)
719                 lt->setCursor(bv, par, 0);
720         else {
721                 Paragraph * p = par;
722                 while (p->next())
723                         p = p->next();
724 //              int const pos = (p->size() ? p->size()-1 : p->size());
725                 lt->setCursor(bv, p, p->size());
726         }
727         lt->clearSelection();
728         finishUndo();
729         // If the inset is empty set the language of the current font to the
730         // language to the surronding text (if different).
731         if (par->size() == 0 && !par->next() &&
732                 bv->getParentLanguage(this) != lt->current_font.language()) {
733                 LyXFont font(LyXFont::ALL_IGNORE);
734                 font.setLanguage(bv->getParentLanguage(this));
735                 setFont(bv, font, false);
736         }
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         showInsetCursor(bv);
744 }
745
746
747 void InsetText::insetUnlock(BufferView * bv)
748 {
749         if (the_locking_inset) {
750                 the_locking_inset->insetUnlock(bv);
751                 the_locking_inset = 0;
752         }
753         hideInsetCursor(bv);
754         no_selection = true;
755         locked = false;
756         int code;
757         if (drawFrame_ == LOCKED)
758                 code = CURSOR|CLEAR_FRAME;
759         else
760                 code = CURSOR;
761         bool clear = false;
762         if (!lt) {
763                 lt = getLyXText(bv);
764                 clear = true;
765         }
766         if (lt->selection.set()) {
767                 lt->clearSelection();
768                 code = FULL;
769         } else if (owner()) {
770                 bv->owner()->setLayout(owner()->getLyXText(bv)
771                                        ->cursor.par()->layout());
772         } else
773                 bv->owner()->setLayout(bv->text->cursor.par()->layout());
774         // hack for deleteEmptyParMech
775         if (par->size()) {
776                 lt->setCursor(bv, par, 0);
777         } else if (par->next()) {
778                 lt->setCursor(bv, par->next(), 0);
779         }
780         if (clear)
781                 lt = 0;
782         updateLocal(bv, code, false);
783 }
784
785 void InsetText::lockInset(BufferView * bv, UpdatableInset * inset)
786 {
787         the_locking_inset = inset;
788         inset_x = cx(bv) - top_x + drawTextXOffset;
789         inset_y = cy(bv) + drawTextYOffset;
790         inset_pos = cpos(bv);
791         inset_par = cpar(bv);
792         inset_boundary = cboundary(bv);
793         updateLocal(bv, CURSOR, false);
794 }
795
796
797 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
798 {
799         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
800                               << inset << "): ";
801         if (!inset)
802                 return false;
803         if (!the_locking_inset) {
804                 Paragraph * p = par;
805                 int const id = inset->id();
806                 while(p) {
807                         Paragraph::inset_iterator it =
808                                 p->inset_iterator_begin();
809                         Paragraph::inset_iterator const end =
810                                 p->inset_iterator_end();
811                         for (; it != end; ++it) {
812                                 if ((*it) == inset) {
813                                         getLyXText(bv)->setCursorIntern(bv, p, it.getPos());
814                                         lockInset(bv, inset);
815                                         return true;
816                                 }
817                                 if ((*it)->getInsetFromID(id)) {
818                                         getLyXText(bv)->setCursorIntern(bv, p, it.getPos());
819                                         (*it)->edit(bv);
820                                         return the_locking_inset->lockInsetInInset(bv, inset);
821                                 }
822                         }
823                         p = p->next();
824                 }
825                 return false;
826         }
827         if (inset == cpar(bv)->getInset(cpos(bv))) {
828                 lyxerr[Debug::INSETS] << "OK" << endl;
829                 lockInset(bv, inset);
830                 return true;
831         } else if (the_locking_inset && (the_locking_inset == inset)) {
832                 if (cpar(bv) == inset_par && cpos(bv) == inset_pos) {
833                         lyxerr[Debug::INSETS] << "OK" << endl;
834                         inset_x = cx(bv) - top_x + drawTextXOffset;
835                         inset_y = cy(bv) + drawTextYOffset;
836                 } else {
837                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
838                 }
839         } else if (the_locking_inset) {
840                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
841                 return the_locking_inset->lockInsetInInset(bv, inset);
842         }
843         lyxerr[Debug::INSETS] << "NOT OK" << endl;
844         return false;
845 }
846
847
848 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
849                                    bool lr)
850 {
851         if (!the_locking_inset)
852                 return false;
853         if (the_locking_inset == inset) {
854                 the_locking_inset->insetUnlock(bv);
855                 getLyXText(bv)->updateInset(bv, inset);
856                 the_locking_inset = 0;
857                 if (lr)
858                         moveRight(bv, false);
859                 old_par = 0; // force layout setting
860                 if (scroll())
861                         scroll(bv, 0.0F);
862                 else
863                         updateLocal(bv, CURSOR, false);
864                 return true;
865         }
866         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
867 }
868
869
870 bool InsetText::updateInsetInInset(BufferView * bv, Inset * inset)
871 {
872         if (!autoBreakRows && par->next())
873                 collapseParagraphs(bv->buffer()->params);
874         if (inset == this)
875                 return true;
876         bool clear = false;
877         if (!lt) {
878                 lt = getLyXText(bv);
879                 clear = true;
880         }
881         if (inset->owner() != this) {
882                 int ustat = CURSOR_PAR;
883                 bool found = false;
884                 UpdatableInset * tl_inset = the_locking_inset;
885                 if (tl_inset)
886                         found = tl_inset->updateInsetInInset(bv, inset);
887                 if (!found) {
888                         tl_inset = static_cast<UpdatableInset *>(inset);
889                         while(tl_inset->owner() && tl_inset->owner() != this)
890                                 tl_inset = static_cast<UpdatableInset *>(tl_inset->owner());
891                         if (!tl_inset->owner())
892                                 return false;
893                         found = tl_inset->updateInsetInInset(bv, inset);
894                         ustat = FULL;
895                 }
896                 if (found)
897                         lt->updateInset(bv, tl_inset);
898                 if (clear)
899                         lt = 0;
900                 if (found)
901                         setUpdateStatus(bv, ustat);
902                 return found;
903         }
904         bool found = lt->updateInset(bv, inset);
905         if (clear)
906                 lt = 0;
907         if (found) {
908                 setUpdateStatus(bv, CURSOR_PAR);
909                 if (the_locking_inset &&
910                     cpar(bv) == inset_par && cpos(bv) == inset_pos)
911                 {
912                         inset_x = cx(bv) - top_x + drawTextXOffset;
913                         inset_y = cy(bv) + drawTextYOffset;
914                 }
915         }
916         return found;
917 }
918
919
920 void InsetText::insetButtonPress(BufferView * bv, int x, int y, int button)
921 {
922         no_selection = true;
923
924         // use this to check mouse motion for selection!
925         mouse_x = x;
926         mouse_y = y;
927
928         int tmp_x = x - drawTextXOffset;
929         int tmp_y = y + insetAscent - getLyXText(bv)->first_y;
930         Inset * inset = bv->checkInsetHit(getLyXText(bv), tmp_x, tmp_y);
931
932         hideInsetCursor(bv);
933         if (the_locking_inset) {
934                 if (the_locking_inset == inset) {
935                         the_locking_inset->insetButtonPress(bv,
936                                                             x - inset_x,
937                                                             y - inset_y,
938                                                             button);
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                         return;
952                 }
953                 // otherwise only unlock the_locking_inset
954                 the_locking_inset->insetUnlock(bv);
955                 the_locking_inset = 0;
956         }
957         if (!inset)
958                 no_selection = false;
959
960         if (bv->theLockingInset()) {
961                 if (isHighlyEditableInset(inset)) {
962                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
963                         inset_x = cx(bv) - top_x + drawTextXOffset;
964                         inset_y = cy(bv) + drawTextYOffset;
965                         inset_pos = cpos(bv);
966                         inset_par = cpar(bv);
967                         inset_boundary = cboundary(bv);
968                         the_locking_inset = uinset;
969                         uinset->insetButtonPress(bv, x - inset_x, y - inset_y,
970                                                  button);
971                         uinset->edit(bv, x - inset_x, y - inset_y, 0);
972                         if (the_locking_inset)
973                                 updateLocal(bv, CURSOR, false);
974                         return;
975                 }
976         }
977         if (!inset) { // && (button == 2)) {
978                 bool paste_internally = false;
979                 if ((button == 2) && getLyXText(bv)->selection.set()) {
980                         localDispatch(bv, LFUN_COPY, "");
981                         paste_internally = true;
982                 }
983                 bool clear = false;
984                 if (!lt) {
985                         lt = getLyXText(bv);
986                         clear = true;
987                 }
988                 int old_first_y = lt->first_y;
989
990                 lt->setCursorFromCoordinates(bv, x - drawTextXOffset,
991                                              y + insetAscent);
992                 // set the selection cursor!
993                 lt->selection.cursor = lt->cursor;
994                 lt->cursor.x_fix(lt->cursor.x());
995
996                 if (lt->selection.set()) {
997                         lt->clearSelection();
998                         if (clear)
999                                 lt = 0;
1000                         updateLocal(bv, FULL, false);
1001                 } else {
1002                         lt->clearSelection();
1003                         if (clear)
1004                                 lt = 0;
1005                         updateLocal(bv, CURSOR, false);
1006                 }
1007                 bv->owner()->setLayout(cpar(bv)->layout());
1008                 // we moved the view we cannot do mouse selection in this case!
1009                 if (getLyXText(bv)->first_y != old_first_y)
1010                         no_selection = true;
1011                 old_par = cpar(bv);
1012                 // Insert primary selection with middle mouse
1013                 // if there is a local selection in the current buffer,
1014                 // insert this
1015                 if (button == 2) {
1016                         if (paste_internally)
1017                                 localDispatch(bv, LFUN_PASTE, "");
1018                         else
1019                                 localDispatch(bv, LFUN_PASTESELECTION,
1020                                               "paragraph");
1021                 }
1022         } else {
1023                 getLyXText(bv)->clearSelection();
1024         }
1025         showInsetCursor(bv);
1026 }
1027
1028
1029 bool InsetText::insetButtonRelease(BufferView * bv, int x, int y, int button)
1030 {
1031         no_selection = true;
1032         if (the_locking_inset) {
1033                 return the_locking_inset->insetButtonRelease(bv,
1034                                                              x - inset_x, y - inset_y,
1035                                                              button);
1036         }
1037         int tmp_x = x - drawTextXOffset;
1038         int tmp_y = y + insetAscent - getLyXText(bv)->first_y;
1039         Inset * inset = bv->checkInsetHit(getLyXText(bv), tmp_x, tmp_y);
1040         bool ret = false;
1041         if (inset) {
1042                 if (isHighlyEditableInset(inset)) {
1043                         ret = inset->insetButtonRelease(bv, x - inset_x,
1044                                                         y - inset_y, button);
1045                 } else {
1046                         inset_x = cx(bv) - top_x + drawTextXOffset;
1047                         inset_y = cy(bv) + drawTextYOffset;
1048                         ret = inset->insetButtonRelease(bv, x - inset_x,
1049                                                         y - inset_y, button);
1050                         inset->edit(bv, x - inset_x,
1051                                     y - inset_y, button);
1052                 }
1053                 updateLocal(bv, CURSOR_PAR, false);
1054         }
1055         return ret;
1056 }
1057
1058
1059 void InsetText::insetMotionNotify(BufferView * bv, int x, int y, int state)
1060 {
1061         if (the_locking_inset) {
1062                 the_locking_inset->insetMotionNotify(bv, x - inset_x,
1063                                                      y - inset_y,state);
1064                 return;
1065         }
1066
1067         if (no_selection || ((mouse_x == x) && (mouse_y == y)))
1068                 return;
1069
1070         bool clear = false;
1071         if (!lt) {
1072                 lt = getLyXText(bv);
1073                 clear = true;
1074         }
1075         hideInsetCursor(bv);
1076         LyXCursor cur = lt->cursor;
1077         lt->setCursorFromCoordinates(bv, x - drawTextXOffset, y + insetAscent);
1078         if (cur == lt->cursor) {
1079                 if (clear)
1080                         lt = 0;
1081                 return;
1082         }
1083         lt->setSelection(bv);
1084         bool flag = (lt->toggle_cursor.par() != lt->toggle_end_cursor.par() ||
1085                                  lt->toggle_cursor.pos() != lt->toggle_end_cursor.pos());
1086         if (clear)
1087                 lt = 0;
1088         if (flag) {
1089                 updateLocal(bv, SELECTION, false);
1090         }
1091         showInsetCursor(bv);
1092 }
1093
1094
1095 void InsetText::insetKeyPress(XKeyEvent * xke)
1096 {
1097         if (the_locking_inset) {
1098                 the_locking_inset->insetKeyPress(xke);
1099                 return;
1100         }
1101 }
1102
1103
1104 UpdatableInset::RESULT
1105 InsetText::localDispatch(BufferView * bv,
1106                          kb_action action, string const & arg)
1107 {
1108         bool was_empty = par->size() == 0 && !par->next();
1109         no_selection = false;
1110         UpdatableInset::RESULT
1111                 result= UpdatableInset::localDispatch(bv, action, arg);
1112         if (result != UNDISPATCHED) {
1113                 return DISPATCHED;
1114         }
1115
1116         result = DISPATCHED;
1117         if ((action < 0) && arg.empty())
1118                 return FINISHED;
1119
1120         if (the_locking_inset) {
1121                 result = the_locking_inset->localDispatch(bv, action, arg);
1122                 if (result == DISPATCHED_NOUPDATE)
1123                         return result;
1124                 else if (result == DISPATCHED) {
1125                         updateLocal(bv, CURSOR_PAR, false);
1126                         return result;
1127                 } else if (result >= FINISHED) {
1128                         switch (result) {
1129                         case FINISHED_RIGHT:
1130                                 moveRightIntern(bv, false, false);
1131                                 result = DISPATCHED;
1132                                 break;
1133                         case FINISHED_UP:
1134                                 if ((result = moveUp(bv)) >= FINISHED) {
1135                                         updateLocal(bv, CURSOR, false);
1136                                         bv->unlockInset(this);
1137                                 }
1138                                 break;
1139                         case FINISHED_DOWN:
1140                                 if ((result = moveDown(bv)) >= FINISHED) {
1141                                         updateLocal(bv, CURSOR, false);
1142                                         bv->unlockInset(this);
1143                                 }
1144                                 break;
1145                         default:
1146                                 result = DISPATCHED;
1147                                 break;
1148                         }
1149                         the_locking_inset = 0;
1150 #ifdef WITH_WARNINGS
1151 #warning I changed this to always return Dispatched maybe it is wrong (20011001 Jug)
1152 #endif
1153                         updateLocal(bv, CURSOR, false);
1154                         return result;
1155                 }
1156         }
1157         hideInsetCursor(bv);
1158         bool clear = false;
1159         if (!lt) {
1160                 lt = getLyXText(bv);
1161                 clear = true;
1162         }
1163         int updwhat = 0;
1164         int updflag = false;
1165         switch (action) {
1166         // Normal chars
1167         case LFUN_SELFINSERT:
1168                 if (bv->buffer()->isReadonly()) {
1169 //          setErrorMessage(N_("Document is read only"));
1170                         break;
1171                 }
1172                 if (!arg.empty()) {
1173                         /* Automatically delete the currently selected
1174                          * text and replace it with what is being
1175                          * typed in now. Depends on lyxrc settings
1176                          * "auto_region_delete", which defaults to
1177                          * true (on). */
1178
1179                         setUndo(bv, Undo::INSERT,
1180                                 lt->cursor.par(), lt->cursor.par()->next());
1181                         bv->setState();
1182                         if (lyxrc.auto_region_delete) {
1183                                 if (lt->selection.set()) {
1184                                         lt->cutSelection(bv, false);
1185                                 }
1186                         }
1187                         lt->clearSelection();
1188                         for (string::size_type i = 0; i < arg.length(); ++i) {
1189                                 bv->owner()->getIntl()->getTrans().TranslateAndInsert(arg[i], lt);
1190                         }
1191                 }
1192                 lt->selection.cursor = lt->cursor;
1193                 updwhat = CURSOR_PAR;
1194                 updflag = true;
1195                 result = DISPATCHED_NOUPDATE;
1196                 break;
1197                 // --- Cursor Movements -----------------------------------
1198         case LFUN_RIGHTSEL:
1199                 finishUndo();
1200                 moveRight(bv, false, true);
1201                 lt->setSelection(bv);
1202                 updwhat = SELECTION;
1203                 break;
1204         case LFUN_RIGHT:
1205                 result = moveRight(bv);
1206                 finishUndo();
1207                 updwhat = CURSOR;
1208                 break;
1209         case LFUN_LEFTSEL:
1210                 finishUndo();
1211                 moveLeft(bv, false, true);
1212                 lt->setSelection(bv);
1213                 updwhat = SELECTION;
1214                 break;
1215         case LFUN_LEFT:
1216                 finishUndo();
1217                 result = moveLeft(bv);
1218                 updwhat = CURSOR;
1219                 break;
1220         case LFUN_DOWNSEL:
1221                 finishUndo();
1222                 moveDown(bv);
1223                 lt->setSelection(bv);
1224                 updwhat = SELECTION;
1225                 break;
1226         case LFUN_DOWN:
1227                 finishUndo();
1228                 result = moveDown(bv);
1229                 updwhat = CURSOR;
1230                 break;
1231         case LFUN_UPSEL:
1232                 finishUndo();
1233                 moveUp(bv);
1234                 lt->setSelection(bv);
1235                 updwhat = SELECTION;
1236                 break;
1237         case LFUN_UP:
1238                 finishUndo();
1239                 result = moveUp(bv);
1240                 updwhat = CURSOR;
1241                 break;
1242         case LFUN_HOME:
1243                 finishUndo();
1244                 lt->cursorHome(bv);
1245                 updwhat = CURSOR;
1246                 break;
1247         case LFUN_END:
1248                 lt->cursorEnd(bv);
1249                 updwhat = CURSOR;
1250                 break;
1251         case LFUN_BACKSPACE: {
1252                 setUndo(bv, Undo::DELETE,
1253                         lt->cursor.par(), lt->cursor.par()->next());
1254                 if (lt->selection.set())
1255                         lt->cutSelection(bv);
1256                 else
1257                         lt->backspace(bv);
1258                 updwhat = CURSOR_PAR;
1259                 updflag = true;
1260         }
1261         break;
1262
1263         case LFUN_DELETE: {
1264                 setUndo(bv, Undo::DELETE,
1265                         lt->cursor.par(), lt->cursor.par()->next());
1266                 if (lt->selection.set()) {
1267                         lt->cutSelection(bv);
1268                 } else {
1269                         lt->Delete(bv);
1270                 }
1271                 updwhat = CURSOR_PAR;
1272                 updflag = true;
1273         }
1274         break;
1275
1276         case LFUN_CUT: {
1277                 setUndo(bv, Undo::DELETE,
1278                         lt->cursor.par(), lt->cursor.par()->next());
1279                 lt->cutSelection(bv);
1280                 updwhat = CURSOR_PAR;
1281                 updflag = true;
1282         }
1283         break;
1284
1285         case LFUN_COPY:
1286                 finishUndo();
1287                 lt->copySelection(bv);
1288                 updwhat = CURSOR_PAR;
1289                 break;
1290         case LFUN_PASTESELECTION:
1291         {
1292                 string const clip(bv->getClipboard());
1293
1294                 if (clip.empty())
1295                         break;
1296                 if (arg == "paragraph") {
1297                         lt->insertStringAsParagraphs(bv, clip);
1298                 } else {
1299                         lt->insertStringAsLines(bv, clip);
1300                 }
1301                 updwhat = CURSOR_PAR;
1302                 updflag = true;
1303                 break;
1304         }
1305         case LFUN_PASTE: {
1306                 if (!autoBreakRows) {
1307
1308                         if (CutAndPaste::nrOfParagraphs() > 1) {
1309                                 Alert::alert(_("Impossible operation"),
1310                                                    _("Cannot include more than one paragraph!"),
1311                                                    _("Sorry."));
1312                                 break;
1313                         }
1314                 }
1315                 setUndo(bv, Undo::INSERT,
1316                         lt->cursor.par(), lt->cursor.par()->next());
1317                 lt->pasteSelection(bv);
1318                 updwhat = CURSOR_PAR;
1319                 updflag = true;
1320         }
1321         break;
1322
1323         case LFUN_BREAKPARAGRAPH:
1324                 if (!autoBreakRows) {
1325                         result = DISPATCHED;
1326                         break;
1327                 }
1328                 lt->breakParagraph(bv, 0);
1329                 updwhat = CURSOR | FULL;
1330                 updflag = true;
1331                 break;
1332         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1333                 if (!autoBreakRows) {
1334                         result = DISPATCHED;
1335                         break;
1336                 }
1337                 lt->breakParagraph(bv, 1);
1338                 updwhat = CURSOR | FULL;
1339                 updflag = true;
1340                 break;
1341
1342         case LFUN_BREAKLINE: {
1343                 if (!autoBreakRows) {
1344                         result = DISPATCHED;
1345                         break;
1346                 }
1347                 setUndo(bv, Undo::INSERT,
1348                         lt->cursor.par(), lt->cursor.par()->next());
1349                 lt->insertChar(bv, Paragraph::META_NEWLINE);
1350                 updwhat = CURSOR | CURSOR_PAR;
1351                 updflag = true;
1352         }
1353         break;
1354
1355         case LFUN_LAYOUT:
1356                 // do not set layouts on non breakable textinsets
1357                 if (autoBreakRows) {
1358                         string cur_layout = cpar(bv)->layout();
1359
1360                         // Derive layout number from given argument (string)
1361                         // and current buffer's textclass (number). */
1362                         textclass_type tclass = bv->buffer()->params.textclass;
1363                         string layout = arg;
1364                         bool hasLayout = textclasslist[tclass].hasLayout(layout);
1365
1366                         // If the entry is obsolete, use the new one instead.
1367                         if (hasLayout) {
1368                                 string const & obs =
1369                                         textclasslist[tclass][layout].
1370                                         obsoleted_by();
1371                                 if (!obs.empty())
1372                                         layout = obs;
1373                         }
1374
1375                         // see if we found the layout number:
1376                         if (!hasLayout) {
1377                                 string const msg = string(N_("Layout ")) + arg + N_(" not known");
1378                                 bv->owner()->getLyXFunc()->dispatch(LFUN_MESSAGE, msg);
1379                                 break;
1380                         }
1381
1382                         if (cur_layout != layout) {
1383                                 cur_layout = layout;
1384                                 lt->setLayout(bv, layout);
1385                                 bv->owner()->setLayout(cpar(bv)->layout());
1386                                 updwhat = CURSOR_PAR;
1387                                 updflag = true;
1388                         }
1389                 } else {
1390                         // reset the layout box
1391                         bv->owner()->setLayout(cpar(bv)->layout());
1392                 }
1393                 break;
1394         case LFUN_PARAGRAPH_SPACING:
1395                 // This one is absolutely not working. When fiddling with this
1396                 // it also seems to me that the paragraphs inside the insettext
1397                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1398         {
1399                 Paragraph * par = lt->cursor.par();
1400                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
1401                 float cur_value = 1.0;
1402                 if (cur_spacing == Spacing::Other) {
1403                         cur_value = par->params().spacing().getValue();
1404                 }
1405
1406                 istringstream istr(arg.c_str());
1407                 string tmp;
1408                 istr >> tmp;
1409                 Spacing::Space new_spacing = cur_spacing;
1410                 float new_value = cur_value;
1411                 if (tmp.empty()) {
1412                         lyxerr << "Missing argument to `paragraph-spacing'"
1413                                    << endl;
1414                 } else if (tmp == "single") {
1415                         new_spacing = Spacing::Single;
1416                 } else if (tmp == "onehalf") {
1417                         new_spacing = Spacing::Onehalf;
1418                 } else if (tmp == "double") {
1419                         new_spacing = Spacing::Double;
1420                 } else if (tmp == "other") {
1421                         new_spacing = Spacing::Other;
1422                         float tmpval = 0.0;
1423                         istr >> tmpval;
1424                         lyxerr << "new_value = " << tmpval << endl;
1425                         if (tmpval != 0.0)
1426                                 new_value = tmpval;
1427                 } else if (tmp == "default") {
1428                         new_spacing = Spacing::Default;
1429                 } else {
1430                         lyxerr << _("Unknown spacing argument: ")
1431                                    << arg << endl;
1432                 }
1433                 if (cur_spacing != new_spacing || cur_value != new_value) {
1434                         par->params().spacing(Spacing(new_spacing, new_value));
1435                         updwhat = CURSOR_PAR;
1436                         updflag = true;
1437                 }
1438         }
1439         break;
1440
1441         default:
1442                 if (!bv->Dispatch(action, arg))
1443                         result = UNDISPATCHED;
1444                 break;
1445         }
1446
1447         if (clear)
1448                 lt = 0;
1449         if (updwhat > 0)
1450                 updateLocal(bv, updwhat, updflag);
1451         /// If the action has deleted all text in the inset, we need to change the
1452         // language to the language of the surronding text.
1453         if (!was_empty && par->size() == 0 && !par->next()) {
1454                 LyXFont font(LyXFont::ALL_IGNORE);
1455                 font.setLanguage(bv->getParentLanguage(this));
1456                 setFont(bv, font, false);
1457         }
1458
1459         if (result >= FINISHED)
1460                 bv->unlockInset(this);
1461
1462         if (result == DISPATCHED_NOUPDATE && (need_update & FULL))
1463                 result = DISPATCHED;
1464         return result;
1465 }
1466
1467
1468 int InsetText::latex(Buffer const * buf, ostream & os, bool, bool) const
1469 {
1470         TexRow texrow;
1471         buf->latexParagraphs(os, par, 0, texrow);
1472         return texrow.rows();
1473 }
1474
1475
1476 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1477 {
1478         Paragraph * p = par;
1479         unsigned int lines = 0;
1480
1481         while (p) {
1482                 string const tmp = buf->asciiParagraph(p, linelen, p->previous()==0);
1483                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1484                 os << tmp;
1485                 p = p->next();
1486         }
1487         return lines;
1488 }
1489
1490
1491 int InsetText::docbook(Buffer const * buf, ostream & os) const
1492 {
1493         Paragraph * p = par;
1494         unsigned int lines = 0;
1495
1496         vector<string> environment_stack(10);
1497         vector<string> environment_inner(10);
1498
1499         int const command_depth = 0;
1500         string item_name;
1501
1502         Paragraph::depth_type depth = 0; // paragraph depth
1503
1504         while (p) {
1505                 string sgmlparam;
1506                 int desc_on = 0; // description mode
1507
1508                 LyXLayout const & style =
1509                         textclasslist[buf->params.textclass][p->layout()];
1510
1511                 // environment tag closing
1512                 for (; depth > p->params().depth(); --depth) {
1513                         if (environment_inner[depth] != "!-- --") {
1514                                 item_name = "listitem";
1515                                 buf->sgmlCloseTag(os, command_depth + depth,
1516                                              item_name);
1517                                 if (environment_inner[depth] == "varlistentry")
1518                                         buf->sgmlCloseTag(os, depth+command_depth,
1519                                                      environment_inner[depth]);
1520                         }
1521                         buf->sgmlCloseTag(os, depth + command_depth,
1522                                      environment_stack[depth]);
1523                         environment_stack[depth].erase();
1524                         environment_inner[depth].erase();
1525                 }
1526
1527                 if (depth == p->params().depth()
1528                    && environment_stack[depth] != style.latexname()
1529                    && !environment_stack[depth].empty()) {
1530                         if (environment_inner[depth] != "!-- --") {
1531                                 item_name= "listitem";
1532                                 buf->sgmlCloseTag(os, command_depth+depth,
1533                                                   item_name);
1534                                 if (environment_inner[depth] == "varlistentry")
1535                                         buf->sgmlCloseTag(os,
1536                                                           depth + command_depth,
1537                                                           environment_inner[depth]);
1538                         }
1539
1540                         buf->sgmlCloseTag(os, depth + command_depth,
1541                                           environment_stack[depth]);
1542
1543                         environment_stack[depth].erase();
1544                         environment_inner[depth].erase();
1545                 }
1546
1547                 // Write opening SGML tags.
1548                 switch (style.latextype) {
1549                 case LATEX_PARAGRAPH:
1550                         buf->sgmlOpenTag(os, depth + command_depth,
1551                                          style.latexname());
1552                         break;
1553
1554                 case LATEX_COMMAND:
1555                         buf->sgmlError(p, 0,
1556                                        _("Error : LatexType Command not allowed here.\n"));
1557                         return -1;
1558                         break;
1559
1560                 case LATEX_ENVIRONMENT:
1561                 case LATEX_ITEM_ENVIRONMENT:
1562                         if (depth < p->params().depth()) {
1563                                 depth = p->params().depth();
1564                                 environment_stack[depth].erase();
1565                         }
1566
1567                         if (environment_stack[depth] != style.latexname()) {
1568                                 if (environment_stack.size() == depth + 1) {
1569                                         environment_stack.push_back("!-- --");
1570                                         environment_inner.push_back("!-- --");
1571                                 }
1572                                 environment_stack[depth] = style.latexname();
1573                                 environment_inner[depth] = "!-- --";
1574                                 buf->sgmlOpenTag(os, depth + command_depth,
1575                                                  environment_stack[depth]);
1576                         } else {
1577                                 if (environment_inner[depth] != "!-- --") {
1578                                         item_name= "listitem";
1579                                         buf->sgmlCloseTag(os,
1580                                                           command_depth + depth,
1581                                                           item_name);
1582                                         if (environment_inner[depth] == "varlistentry")
1583                                                 buf->sgmlCloseTag(os,
1584                                                                   depth + command_depth,
1585                                                                   environment_inner[depth]);
1586                                 }
1587                         }
1588
1589                         if (style.latextype == LATEX_ENVIRONMENT) {
1590                                 if (!style.latexparam().empty()) {
1591                                         if (style.latexparam() == "CDATA")
1592                                                 os << "<![CDATA[";
1593                                         else
1594                                                 buf->sgmlOpenTag(os, depth + command_depth,
1595                                                                  style.latexparam());
1596                                 }
1597                                 break;
1598                         }
1599
1600                         desc_on = (style.labeltype == LABEL_MANUAL);
1601
1602                         if (desc_on)
1603                                 environment_inner[depth]= "varlistentry";
1604                         else
1605                                 environment_inner[depth]= "listitem";
1606
1607                         buf->sgmlOpenTag(os, depth + 1 + command_depth,
1608                                          environment_inner[depth]);
1609
1610                         if (desc_on) {
1611                                 item_name= "term";
1612                                 buf->sgmlOpenTag(os, depth + 1 + command_depth,
1613                                                  item_name);
1614                         } else {
1615                                 item_name= "para";
1616                                 buf->sgmlOpenTag(os, depth + 1 + command_depth,
1617                                                  item_name);
1618                         }
1619                         break;
1620                 default:
1621                         buf->sgmlOpenTag(os, depth + command_depth,
1622                                          style.latexname());
1623                         break;
1624                 }
1625
1626                 buf->simpleDocBookOnePar(os, p, desc_on,
1627                                          depth + 1 + command_depth);
1628                 p = p->next();
1629
1630                 string end_tag;
1631                 // write closing SGML tags
1632                 switch (style.latextype) {
1633                 case LATEX_ENVIRONMENT:
1634                         if (!style.latexparam().empty()) {
1635                                 if (style.latexparam() == "CDATA")
1636                                         os << "]]>";
1637                                 else
1638                                         buf->sgmlCloseTag(os, depth + command_depth,
1639                                                           style.latexparam());
1640                         }
1641                         break;
1642                 case LATEX_ITEM_ENVIRONMENT:
1643                         if (desc_on == 1) break;
1644                         end_tag= "para";
1645                         buf->sgmlCloseTag(os, depth + 1 + command_depth, end_tag);
1646                         break;
1647                 case LATEX_PARAGRAPH:
1648                         buf->sgmlCloseTag(os, depth + command_depth, style.latexname());
1649                         break;
1650                 default:
1651                         buf->sgmlCloseTag(os, depth + command_depth, style.latexname());
1652                         break;
1653                 }
1654         }
1655
1656         // Close open tags
1657         for (int d = depth; d >= 0; --d) {
1658                 if (!environment_stack[depth].empty()) {
1659                         if (environment_inner[depth] != "!-- --") {
1660                                 item_name = "listitem";
1661                                 buf->sgmlCloseTag(os, command_depth + depth,
1662                                                   item_name);
1663                                if (environment_inner[depth] == "varlistentry")
1664                                        buf->sgmlCloseTag(os, depth + command_depth,
1665                                                          environment_inner[depth]);
1666                         }
1667
1668                         buf->sgmlCloseTag(os, depth + command_depth,
1669                                           environment_stack[depth]);
1670                 }
1671         }
1672
1673         return lines;
1674 }
1675
1676
1677 void InsetText::validate(LaTeXFeatures & features) const
1678 {
1679         Paragraph * p = par;
1680         while (p) {
1681                 p->validate(features);
1682                 p = p->next();
1683         }
1684 }
1685
1686
1687 int InsetText::beginningOfMainBody(Buffer const * buf, Paragraph * p) const
1688 {
1689         if (textclasslist[buf->params.textclass][p->layout()].labeltype != LABEL_MANUAL)
1690                 return 0;
1691         else
1692                 return p->beginningOfMainBody();
1693 }
1694
1695
1696 void InsetText::getCursorPos(BufferView * bv,
1697                              int & x, int & y) const
1698 {
1699         if (the_locking_inset) {
1700                 the_locking_inset->getCursorPos(bv, x, y);
1701                 return;
1702         }
1703         x = cx(bv);
1704         y = cy(bv);
1705 }
1706
1707
1708 unsigned int InsetText::insetInInsetY()
1709 {
1710         if (!the_locking_inset)
1711                 return 0;
1712
1713         return (inset_y + the_locking_inset->insetInInsetY());
1714 }
1715
1716
1717 void InsetText::toggleInsetCursor(BufferView * bv)
1718 {
1719         if (the_locking_inset) {
1720                 the_locking_inset->toggleInsetCursor(bv);
1721                 return;
1722         }
1723
1724         LyXFont const font(getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv)));
1725
1726         int const asc = lyxfont::maxAscent(font);
1727         int const desc = lyxfont::maxDescent(font);
1728
1729         if (isCursorVisible())
1730                 bv->hideLockedInsetCursor();
1731         else
1732                 bv->showLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1733         toggleCursorVisible();
1734 }
1735
1736
1737 void InsetText::showInsetCursor(BufferView * bv, bool show)
1738 {
1739         if (the_locking_inset) {
1740                 the_locking_inset->showInsetCursor(bv, show);
1741                 return;
1742         }
1743         if (!isCursorVisible()) {
1744                 LyXFont const font =
1745                         getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1746
1747                 int const asc = lyxfont::maxAscent(font);
1748                 int const desc = lyxfont::maxDescent(font);
1749
1750                 bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1751                 if (show)
1752                         bv->showLockedInsetCursor(cx(bv), cy(bv), asc, desc);
1753                 setCursorVisible(true);
1754         }
1755 }
1756
1757
1758 void InsetText::hideInsetCursor(BufferView * bv)
1759 {
1760         if (isCursorVisible()) {
1761                 bv->hideLockedInsetCursor();
1762                 setCursorVisible(false);
1763         }
1764         if (the_locking_inset)
1765                 the_locking_inset->hideInsetCursor(bv);
1766 }
1767
1768
1769 void InsetText::fitInsetCursor(BufferView * bv) const
1770 {
1771         if (the_locking_inset) {
1772                 the_locking_inset->fitInsetCursor(bv);
1773                 return;
1774         }
1775         LyXFont const font =
1776                 getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1777
1778         int const asc = lyxfont::maxAscent(font);
1779         int const desc = lyxfont::maxDescent(font);
1780
1781         if (bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc))
1782                 need_update |= FULL;
1783 }
1784
1785
1786 UpdatableInset::RESULT
1787 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1788 {
1789         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1790                 return moveLeftIntern(bv, false, activate_inset, selecting);
1791         else
1792                 return moveRightIntern(bv, false, activate_inset, selecting);
1793 }
1794
1795
1796 UpdatableInset::RESULT
1797 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1798 {
1799         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1800                 return moveRightIntern(bv, true, activate_inset, selecting);
1801         else
1802                 return moveLeftIntern(bv, true, activate_inset, selecting);
1803 }
1804
1805
1806 UpdatableInset::RESULT
1807 InsetText::moveRightIntern(BufferView * bv, bool behind,
1808                            bool activate_inset, bool selecting)
1809 {
1810         if (!cpar(bv)->next() && (cpos(bv) >= cpar(bv)->size()))
1811                 return FINISHED_RIGHT;
1812         if (activate_inset && checkAndActivateInset(bv, behind))
1813                 return DISPATCHED;
1814         getLyXText(bv)->cursorRight(bv);
1815         if (!selecting)
1816                 getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
1817         return DISPATCHED_NOUPDATE;
1818 }
1819
1820
1821 UpdatableInset::RESULT
1822 InsetText::moveLeftIntern(BufferView * bv, bool behind,
1823                           bool activate_inset, bool selecting)
1824 {
1825         if (!cpar(bv)->previous() && (cpos(bv) <= 0))
1826                 return FINISHED;
1827         getLyXText(bv)->cursorLeft(bv);
1828         if (!selecting)
1829                 getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
1830         if (activate_inset && checkAndActivateInset(bv, behind))
1831                 return DISPATCHED;
1832         return DISPATCHED_NOUPDATE;
1833 }
1834
1835
1836 UpdatableInset::RESULT
1837 InsetText::moveUp(BufferView * bv)
1838 {
1839         if (!crow(bv)->previous())
1840                 return FINISHED_UP;
1841         getLyXText(bv)->cursorUp(bv);
1842         return DISPATCHED_NOUPDATE;
1843 }
1844
1845
1846 UpdatableInset::RESULT
1847 InsetText::moveDown(BufferView * bv)
1848 {
1849         if (!crow(bv)->next())
1850                 return FINISHED_DOWN;
1851         getLyXText(bv)->cursorDown(bv);
1852         return DISPATCHED_NOUPDATE;
1853 }
1854
1855
1856 bool InsetText::insertInset(BufferView * bv, Inset * inset)
1857 {
1858         if (the_locking_inset) {
1859                 if (the_locking_inset->insetAllowed(inset))
1860                         return the_locking_inset->insertInset(bv, inset);
1861                 return false;
1862         }
1863         bool clear = false;
1864         if (!lt) {
1865                 lt = getLyXText(bv);
1866                 clear = true;
1867         }
1868         setUndo(bv, Undo::FINISH, lt->cursor.par(), lt->cursor.par()->next());
1869         freezeUndo();
1870         inset->setOwner(this);
1871         hideInsetCursor(bv);
1872         lt->insertInset(bv, inset);
1873         bv->fitCursor();
1874         if (clear)
1875                 lt = 0;
1876         updateLocal(bv, CURSOR_PAR|CURSOR, true);
1877         unFreezeUndo();
1878         return true;
1879 }
1880
1881
1882 bool InsetText::insetAllowed(Inset::Code code) const
1883 {
1884         // in_insetAllowed is a really gross hack,
1885         // to allow us to call the owner's insetAllowed
1886         // without stack overflow, which can happen
1887         // when the owner uses InsetCollapsable::insetAllowed()
1888         bool ret = true;
1889         if (in_insetAllowed)
1890                 return ret;
1891         in_insetAllowed = true;
1892         if (the_locking_inset)
1893                 ret = the_locking_inset->insetAllowed(code);
1894         else if (owner())
1895                 ret = owner()->insetAllowed(code);
1896         in_insetAllowed = false;
1897         return ret;
1898 }
1899
1900
1901 UpdatableInset * InsetText::getLockingInset() const
1902 {
1903         return the_locking_inset ? the_locking_inset->getLockingInset() :
1904                 const_cast<InsetText *>(this);
1905 }
1906
1907
1908 UpdatableInset * InsetText::getFirstLockingInsetOfType(Inset::Code c)
1909 {
1910         if (c == lyxCode())
1911                 return this;
1912         if (the_locking_inset)
1913                 return the_locking_inset->getFirstLockingInsetOfType(c);
1914         return 0;
1915 }
1916
1917
1918 bool InsetText::showInsetDialog(BufferView * bv) const
1919 {
1920         if (the_locking_inset)
1921                 return the_locking_inset->showInsetDialog(bv);
1922         return false;
1923 }
1924
1925
1926 vector<string> const InsetText::getLabelList() const
1927 {
1928         vector<string> label_list;
1929
1930         Paragraph * tpar = par;
1931         while (tpar) {
1932                 Paragraph::inset_iterator beg = tpar->inset_iterator_begin();
1933                 Paragraph::inset_iterator end = tpar->inset_iterator_end();
1934                 for (; beg != end; ++beg) {
1935                         vector<string> const l = (*beg)->getLabelList();
1936                         label_list.insert(label_list.end(), l.begin(), l.end());
1937                 }
1938                 tpar = tpar->next();
1939         }
1940         return label_list;
1941 }
1942
1943
1944 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1945                         bool selectall)
1946 {
1947         if (the_locking_inset) {
1948                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1949                 return;
1950         }
1951         if ((!par->next() && !par->size()) || !cpar(bv)->size()) {
1952                 getLyXText(bv)->setFont(bv, font, toggleall);
1953                 return;
1954         }
1955         bool clear = false;
1956         if (!lt) {
1957                 lt = getLyXText(bv);
1958                 clear = true;
1959         }
1960         if (lt->selection.set()) {
1961                 setUndo(bv, Undo::EDIT, lt->cursor.par(), lt->cursor.par()->next());
1962         }
1963         if (selectall)
1964                 selectAll(bv);
1965         lt->toggleFree(bv, font, toggleall);
1966         if (selectall)
1967                 lt->clearSelection();
1968         bv->fitCursor();
1969         bool flag = (selectall || lt->selection.set());
1970         if (clear)
1971                 lt = 0;
1972         if (flag)
1973                 updateLocal(bv, FULL, true);
1974         else
1975                 updateLocal(bv, CURSOR_PAR, true);
1976 }
1977
1978
1979 bool InsetText::checkAndActivateInset(BufferView * bv, bool behind)
1980 {
1981         if (cpar(bv)->isInset(cpos(bv))) {
1982                 unsigned int x;
1983                 unsigned int y;
1984                 Inset * inset =
1985                         static_cast<UpdatableInset*>(cpar(bv)->getInset(cpos(bv)));
1986                 if (!isHighlyEditableInset(inset))
1987                         return false;
1988                 LyXFont const font =
1989                         getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1990                 if (behind) {
1991                         x = inset->width(bv, font);
1992                         y = font.isRightToLeft() ? 0 : inset->descent(bv, font);
1993                 } else {
1994                         x = 0;
1995                         y = font.isRightToLeft() ? inset->descent(bv, font) : 0;
1996                 }
1997                 //inset_x = cx(bv) - top_x + drawTextXOffset;
1998                 //inset_y = cy(bv) + drawTextYOffset;
1999                 inset->edit(bv, x, y, 0);
2000                 if (!the_locking_inset)
2001                         return false;
2002                 updateLocal(bv, CURSOR, false);
2003                 return true;
2004         }
2005         return false;
2006 }
2007
2008
2009 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
2010                                       int button)
2011 {
2012         x -= drawTextXOffset;
2013         int dummyx = x;
2014         int dummyy = y + insetAscent;
2015         Inset * inset = bv->checkInsetHit(getLyXText(bv), dummyx, dummyy);
2016
2017         if (inset) {
2018                 if (x < 0)
2019                         x = insetWidth;
2020                 if (y < 0)
2021                         y = insetDescent;
2022                 inset_x = cx(bv) - top_x + drawTextXOffset;
2023                 inset_y = cy(bv) + drawTextYOffset;
2024                 inset->edit(bv, x - inset_x, y - inset_y, button);
2025                 if (!the_locking_inset)
2026                         return false;
2027                 updateLocal(bv, CURSOR, false);
2028                 return true;
2029         }
2030         return false;
2031 }
2032
2033
2034 int InsetText::getMaxWidth(BufferView * bv, UpdatableInset const * inset) const
2035 {
2036 #if 0
2037         int w = UpdatableInset::getMaxWidth(bv, inset);
2038         if (w < 0) {
2039                 return -1;
2040         }
2041         if (owner()) {
2042                 w = w - top_x + owner()->x();
2043                 return w;
2044         }
2045         w -= (2 * TEXT_TO_INSET_OFFSET);
2046         return w - top_x;
2047 #else
2048         return UpdatableInset::getMaxWidth(bv, inset);
2049 #endif
2050 }
2051
2052
2053 void InsetText::setParagraphData(Paragraph * p, bool same_id)
2054 {
2055         // we have to unlock any locked inset otherwise we're in troubles
2056         the_locking_inset = 0;
2057         while (par) {
2058                 Paragraph * tmp = par->next();
2059                 delete par;
2060                 par = tmp;
2061         }
2062
2063         par = new Paragraph(*p, same_id);
2064         par->setInsetOwner(this);
2065         Paragraph * np = par;
2066         while (p->next()) {
2067                 p = p->next();
2068                 np->next(new Paragraph(*p, same_id));
2069                 np->next()->previous(np);
2070                 np = np->next();
2071                 np->setInsetOwner(this);
2072         }
2073         reinitLyXText();
2074         need_update = INIT;
2075 }
2076
2077
2078 void InsetText::setText(string const & data, LyXFont const & font)
2079 {
2080         clear();
2081         for (unsigned int i=0; i < data.length(); ++i)
2082                 par->insertChar(i, data[i], font);
2083         reinitLyXText();
2084 }
2085
2086
2087 void InsetText::setAutoBreakRows(bool flag)
2088 {
2089         if (flag != autoBreakRows) {
2090                 autoBreakRows = flag;
2091                 if (!flag)
2092                         removeNewlines();
2093                 need_update = INIT;
2094         }
2095 }
2096
2097
2098 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
2099 {
2100         if (how != drawFrame_) {
2101                 drawFrame_ = how;
2102                 if (bv)
2103                         updateLocal(bv, DRAW_FRAME, false);
2104         }
2105 }
2106
2107
2108 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
2109 {
2110         if (frame_color != col) {
2111                 frame_color = col;
2112                 if (bv)
2113                         updateLocal(bv, DRAW_FRAME, false);
2114         }
2115 }
2116
2117
2118 int InsetText::cx(BufferView * bv) const
2119 {
2120         // we do nothing dangerous so we use a local cache
2121         LyXText * llt = getLyXText(bv);
2122         int x = llt->cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
2123         if (the_locking_inset) {
2124                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2125                                             llt->cursor.pos());
2126                 if (font.isVisibleRightToLeft())
2127                         x -= the_locking_inset->width(bv, font);
2128         }
2129         return x;
2130 }
2131
2132
2133 int InsetText::cy(BufferView * bv) const
2134 {
2135         LyXFont font;
2136         return getLyXText(bv)->cursor.y() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2137 }
2138
2139
2140 pos_type InsetText::cpos(BufferView * bv) const
2141 {
2142         return getLyXText(bv)->cursor.pos();
2143 }
2144
2145
2146 Paragraph * InsetText::cpar(BufferView * bv) const
2147 {
2148         return getLyXText(bv)->cursor.par();
2149 }
2150
2151
2152 bool InsetText::cboundary(BufferView * bv) const
2153 {
2154         return getLyXText(bv)->cursor.boundary();
2155 }
2156
2157
2158 Row * InsetText::crow(BufferView * bv) const
2159 {
2160         return getLyXText(bv)->cursor.row();
2161 }
2162
2163
2164 LyXText * InsetText::getLyXText(BufferView const * lbv,
2165                                 bool const recursive) const
2166 {
2167         if (cached_bview == lbv) {
2168                 if (recursive && the_locking_inset)
2169                         return the_locking_inset->getLyXText(lbv, true);
2170                 LyXText * lt = cached_text.get();
2171                 lyx::Assert(lt && lt->firstRow()->par() == par);
2172                 return lt;
2173         }
2174         // Super UGLY! (Lgb)
2175         BufferView * bv = const_cast<BufferView *>(lbv);
2176
2177         cached_bview = bv;
2178         Cache::iterator it = cache.find(bv);
2179
2180         if (it != cache.end()) {
2181                 if (do_reinit) {
2182                         reinitLyXText();
2183                 } else if (do_resize) {
2184                         resizeLyXText(do_resize);
2185                 } else {
2186                         if (lt || !it->second.remove) {
2187                                 lyx::Assert(it->second.text.get());
2188                                 cached_text = it->second.text;
2189                                 if (recursive && the_locking_inset) {
2190                                         return the_locking_inset->getLyXText(bv, true);
2191                                 }
2192                                 return cached_text.get();
2193                         } else if (it->second.remove) {
2194                                 if (locked) {
2195                                         saveLyXTextState(it->second.text.get());
2196                                 } else {
2197                                         sstate.lpar = 0;
2198                                 }
2199                         }
2200                         //
2201                         // when we have to reinit the existing LyXText!
2202                         //
2203                         it->second.text->init(bv);
2204                         restoreLyXTextState(bv, it->second.text.get());
2205                         it->second.remove = false;
2206                 }
2207                 cached_text = it->second.text;
2208                 if (the_locking_inset && recursive) {
2209                         return the_locking_inset->getLyXText(bv);
2210                 }
2211                 return cached_text.get();
2212         }
2213         ///
2214         // we are here only if we don't have a BufferView * in the cache!!!
2215         ///
2216         cached_text.reset(new LyXText(const_cast<InsetText *>(this)));
2217         cached_text->init(bv);
2218         restoreLyXTextState(bv, cached_text.get());
2219
2220         cache.insert(make_pair(bv, cached_text));
2221
2222         if (the_locking_inset && recursive) {
2223                 return the_locking_inset->getLyXText(bv);
2224         }
2225         return cached_text.get();
2226 }
2227
2228
2229 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
2230 {
2231         cached_bview = 0;
2232
2233         Cache::iterator it = cache.find(bv);
2234
2235         if (it == cache.end()) {
2236                 return;
2237         }
2238
2239         lyx::Assert(it->second.text.get());
2240
2241         it->second.remove = true;
2242         if (recursive) {
2243                 /// then remove all LyXText in text-insets
2244                 Paragraph * p = par;
2245                 for (; p; p = p->next()) {
2246                         p->deleteInsetsLyXText(bv);
2247                 }
2248         }
2249 }
2250
2251
2252 void InsetText::resizeLyXText(BufferView * bv, bool force) const
2253 {
2254         if (lt) {
2255                 // we cannot resize this because we are in use!
2256                 // so do this on the next possible getLyXText()
2257                 do_resize = bv;
2258                 return;
2259         }
2260         do_resize = 0;
2261 //      lyxerr << "InsetText::resizeLyXText\n";
2262         if (!par->next() && !par->size()) { // no data, resize not neccessary!
2263                 // we have to do this as a fixed width may have changed!
2264                 LyXText * t = getLyXText(bv);
2265                 saveLyXTextState(t);
2266                 t->init(bv, true);
2267                 restoreLyXTextState(bv, t);
2268                 return;
2269         }
2270         // one endless line, resize normally not necessary
2271         if (!force && getMaxWidth(bv, this) < 0)
2272                 return;
2273
2274         Cache::iterator it = cache.find(bv);
2275         if (it == cache.end()) {
2276                 return;
2277         }
2278         lyx::Assert(it->second.text.get());
2279
2280         LyXText * t = it->second.text.get();
2281         saveLyXTextState(t);
2282         for (Paragraph * p = par; p; p = p->next()) {
2283                 p->resizeInsetsLyXText(bv);
2284         }
2285         t->init(bv, true);
2286         restoreLyXTextState(bv, t);
2287         if (the_locking_inset) {
2288                 inset_x = cx(bv) - top_x + drawTextXOffset;
2289                 inset_y = cy(bv) + drawTextYOffset;
2290         }
2291
2292         if (bv->screen()) {
2293                 t->first_y = bv->screen()->topCursorVisible(t);
2294         }
2295         if (!owner()) {
2296                 updateLocal(bv, FULL, false);
2297                 // this will scroll the screen such that the cursor becomes visible
2298                 bv->updateScrollbar();
2299         } else {
2300                 need_update |= FULL;
2301         }
2302 }
2303
2304
2305 void InsetText::reinitLyXText() const
2306 {
2307         if (lt) {
2308                 // we cannot resize this because we are in use!
2309                 // so do this on the next possible getLyXText()
2310                 do_reinit = true;
2311                 return;
2312         }
2313         do_reinit = false;
2314         do_resize = 0;
2315 //      lyxerr << "InsetText::reinitLyXText\n";
2316         for(Cache::iterator it = cache.begin(); it != cache.end(); ++it) {
2317                 lyx::Assert(it->second.text.get());
2318
2319                 LyXText * t = it->second.text.get();
2320                 BufferView * bv = it->first;
2321
2322                 saveLyXTextState(t);
2323                 for (Paragraph * p = par; p; p = p->next()) {
2324                         p->resizeInsetsLyXText(bv);
2325                 }
2326                 t->init(bv, true);
2327                 restoreLyXTextState(bv, t);
2328                 if (the_locking_inset) {
2329                         inset_x = cx(bv) - top_x + drawTextXOffset;
2330                         inset_y = cy(bv) + drawTextYOffset;
2331                 }
2332                 if (bv->screen()) {
2333                         t->first_y = bv->screen()->topCursorVisible(t);
2334                 }
2335                 if (!owner()) {
2336                         updateLocal(bv, FULL, false);
2337                         // this will scroll the screen such that the cursor becomes visible
2338                         bv->updateScrollbar();
2339                 } else {
2340                         need_update = FULL;
2341                 }
2342         }
2343 }
2344
2345
2346 void InsetText::removeNewlines()
2347 {
2348         bool changed = false;
2349
2350         for (Paragraph * p = par; p; p = p->next()) {
2351                 for (int i = 0; i < p->size(); ++i) {
2352                         if (p->getChar(i) == Paragraph::META_NEWLINE) {
2353                                 changed = true;
2354                                 p->erase(i);
2355                         }
2356                 }
2357         }
2358         if (changed)
2359                 reinitLyXText();
2360 }
2361
2362
2363 bool InsetText::nodraw() const
2364 {
2365         if (the_locking_inset)
2366                 return the_locking_inset->nodraw();
2367         return UpdatableInset::nodraw();
2368 }
2369
2370
2371 int InsetText::scroll(bool recursive) const
2372 {
2373         int sx = UpdatableInset::scroll(false);
2374
2375         if (recursive && the_locking_inset)
2376                 sx += the_locking_inset->scroll(recursive);
2377
2378         return sx;
2379 }
2380
2381
2382 bool InsetText::doClearArea() const
2383 {
2384         return !locked || (need_update & (FULL|INIT));
2385 }
2386
2387
2388 void InsetText::selectAll(BufferView * bv)
2389 {
2390         getLyXText(bv)->cursorTop(bv);
2391         getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
2392         getLyXText(bv)->cursorBottom(bv);
2393         getLyXText(bv)->setSelection(bv);
2394 }
2395
2396
2397 void InsetText::clearSelection(BufferView * bv)
2398 {
2399         getLyXText(bv)->clearSelection();
2400 }
2401
2402
2403 void InsetText::clearInset(BufferView * bv, int baseline, bool & cleared) const
2404 {
2405         Painter & pain = bv->painter();
2406         int w = insetWidth;
2407         int h = insetAscent + insetDescent;
2408         int ty = baseline - insetAscent;
2409
2410         if (ty < 0) {
2411                 h += ty;
2412                 ty = 0;
2413         }
2414         if ((ty + h) > pain.paperHeight())
2415                 h = pain.paperHeight();
2416         if ((top_x + drawTextXOffset + w) > pain.paperWidth())
2417                 w = pain.paperWidth();
2418 //      w -= TEXT_TO_INSET_OFFSET;
2419         pain.fillRectangle(top_x, ty, w+1, h+1, backgroundColor());
2420         cleared = true;
2421         need_update = FULL;
2422         frame_is_visible = false;
2423 }
2424
2425
2426 Paragraph * InsetText::getParFromID(int id) const
2427 {
2428 #if 0
2429         Paragraph * result = par;
2430         Paragraph * ires = 0;
2431         while (result && result->id() != id) {
2432                 if ((ires = result->getParFromID(id)))
2433                         return ires;
2434                 result = result->next();
2435         }
2436         return result;
2437 #else
2438         Paragraph * tmp = par;
2439         while (tmp) {
2440                 if (tmp->id() == id) {
2441                         return tmp;
2442                 }
2443                 Paragraph * tmp2 = tmp->getParFromID(id);
2444                 if (tmp2 != 0) {
2445                         return tmp2;
2446                 }
2447                 tmp = tmp->next();
2448         }
2449         return 0;
2450 #endif
2451 }
2452
2453
2454 Paragraph * InsetText::firstParagraph() const
2455 {
2456         Paragraph * result;
2457         if (the_locking_inset)
2458                 if ((result = the_locking_inset->firstParagraph()))
2459                         return result;
2460         return par;
2461 }
2462
2463
2464 Paragraph * InsetText::getFirstParagraph(int i) const
2465 {
2466         return (i == 0) ? par : 0;
2467 }
2468
2469
2470 LyXCursor const & InsetText::cursor(BufferView * bv) const
2471 {
2472                 if (the_locking_inset)
2473                                 return the_locking_inset->cursor(bv);
2474                 return getLyXText(bv)->cursor;
2475 }
2476
2477
2478 Paragraph * InsetText::paragraph() const
2479 {
2480         return par;
2481 }
2482
2483
2484 void InsetText::paragraph(Paragraph * p)
2485 {
2486         // GENERAL COMMENT: We don't have to free the old paragraphs as the
2487         // caller of this function has to take care of it. This IS important
2488         // as we could have to insert a paragraph before this one and just
2489         // link the actual to a new ones next and set it with this function
2490         // and are done!
2491         par = p;
2492         // set ourself as owner for all the paragraphs inserted!
2493         Paragraph * np = par;
2494         while (np) {
2495                 np->setInsetOwner(this);
2496                 np = np->next();
2497         }
2498         reinitLyXText();
2499         // redraw myself when asked for
2500         need_update = INIT;
2501 }
2502
2503
2504 Inset * InsetText::getInsetFromID(int id_arg) const
2505 {
2506         if (id_arg == id())
2507                 return const_cast<InsetText *>(this);
2508
2509         Paragraph * lp = par;
2510
2511         while (lp) {
2512                 for (Paragraph::inset_iterator it = lp->inset_iterator_begin(),
2513                          en = lp->inset_iterator_end();
2514                          it != en; ++it)
2515                 {
2516                         if ((*it)->id() == id_arg)
2517                                 return *it;
2518                         Inset * in = (*it)->getInsetFromID(id_arg);
2519                         if (in)
2520                                 return in;
2521                 }
2522                 lp = lp->next();
2523         }
2524         return 0;
2525 }
2526
2527
2528 string const InsetText::selectNextWordToSpellcheck(BufferView * bv, float & value) const
2529 {
2530         bool clear = false;
2531         string str;
2532
2533         if (!lt) {
2534                 lt = getLyXText(bv);
2535                 clear = true;
2536         }
2537         if (the_locking_inset) {
2538                 str = the_locking_inset->selectNextWordToSpellcheck(bv, value);
2539                 if (!str.empty()) {
2540                         value += cy(bv);
2541                         if (clear)
2542                                 lt = 0;
2543                         return str;
2544                 }
2545                 // we have to go on checking so move cusor to the next char
2546                 lt->cursor.pos(lt->cursor.pos() + 1);
2547         }
2548         str = lt->selectNextWordToSpellcheck(bv, value);
2549         if (str.empty())
2550                 bv->unlockInset(const_cast<InsetText *>(this));
2551         else
2552                 value = cy(bv);
2553         if (clear)
2554                 lt = 0;
2555         return str;
2556 }
2557
2558
2559 void InsetText::selectSelectedWord(BufferView * bv)
2560 {
2561         if (the_locking_inset) {
2562                 the_locking_inset->selectSelectedWord(bv);
2563                 return;
2564         }
2565         getLyXText(bv)->selectSelectedWord(bv);
2566         updateLocal(bv, SELECTION, false);
2567 }
2568
2569
2570 void InsetText::toggleSelection(BufferView * bv, bool kill_selection)
2571 {
2572         if (the_locking_inset) {
2573                 the_locking_inset->toggleSelection(bv, kill_selection);
2574         }
2575         bool clear = false;
2576         if (!lt) {
2577                 lt = getLyXText(bv);
2578                 clear = true;
2579         }
2580
2581         int x = top_x + TEXT_TO_INSET_OFFSET;
2582
2583         Row * row = lt->firstRow();
2584         int y_offset = top_baseline - row->ascent_of_text();
2585         int y = y_offset;
2586         while ((row != 0) && ((y+row->height()) <= 0)) {
2587                 y += row->height();
2588                 row = row->next();
2589         }
2590         if (y_offset < 0)
2591                 y_offset = y;
2592
2593         if (need_update & SELECTION)
2594                 need_update = NONE;
2595         bv->screen()->toggleSelection(lt, bv, kill_selection, y_offset, x);
2596         if (clear)
2597                 lt = 0;
2598 }
2599
2600
2601 bool InsetText::searchForward(BufferView * bv, string const & str,
2602                               bool cs, bool mw)
2603 {
2604         if (the_locking_inset) {
2605                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2606                         return true;
2607                 bool clear = false;
2608                 if (!lt) {
2609                         lt = getLyXText(bv);
2610                         clear = true;
2611                 }
2612                 Paragraph * lpar = lt->cursor.par();
2613                 pos_type pos = lt->cursor.pos();
2614                 if (pos < lpar->size() - 1)
2615                         ++pos;
2616                 else {
2617                         pos = 0;
2618                         lpar = lpar->next();
2619                 }
2620                 if (!lpar) {
2621                         if (clear)
2622                                 lt = 0;
2623                         // we have to unlock ourself in this function by default!
2624                         bv->unlockInset(const_cast<InsetText *>(this));
2625                         return false;
2626                 }
2627                 lt->setCursor(bv, lpar, pos);
2628                 if (clear)
2629                         lt = 0;
2630         }
2631         if (LyXFind(bv, str, true, true, cs , mw)) {
2632                 return true;
2633         }
2634         // we have to unlock ourself in this function by default!
2635         bv->unlockInset(const_cast<InsetText *>(this));
2636         return false;
2637 }
2638
2639 bool InsetText::searchBackward(BufferView * bv, string const & str,
2640                                bool cs, bool mw)
2641 {
2642         if (the_locking_inset)
2643                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2644                         return true;
2645         if (LyXFind(bv, str, false, true, cs, mw)) {
2646                 return true;
2647         }
2648         // we have to unlock ourself in this function by default!
2649         bv->unlockInset(const_cast<InsetText *>(this));
2650         return false;
2651 }
2652
2653
2654 bool InsetText::checkInsertChar(LyXFont & font)
2655 {
2656         if (owner())
2657                 return owner()->checkInsertChar(font);
2658         return true;
2659 }
2660
2661
2662 void InsetText::collapseParagraphs(BufferParams const & bparams) const
2663 {
2664         while(par->next()) {
2665                 if (par->size() && par->next()->size() &&
2666                         !par->isSeparator(par->size()-1))
2667                 {
2668                         par->insertChar(par->size(), ' ');
2669                 }
2670                 par->pasteParagraph(bparams);
2671         }
2672         reinitLyXText();
2673 }
2674
2675
2676 void InsetText::getDrawFont(LyXFont & font) const
2677 {
2678         if (!owner())
2679                 return;
2680         owner()->getDrawFont(font);
2681 }
2682
2683
2684 void InsetText::appendParagraphs(BufferParams const & bparams,
2685                                  Paragraph * newpar)
2686 {
2687         Paragraph * buf;
2688         Paragraph * tmpbuf = newpar;
2689         Paragraph * lastbuffer = buf = new Paragraph(*tmpbuf, false);
2690
2691         while (tmpbuf->next()) {
2692                 tmpbuf = tmpbuf->next();
2693                 lastbuffer->next(new Paragraph(*tmpbuf, false));
2694                 lastbuffer->next()->previous(lastbuffer);
2695                 lastbuffer = lastbuffer->next();
2696         }
2697         lastbuffer = par;
2698         while (lastbuffer->next())
2699                 lastbuffer = lastbuffer->next();
2700         if (newpar->size() && lastbuffer->size() &&
2701                 !lastbuffer->isSeparator(lastbuffer->size()-1))
2702         {
2703                 lastbuffer->insertChar(lastbuffer->size(), ' ');
2704         }
2705
2706         // make the buf exactly the same layout than our last paragraph
2707         buf->makeSameLayout(lastbuffer);
2708
2709         // paste it!
2710         lastbuffer->next(buf);
2711         buf->previous(lastbuffer);
2712         lastbuffer->pasteParagraph(bparams);
2713
2714         reinitLyXText();
2715 }