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