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