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