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