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