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