]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
The EnumLColor patch, free of macros.
[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 #include "insettext.h"
14 #include "insetnewline.h"
15
16 #include "buffer.h"
17 #include "bufferparams.h"
18 #include "BufferView.h"
19 #include "CutAndPaste.h"
20 #include "debug.h"
21 #include "errorlist.h"
22 #include "funcrequest.h"
23 #include "gettext.h"
24 #include "intl.h"
25 #include "lyxfind.h"
26 #include "lyxlex.h"
27 #include "lyxrc.h"
28 #include "metricsinfo.h"
29 #include "paragraph.h"
30 #include "paragraph_funcs.h"
31 #include "ParagraphParameters.h"
32 #include "rowpainter.h"
33 #include "sgml.h"
34 #include "texrow.h"
35 #include "undo_funcs.h"
36 #include "WordLangTuple.h"
37
38 #include "frontends/Alert.h"
39 #include "frontends/font_metrics.h"
40 #include "frontends/LyXView.h"
41 #include "frontends/Painter.h"
42
43 #include "support/lyxalgo.h" // lyx::count
44
45 #include <boost/bind.hpp>
46
47 using bv_funcs::replaceSelection;
48
49 using lyx::pos_type;
50
51 using lyx::graphics::PreviewLoader;
52
53 using lyx::support::isStrUnsignedInt;
54 using lyx::support::strToUnsignedInt;
55
56 using std::endl;
57 using std::for_each;
58 using std::max;
59
60 using std::auto_ptr;
61 using std::ostream;
62 using std::vector;
63
64
65 InsetText::InsetText(BufferParams const & bp)
66         : UpdatableInset(), text_(0, this, true, paragraphs)
67 {
68         paragraphs.push_back(Paragraph());
69         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
70         if (bp.tracking_changes)
71                 paragraphs.begin()->trackChanges();
72         init(0);
73 }
74
75
76 InsetText::InsetText(InsetText const & in)
77         : UpdatableInset(in), text_(0, this, true, paragraphs)
78 {
79         init(&in);
80 }
81
82
83 InsetText & InsetText::operator=(InsetText const & it)
84 {
85         init(&it);
86         return *this;
87 }
88
89
90 void InsetText::init(InsetText const * ins)
91 {
92         if (ins) {
93                 textwidth_ = ins->textwidth_;
94                 text_.bv_owner = ins->text_.bv_owner;
95
96                 paragraphs = ins->paragraphs;
97
98                 ParagraphList::iterator pit = paragraphs.begin();
99                 ParagraphList::iterator end = paragraphs.end();
100                 for (; pit != end; ++pit)
101                         pit->setInsetOwner(this);
102
103                 autoBreakRows = ins->autoBreakRows;
104                 drawFrame_ = ins->drawFrame_;
105                 frame_color = ins->frame_color;
106         } else {
107                 textwidth_ = 0; // broken
108                 drawFrame_ = NEVER;
109                 frame_color = LColor::insetframe;
110                 autoBreakRows = false;
111         }
112         the_locking_inset = 0;
113         for_each(paragraphs.begin(), paragraphs.end(),
114                  boost::bind(&Paragraph::setInsetOwner, _1, this));
115         top_y = 0;
116         no_selection = true;
117         locked = false;
118         old_par = paragraphs.end();
119         in_insetAllowed = false;
120 }
121
122
123 void InsetText::clear(bool just_mark_erased)
124 {
125         if (just_mark_erased) {
126                 ParagraphList::iterator it = paragraphs.begin();
127                 ParagraphList::iterator end = paragraphs.end();
128                 for (; it != end; ++it)
129                         it->markErased();
130                 return;
131         }
132
133         // This is a gross hack...
134         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
135
136         paragraphs.clear();
137         paragraphs.push_back(Paragraph());
138         paragraphs.begin()->setInsetOwner(this);
139         paragraphs.begin()->layout(old_layout);
140 }
141
142
143 auto_ptr<InsetBase> InsetText::clone() const
144 {
145         return auto_ptr<InsetBase>(new InsetText(*this));
146 }
147
148
149 void InsetText::write(Buffer const & buf, ostream & os) const
150 {
151         os << "Text\n";
152         writeParagraphData(buf, os);
153 }
154
155
156 void InsetText::writeParagraphData(Buffer const & buf, ostream & os) const
157 {
158         ParagraphList::const_iterator it = paragraphs.begin();
159         ParagraphList::const_iterator end = paragraphs.end();
160         Paragraph::depth_type dth = 0;
161         for (; it != end; ++it) {
162                 it->write(buf, os, buf.params(), dth);
163         }
164 }
165
166
167 void InsetText::read(Buffer const & buf, LyXLex & lex)
168 {
169         string token;
170         Paragraph::depth_type depth = 0;
171
172         clear(false);
173
174         if (buf.params().tracking_changes)
175                 paragraphs.begin()->trackChanges();
176
177         // delete the initial paragraph
178         paragraphs.clear();
179         ParagraphList::iterator pit = paragraphs.begin();
180
181         while (lex.isOK()) {
182                 lex.nextToken();
183                 token = lex.getString();
184                 if (token.empty())
185                         continue;
186                 if (token == "\\end_inset") {
187                         break;
188                 }
189
190                 if (token == "\\end_document") {
191                         lex.printError("\\end_document read in inset! Error in document!");
192                         return;
193                 }
194
195                 // FIXME: ugly.
196                 const_cast<Buffer&>(buf).readParagraph(lex, token, paragraphs, pit, depth);
197         }
198
199         pit = paragraphs.begin();
200         ParagraphList::iterator const end = paragraphs.end();
201         for (; pit != end; ++pit)
202                 pit->setInsetOwner(this);
203
204         if (token != "\\end_inset") {
205                 lex.printError("Missing \\end_inset at this point. "
206                                            "Read: `$$Token'");
207         }
208 }
209
210
211 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
212 {
213         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
214
215         textwidth_ = mi.base.textwidth;
216         BufferView * bv = mi.base.bv;
217         setViewCache(bv);
218         text_.metrics(mi, dim);
219         dim.asc += TEXT_TO_INSET_OFFSET;
220         dim.des += TEXT_TO_INSET_OFFSET;
221         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
222         dim.wid = max(dim.wid, 10);
223         dim_ = dim;
224 }
225
226
227 int InsetText::textWidth() const
228 {
229         return textwidth_;
230 }
231
232
233 void InsetText::draw(PainterInfo & pi, int x, int y) const
234 {
235         // update our idea of where we are. Clearly, we should
236         // not have to know this information.
237         top_x = x;
238
239         int const start_x = x;
240
241         BufferView * bv = pi.base.bv;
242         Painter & pain = pi.pain;
243
244         // repaint the background if needed
245         if (backgroundColor() != LColor::background)
246                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, y);
247
248         // no draw is necessary !!!
249         if (drawFrame_ == LOCKED && !locked && paragraphs.begin()->empty()) {
250                 top_baseline = y;
251                 return;
252         }
253
254         bv->hideCursor();
255
256         if (!owner())
257                 x += scroll();
258
259         top_baseline = y;
260         top_y = y - dim_.asc;
261
262         if (the_locking_inset && cpar() == inset_par && cpos() == inset_pos) {
263                 inset_x = cx() - x;
264                 inset_y = cy();
265         }
266
267         x += TEXT_TO_INSET_OFFSET;
268
269         paintTextInset(*bv, text_, x, y);
270
271         if (drawFrame_ == ALWAYS || (drawFrame_ == LOCKED && locked))
272                 drawFrame(pain, start_x);
273 }
274
275
276 void InsetText::drawFrame(Painter & pain, int x) const
277 {
278         int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
279         int const frame_x = x + ttoD2;
280         int const frame_y = top_baseline - dim_.asc + ttoD2;
281         int const frame_w = dim_.wid - TEXT_TO_INSET_OFFSET;
282         int const frame_h = dim_.asc + dim_.des - TEXT_TO_INSET_OFFSET;
283         pain.rectangle(frame_x, frame_y, frame_w, frame_h, frame_color);
284 }
285
286
287 void InsetText::updateLocal(BufferView * bv, bool /*mark_dirty*/)
288 {
289         if (!bv)
290                 return;
291
292         if (!autoBreakRows && paragraphs.size() > 1)
293                 collapseParagraphs(bv);
294
295         if (!text_.selection.set())
296                 text_.selection.cursor = text_.cursor;
297
298         bv->fitCursor();
299         bv->updateInset(this);
300         bv->owner()->view_state_changed();
301         bv->owner()->updateMenubar();
302         bv->owner()->updateToolbar();
303         if (old_par != cpar()) {
304                 bv->owner()->setLayout(cpar()->layout()->name());
305                 old_par = cpar();
306         }
307 }
308
309
310 string const InsetText::editMessage() const
311 {
312         return _("Opened Text Inset");
313 }
314
315
316 void InsetText::insetUnlock(BufferView * bv)
317 {
318         if (the_locking_inset) {
319                 the_locking_inset->insetUnlock(bv);
320                 the_locking_inset = 0;
321                 updateLocal(bv, false);
322         }
323         no_selection = true;
324         locked = false;
325
326         if (text_.selection.set()) {
327                 text_.clearSelection();
328         } else if (owner()) {
329                 bv->owner()->setLayout(owner()->getLyXText(bv)
330                                        ->cursor.par()->layout()->name());
331         } else
332                 bv->owner()->setLayout(bv->text->cursor.par()->layout()->name());
333         // hack for deleteEmptyParMech
334         ParagraphList::iterator first_par = paragraphs.begin();
335         if (!first_par->empty()) {
336                 text_.setCursor(first_par, 0);
337         } else if (paragraphs.size() > 1) {
338                 text_.setCursor(boost::next(first_par), 0);
339         }
340 }
341
342
343 void InsetText::lockInset(BufferView * bv)
344 {
345         locked = true;
346         the_locking_inset = 0;
347         inset_pos = inset_x = inset_y = 0;
348         inset_boundary = false;
349         inset_par = paragraphs.end();
350         old_par = paragraphs.end();
351         text_.setCursorIntern(paragraphs.begin(), 0);
352         text_.clearSelection();
353         finishUndo();
354         // If the inset is empty set the language of the current font to the
355         // language to the surronding text (if different).
356         if (paragraphs.begin()->empty() && paragraphs.size() == 1 &&
357                 bv->getParentLanguage(this) != text_.current_font.language()) {
358                 LyXFont font(LyXFont::ALL_IGNORE);
359                 font.setLanguage(bv->getParentLanguage(this));
360                 setFont(bv, font, false);
361         }
362 }
363
364
365 void InsetText::lockInset(BufferView * /*bv*/, UpdatableInset * inset)
366 {
367         the_locking_inset = inset;
368         inset_x = cx() - top_x;
369         inset_y = cy();
370         inset_pos = cpos();
371         inset_par = cpar();
372         inset_boundary = cboundary();
373 }
374
375
376 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
377 {
378         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
379                               << inset << "): " << endl;
380         if (!inset)
381                 return false;
382         if (!the_locking_inset) {
383                 ParagraphList::iterator pit = paragraphs.begin();
384                 ParagraphList::iterator pend = paragraphs.end();
385
386                 for (; pit != pend; ++pit) {
387                         InsetList::iterator it = pit->insetlist.begin();
388                         InsetList::iterator const end = pit->insetlist.end();
389                         for (; it != end; ++it) {
390                                 if (it->inset == inset) {
391                                         lyxerr << "InsetText::lockInsetInInset: 1 a" << endl;
392                                         text_.setCursorIntern(pit, it->pos);
393                                         lyxerr << "InsetText::lockInsetInInset: 1 b" << endl;
394                                         lyxerr << "bv: " << bv << " inset: " << inset << endl;
395                                         lockInset(bv, inset);
396                                         lyxerr << "InsetText::lockInsetInInset: 1 c" << endl;
397                                         return true;
398                                 }
399                         }
400                 }
401                 lyxerr << "InsetText::lockInsetInInset: 3" << endl;
402                 return false;
403         }
404         if (inset == cpar()->getInset(cpos())) {
405                 lyxerr[Debug::INSETS] << "OK" << endl;
406                 lockInset(bv, inset);
407                 return true;
408         }
409
410         if (the_locking_inset && the_locking_inset == inset) {
411                 if (cpar() == inset_par && cpos() == inset_pos) {
412                         lyxerr[Debug::INSETS] << "OK" << endl;
413                         inset_x = cx() - top_x;
414                         inset_y = cy();
415                 } else {
416                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
417                 }
418         } else if (the_locking_inset) {
419                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
420                 return the_locking_inset->lockInsetInInset(bv, inset);
421         }
422         lyxerr[Debug::INSETS] << "NOT OK" << endl;
423         return false;
424 }
425
426
427 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
428                                    bool lr)
429 {
430         if (!the_locking_inset)
431                 return false;
432         if (the_locking_inset == inset) {
433                 the_locking_inset->insetUnlock(bv);
434                 the_locking_inset = 0;
435                 if (lr)
436                         moveRightIntern(bv, true, false);
437                 old_par = paragraphs.end(); // force layout setting
438                 if (scroll())
439                         scroll(bv, 0.0F);
440                 else
441                         updateLocal(bv, false);
442                 return true;
443         }
444         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
445 }
446
447
448 void InsetText::lfunMousePress(FuncRequest const & cmd)
449 {
450         no_selection = true;
451
452         // use this to check mouse motion for selection!
453         mouse_x = cmd.x;
454         mouse_y = cmd.y;
455
456         BufferView * bv = cmd.view();
457         FuncRequest cmd1 = cmd;
458         cmd1.x -= inset_x;
459         cmd1.y -= inset_y;
460         if (!locked)
461                 lockInset(bv);
462
463         int tmp_x = cmd.x;
464         int tmp_y = cmd.y + dim_.asc - bv->top_y();
465         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
466
467         if (the_locking_inset) {
468                 if (the_locking_inset == inset) {
469                         the_locking_inset->localDispatch(cmd1);
470                         return;
471                 }
472                 // otherwise only unlock the_locking_inset
473                 the_locking_inset->insetUnlock(bv);
474                 the_locking_inset = 0;
475         }
476         if (!inset)
477                 no_selection = false;
478
479         if (bv->theLockingInset()) {
480                 if (isHighlyEditableInset(inset)) {
481                         // We just have to lock the inset before calling a
482                         // PressEvent on it!
483                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
484                         if (!bv->lockInset(uinset)) {
485                                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
486                         }
487                         inset->localDispatch(cmd1);
488                         if (the_locking_inset)
489                                 updateLocal(bv, false);
490                         return;
491                 }
492         }
493         if (!inset) {
494                 bool paste_internally = false;
495                 if (cmd.button() == mouse_button::button2 && getLyXText(bv)->selection.set()) {
496                         localDispatch(FuncRequest(bv, LFUN_COPY));
497                         paste_internally = true;
498                 }
499                 int old_top_y = bv->top_y();
500
501                 text_.setCursorFromCoordinates(cmd.x, cmd.y + dim_.asc);
502                 // set the selection cursor!
503                 text_.selection.cursor = text_.cursor;
504                 text_.cursor.x_fix(text_.cursor.x());
505
506                 text_.clearSelection();
507                 updateLocal(bv, false);
508
509                 bv->owner()->setLayout(cpar()->layout()->name());
510
511                 // we moved the view we cannot do mouse selection in this case!
512                 if (bv->top_y() != old_top_y)
513                         no_selection = true;
514                 old_par = cpar();
515                 // Insert primary selection with middle mouse
516                 // if there is a local selection in the current buffer,
517                 // insert this
518                 if (cmd.button() == mouse_button::button2) {
519                         if (paste_internally)
520                                 localDispatch(FuncRequest(bv, LFUN_PASTE));
521                         else
522                                 localDispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
523                 }
524         } else {
525                 getLyXText(bv)->clearSelection();
526         }
527 }
528
529
530 bool InsetText::lfunMouseRelease(FuncRequest const & cmd)
531 {
532         BufferView * bv = cmd.view();
533         FuncRequest cmd1 = cmd;
534         cmd1.x -= inset_x;
535         cmd1.y -= inset_y;
536
537         no_selection = true;
538         if (the_locking_inset)
539                 return the_locking_inset->localDispatch(cmd1);
540
541         int tmp_x = cmd.x;
542         int tmp_y = cmd.y + dim_.asc - bv->top_y();
543         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
544         bool ret = false;
545         if (inset) {
546 // This code should probably be removed now. Simple insets
547 // (!highlyEditable) can actually take the localDispatch,
548 // and turn it into edit() if necessary. But we still
549 // need to deal properly with the whole relative vs.
550 // absolute mouse co-ords thing in a realiable, sensible way
551 #if 0
552                 if (isHighlyEditableInset(inset))
553                         ret = inset->localDispatch(cmd1);
554                 else {
555                         inset_x = cx(bv) - top_x;
556                         inset_y = cy();
557                         cmd1.x = cmd.x - inset_x;
558                         cmd1.y = cmd.x - inset_y;
559                         inset->edit(bv, cmd1.x, cmd1.y, cmd.button());
560                         ret = true;
561                 }
562 #endif
563                 ret = inset->localDispatch(cmd1);
564                 updateLocal(bv, false);
565
566         }
567         return ret;
568 }
569
570
571 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
572 {
573         FuncRequest cmd1 = cmd;
574         cmd1.x -= inset_x;
575         cmd1.y -= inset_y;
576
577         if (the_locking_inset) {
578                 the_locking_inset->localDispatch(cmd1);
579                 return;
580         }
581
582         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
583                 return;
584
585         BufferView * bv = cmd.view();
586         LyXCursor cur = text_.cursor;
587         text_.setCursorFromCoordinates (cmd.x, cmd.y + dim_.asc);
588         text_.cursor.x_fix(text_.cursor.x());
589         if (cur == text_.cursor)
590                 return;
591         text_.setSelection();
592         updateLocal(bv, false);
593 }
594
595
596 InsetOld::RESULT InsetText::localDispatch(FuncRequest const & cmd)
597 {
598         BufferView * bv = cmd.view();
599         setViewCache(bv);
600
601         switch (cmd.action) {
602         case LFUN_INSET_EDIT: {
603                 UpdatableInset::localDispatch(cmd);
604
605                 if (!bv->lockInset(this)) {
606                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
607                         return DISPATCHED;
608                 }
609
610                 locked = true;
611                 the_locking_inset = 0;
612                 inset_pos = 0;
613                 inset_x = 0;
614                 inset_y = 0;
615                 inset_boundary = false;
616                 inset_par = paragraphs.end();
617                 old_par = paragraphs.end();
618
619
620                 if (cmd.argument.size()) {
621                         if (cmd.argument == "left")
622                                 text_.setCursorIntern(paragraphs.begin(), 0);
623                         else {
624                                 ParagraphList::iterator it = boost::prior(paragraphs.end());
625                                 text_.setCursor(it, it->size());
626                         }
627                 } else {
628                         int tmp_y = (cmd.y < 0) ? 0 : cmd.y;
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, cmd.x, tmp_y, mouse_button::none)) {
634                                 text_.setCursorFromCoordinates(cmd.x, cmd.y + dim_.asc);
635                                 text_.cursor.x(text_.cursor.x());
636                                 text_.cursor.x_fix(text_.cursor.x());
637                         }
638                 }
639
640                 text_.clearSelection();
641                 finishUndo();
642
643                 // If the inset is empty set the language of the current font to the
644                 // language to the surronding text (if different).
645                 if (paragraphs.begin()->empty() &&
646                     paragraphs.size() == 1 &&
647                     bv->getParentLanguage(this) != text_.current_font.language())
648                 {
649                         LyXFont font(LyXFont::ALL_IGNORE);
650                         font.setLanguage(bv->getParentLanguage(this));
651                         setFont(bv, font, false);
652                 }
653
654                 updateLocal(bv, false);
655                 // Tell the paragraph dialog that we've entered an insettext.
656                 bv->dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
657                 return DISPATCHED;
658         }
659
660         case LFUN_MOUSE_PRESS:
661                 lfunMousePress(cmd);
662                 return DISPATCHED;
663
664         case LFUN_MOUSE_MOTION:
665                 lfunMouseMotion(cmd);
666                 return DISPATCHED;
667
668         case LFUN_MOUSE_RELEASE:
669                 return lfunMouseRelease(cmd) ? DISPATCHED : UNDISPATCHED;
670
671         default:
672                 break;
673         }
674
675         bool was_empty = paragraphs.begin()->empty() && paragraphs.size() == 1;
676         no_selection = false;
677
678         RESULT result = UpdatableInset::localDispatch(cmd);
679         if (result != UNDISPATCHED)
680                 return DISPATCHED;
681
682         result = DISPATCHED;
683         if (cmd.action < 0 && cmd.argument.empty())
684                 return FINISHED;
685
686         if (the_locking_inset) {
687                 result = the_locking_inset->localDispatch(cmd);
688                 if (result == DISPATCHED_NOUPDATE)
689                         return result;
690                 if (result == DISPATCHED) {
691                         updateLocal(bv, false);
692                         return result;
693                 }
694                 if (result >= FINISHED) {
695                         switch (result) {
696                         case FINISHED_RIGHT:
697                                 moveRightIntern(bv, false, false);
698                                 result = DISPATCHED;
699                                 break;
700                         case FINISHED_UP:
701                                 result = moveUp(bv);
702                                 if (result >= FINISHED) {
703                                         updateLocal(bv, false);
704                                         bv->unlockInset(this);
705                                 }
706                                 break;
707                         case FINISHED_DOWN:
708                                 result = moveDown(bv);
709                                 if (result >= FINISHED) {
710                                         updateLocal(bv, false);
711                                         bv->unlockInset(this);
712                                 }
713                                 break;
714                         default:
715                                 result = DISPATCHED;
716                                 break;
717                         }
718                         the_locking_inset = 0;
719                         updateLocal(bv, false);
720                         // make sure status gets reset immediately
721                         bv->owner()->clearMessage();
722                         return result;
723                 }
724         }
725         bool updflag = false;
726
727         switch (cmd.action) {
728
729         // Normal chars
730         case LFUN_SELFINSERT:
731                 if (bv->buffer()->isReadonly()) {
732 //          setErrorMessage(N_("Document is read only"));
733                         break;
734                 }
735                 if (!cmd.argument.empty()) {
736                         /* Automatically delete the currently selected
737                          * text and replace it with what is being
738                          * typed in now. Depends on lyxrc settings
739                          * "auto_region_delete", which defaults to
740                          * true (on). */
741 #if 0
742                         // This should not be needed here and is also WRONG!
743                         recordUndo(bv, Undo::INSERT, text_.cursor.par());
744 #endif
745                         bv->switchKeyMap();
746
747                         if (lyxrc.auto_region_delete && text_.selection.set())
748                                 text_.cutSelection(false, false);
749                         text_.clearSelection();
750
751                         for (string::size_type i = 0; i < cmd.argument.length(); ++i)
752                                 bv->owner()->getIntl().getTransManager().
753                                         TranslateAndInsert(cmd.argument[i], &text_);
754                 }
755                 text_.selection.cursor = text_.cursor;
756                 updflag = true;
757                 result = DISPATCHED_NOUPDATE;
758                 break;
759
760         // cursor movements that need special handling
761
762         case LFUN_RIGHT:
763                 result = moveRight(bv);
764                 finishUndo();
765                 break;
766         case LFUN_LEFT:
767                 finishUndo();
768                 result = moveLeft(bv);
769                 break;
770         case LFUN_DOWN:
771                 finishUndo();
772                 result = moveDown(bv);
773                 break;
774         case LFUN_UP:
775                 finishUndo();
776                 result = moveUp(bv);
777                 break;
778
779         case LFUN_PRIOR:
780                 if (crow() == text_.firstRow())
781                         result = FINISHED_UP;
782                 else {
783                         text_.cursorPrevious();
784                         text_.clearSelection();
785                         result = DISPATCHED_NOUPDATE;
786                 }
787                 break;
788
789         case LFUN_NEXT:
790                 if (crow() == text_.lastRow())
791                         result = FINISHED_DOWN;
792                 else {
793                         text_.cursorNext();
794                         text_.clearSelection();
795                         result = DISPATCHED_NOUPDATE;
796                 }
797                 break;
798
799         case LFUN_BACKSPACE:
800                 if (text_.selection.set())
801                         text_.cutSelection(true, false);
802                 else
803                         text_.backspace();
804                 updflag = true;
805                 break;
806
807         case LFUN_DELETE:
808                 if (text_.selection.set())
809                         text_.cutSelection(true, false);
810                 else
811                         text_.Delete();
812                 updflag = true;
813                 break;
814
815         case LFUN_PASTE: {
816                 if (!autoBreakRows) {
817                         if (CutAndPaste::nrOfParagraphs() > 1) {
818 #ifdef WITH_WARNINGS
819 #warning FIXME horrendously bad UI
820 #endif
821                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
822                                 break;
823                         }
824                 }
825
826                 replaceSelection(bv->getLyXText());
827                 size_t sel_index = 0;
828                 string const & arg = cmd.argument;
829                 if (isStrUnsignedInt(arg)) {
830                         size_t const paste_arg = strToUnsignedInt(arg);
831 #warning FIXME Check if the arg is in the domain of available selections.
832                         sel_index = paste_arg;
833                 }
834                 text_.pasteSelection(sel_index);
835                 // bug 393
836                 text_.clearSelection();
837                 updflag = true;
838                 break;
839         }
840
841         case LFUN_BREAKPARAGRAPH:
842                 if (!autoBreakRows) {
843                         result = DISPATCHED;
844                         break;
845                 }
846                 replaceSelection(bv->getLyXText());
847                 text_.breakParagraph(paragraphs, 0);
848                 updflag = true;
849                 break;
850
851         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
852                 if (!autoBreakRows) {
853                         result = DISPATCHED;
854                         break;
855                 }
856                 replaceSelection(bv->getLyXText());
857                 text_.breakParagraph(paragraphs, 1);
858                 updflag = true;
859                 break;
860
861         case LFUN_BREAKLINE: {
862                 if (!autoBreakRows) {
863                         result = DISPATCHED;
864                         break;
865                 }
866
867                 replaceSelection(bv->getLyXText());
868                 text_.insertInset(new InsetNewline);
869                 updflag = true;
870                 break;
871         }
872
873         case LFUN_LAYOUT:
874                 // do not set layouts on non breakable textinsets
875                 if (autoBreakRows) {
876                         string cur_layout = cpar()->layout()->name();
877
878                         // Derive layout number from given argument (string)
879                         // and current buffer's textclass (number).
880                         LyXTextClass const & tclass =
881                                 bv->buffer()->params().getLyXTextClass();
882                         string layout = cmd.argument;
883                         bool hasLayout = tclass.hasLayout(layout);
884
885                         // If the entry is obsolete, use the new one instead.
886                         if (hasLayout) {
887                                 string const & obs = tclass[layout]->obsoleted_by();
888                                 if (!obs.empty())
889                                         layout = obs;
890                         }
891
892                         // see if we found the layout number:
893                         if (!hasLayout) {
894                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
895                                 bv->owner()->dispatch(lf);
896                                 break;
897                         }
898
899                         if (cur_layout != layout) {
900                                 cur_layout = layout;
901                                 text_.setLayout(layout);
902                                 bv->owner()->setLayout(cpar()->layout()->name());
903                                 updflag = true;
904                         }
905                 } else {
906                         // reset the layout box
907                         bv->owner()->setLayout(cpar()->layout()->name());
908                 }
909                 break;
910
911         default:
912                 if (!bv->dispatch(cmd))
913                         result = UNDISPATCHED;
914                 break;
915         }
916
917         updateLocal(bv, updflag);
918
919         /// If the action has deleted all text in the inset, we need to change the
920         // language to the language of the surronding text.
921         if (!was_empty && paragraphs.begin()->empty() &&
922             paragraphs.size() == 1) {
923                 LyXFont font(LyXFont::ALL_IGNORE);
924                 font.setLanguage(bv->getParentLanguage(this));
925                 setFont(bv, font, false);
926         }
927
928         if (result >= FINISHED)
929                 bv->unlockInset(this);
930
931         if (result == DISPATCHED_NOUPDATE)
932                 result = DISPATCHED;
933         return result;
934 }
935
936
937 int InsetText::latex(Buffer const & buf, ostream & os,
938                      LatexRunParams const & runparams) const
939 {
940         TexRow texrow;
941         latexParagraphs(buf, paragraphs, os, texrow, runparams);
942         return texrow.rows();
943 }
944
945
946 int InsetText::ascii(Buffer const & buf, ostream & os, int linelen) const
947 {
948         unsigned int lines = 0;
949
950         ParagraphList::const_iterator beg = paragraphs.begin();
951         ParagraphList::const_iterator end = paragraphs.end();
952         ParagraphList::const_iterator it = beg;
953         for (; it != end; ++it) {
954                 string const tmp = buf.asciiParagraph(*it, linelen, it == beg);
955                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
956                 os << tmp;
957         }
958         return lines;
959 }
960
961
962 int InsetText::linuxdoc(Buffer const & buf, ostream & os) const
963 {
964         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
965         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
966
967         // There is a confusion between the empty paragraph and the default paragraph
968         // The default paragraph is <p></p>, the empty paragraph is *empty*
969         // Since none of the floats of linuxdoc accepts standard paragraphs
970         // I disable them. I don't expect problems. (jamatos 2003/07/27)
971         for (; pit != pend; ++pit) {
972                 const string name = pit->layout()->latexname();
973                 if (name != "p")
974                         sgml::openTag(os, 1, 0, name);
975                 buf.simpleLinuxDocOnePar(os, pit, 0);
976                 if (name != "p")
977                         sgml::closeTag(os, 1, 0, name);
978         }
979         return 0;
980 }
981
982
983 int InsetText::docbook(Buffer const & buf, ostream & os, bool mixcont) const
984 {
985         unsigned int lines = 0;
986
987         vector<string> environment_stack(10);
988         vector<string> environment_inner(10);
989
990         int const command_depth = 0;
991         string item_name;
992
993         Paragraph::depth_type depth = 0; // paragraph depth
994
995         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
996         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
997
998         for (; pit != pend; ++pit) {
999                 int desc_on = 0; // description mode
1000
1001                 LyXLayout_ptr const & style = pit->layout();
1002
1003                 // environment tag closing
1004                 for (; depth > pit->params().depth(); --depth) {
1005                         if (environment_inner[depth] != "!-- --") {
1006                                 item_name = "listitem";
1007                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1008                                 if (environment_inner[depth] == "varlistentry")
1009                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1010                         }
1011                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1012                         environment_stack[depth].erase();
1013                         environment_inner[depth].erase();
1014                 }
1015
1016                 if (depth == pit->params().depth()
1017                    && environment_stack[depth] != style->latexname()
1018                    && !environment_stack[depth].empty()) {
1019                         if (environment_inner[depth] != "!-- --") {
1020                                 item_name= "listitem";
1021                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1022                                 if (environment_inner[depth] == "varlistentry")
1023                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1024                         }
1025
1026                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1027
1028                         environment_stack[depth].erase();
1029                         environment_inner[depth].erase();
1030                 }
1031
1032                 // Write opening SGML tags.
1033                 switch (style->latextype) {
1034                 case LATEX_PARAGRAPH:
1035                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1036                         break;
1037
1038                 case LATEX_COMMAND:
1039                         buf.error(ErrorItem(_("Error"), _("LatexType Command not allowed here.\n"), pit->id(), 0, pit->size()));
1040                         return -1;
1041                         break;
1042
1043                 case LATEX_ENVIRONMENT:
1044                 case LATEX_ITEM_ENVIRONMENT:
1045                         if (depth < pit->params().depth()) {
1046                                 depth = pit->params().depth();
1047                                 environment_stack[depth].erase();
1048                         }
1049
1050                         if (environment_stack[depth] != style->latexname()) {
1051                                 if (environment_stack.size() == depth + 1) {
1052                                         environment_stack.push_back("!-- --");
1053                                         environment_inner.push_back("!-- --");
1054                                 }
1055                                 environment_stack[depth] = style->latexname();
1056                                 environment_inner[depth] = "!-- --";
1057                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1058                         } else {
1059                                 if (environment_inner[depth] != "!-- --") {
1060                                         item_name= "listitem";
1061                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1062                                         if (environment_inner[depth] == "varlistentry")
1063                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1064                                 }
1065                         }
1066
1067                         if (style->latextype == LATEX_ENVIRONMENT) {
1068                                 if (!style->latexparam().empty()) {
1069                                         if (style->latexparam() == "CDATA")
1070                                                 os << "<![CDATA[";
1071                                         else
1072                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1073                                 }
1074                                 break;
1075                         }
1076
1077                         desc_on = (style->labeltype == LABEL_MANUAL);
1078
1079                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1080                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1081
1082                         item_name = desc_on ? "term" : "para";
1083                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1084
1085                         break;
1086                 default:
1087                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1088                         break;
1089                 }
1090
1091                 buf.simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1092
1093                 string end_tag;
1094                 // write closing SGML tags
1095                 switch (style->latextype) {
1096                 case LATEX_ENVIRONMENT:
1097                         if (!style->latexparam().empty()) {
1098                                 if (style->latexparam() == "CDATA")
1099                                         os << "]]>";
1100                                 else
1101                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1102                         }
1103                         break;
1104                 case LATEX_ITEM_ENVIRONMENT:
1105                         if (desc_on == 1)
1106                                 break;
1107                         end_tag= "para";
1108                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1109                         break;
1110                 case LATEX_PARAGRAPH:
1111                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1112                         break;
1113                 default:
1114                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1115                         break;
1116                 }
1117         }
1118
1119         // Close open tags
1120         for (int d = depth; d >= 0; --d) {
1121                 if (!environment_stack[depth].empty()) {
1122                         if (environment_inner[depth] != "!-- --") {
1123                                 item_name = "listitem";
1124                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1125                                if (environment_inner[depth] == "varlistentry")
1126                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1127                         }
1128
1129                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1130                 }
1131         }
1132
1133         return lines;
1134 }
1135
1136
1137 void InsetText::validate(LaTeXFeatures & features) const
1138 {
1139         for_each(paragraphs.begin(), paragraphs.end(),
1140                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1141 }
1142
1143
1144 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1145 {
1146         if (the_locking_inset) {
1147                 the_locking_inset->getCursor(bv, x, y);
1148                 return;
1149         }
1150         x = cx();
1151         y = cy() + InsetText::y();
1152 }
1153
1154
1155 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1156 {
1157         if (the_locking_inset) {
1158                 the_locking_inset->getCursorPos(bv, x, y);
1159                 return;
1160         }
1161         x = cx() - top_x - TEXT_TO_INSET_OFFSET;
1162         y = cy() - TEXT_TO_INSET_OFFSET;
1163 }
1164
1165
1166 int InsetText::insetInInsetY() const
1167 {
1168         if (!the_locking_inset)
1169                 return 0;
1170
1171         return inset_y + the_locking_inset->insetInInsetY();
1172 }
1173
1174
1175 void InsetText::fitInsetCursor(BufferView * bv) const
1176 {
1177         if (the_locking_inset) {
1178                 the_locking_inset->fitInsetCursor(bv);
1179                 return;
1180         }
1181
1182         LyXFont const font = text_.getFont(cpar(), cpos());
1183
1184         int const asc = font_metrics::maxAscent(font);
1185         int const desc = font_metrics::maxDescent(font);
1186
1187         bv->fitLockedInsetCursor(cx(), cy(), asc, desc);
1188 }
1189
1190
1191 InsetOld::RESULT InsetText::moveRight(BufferView * bv)
1192 {
1193         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params()))
1194                 return moveLeftIntern(bv, false, true, false);
1195         else
1196                 return moveRightIntern(bv, true, true, false);
1197 }
1198
1199
1200 InsetOld::RESULT InsetText::moveLeft(BufferView * bv)
1201 {
1202         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params()))
1203                 return moveRightIntern(bv, true, true, false);
1204         else
1205                 return moveLeftIntern(bv, false, true, false);
1206 }
1207
1208
1209 InsetOld::RESULT
1210 InsetText::moveRightIntern(BufferView * bv, bool front,
1211                            bool activate_inset, bool selecting)
1212 {
1213         ParagraphList::iterator c_par = cpar();
1214
1215         if (boost::next(c_par) == paragraphs.end() && cpos() >= c_par->size())
1216                 return FINISHED_RIGHT;
1217         if (activate_inset && checkAndActivateInset(bv, front))
1218                 return DISPATCHED;
1219         text_.cursorRight(bv);
1220         if (!selecting)
1221                 text_.clearSelection();
1222         return DISPATCHED_NOUPDATE;
1223 }
1224
1225
1226 InsetOld::RESULT
1227 InsetText::moveLeftIntern(BufferView * bv, bool front,
1228                           bool activate_inset, bool selecting)
1229 {
1230         if (cpar() == paragraphs.begin() && cpos() <= 0)
1231                 return FINISHED;
1232         text_.cursorLeft(bv);
1233         if (!selecting)
1234                 text_.clearSelection();
1235         if (activate_inset && checkAndActivateInset(bv, front))
1236                 return DISPATCHED;
1237         return DISPATCHED_NOUPDATE;
1238 }
1239
1240
1241 InsetOld::RESULT InsetText::moveUp(BufferView * bv)
1242 {
1243         if (crow() == text_.firstRow())
1244                 return FINISHED_UP;
1245         text_.cursorUp(bv);
1246         text_.clearSelection();
1247         return DISPATCHED_NOUPDATE;
1248 }
1249
1250
1251 InsetOld::RESULT InsetText::moveDown(BufferView * bv)
1252 {
1253         if (crow() == text_.lastRow())
1254                 return FINISHED_DOWN;
1255         text_.cursorDown(bv);
1256         text_.clearSelection();
1257         return DISPATCHED_NOUPDATE;
1258 }
1259
1260
1261 bool InsetText::insertInset(BufferView * bv, InsetOld * inset)
1262 {
1263         if (the_locking_inset) {
1264                 if (the_locking_inset->insetAllowed(inset))
1265                         return the_locking_inset->insertInset(bv, inset);
1266                 return false;
1267         }
1268         inset->setOwner(this);
1269         text_.insertInset(inset);
1270         bv->fitCursor();
1271         updateLocal(bv, true);
1272         return true;
1273 }
1274
1275
1276 bool InsetText::insetAllowed(InsetOld::Code code) const
1277 {
1278         // in_insetAllowed is a really gross hack,
1279         // to allow us to call the owner's insetAllowed
1280         // without stack overflow, which can happen
1281         // when the owner uses InsetCollapsable::insetAllowed()
1282         bool ret = true;
1283         if (in_insetAllowed)
1284                 return ret;
1285         in_insetAllowed = true;
1286         if (the_locking_inset)
1287                 ret = the_locking_inset->insetAllowed(code);
1288         else if (owner())
1289                 ret = owner()->insetAllowed(code);
1290         in_insetAllowed = false;
1291         return ret;
1292 }
1293
1294
1295 UpdatableInset * InsetText::getLockingInset() const
1296 {
1297         return the_locking_inset ? the_locking_inset->getLockingInset() :
1298                 const_cast<InsetText *>(this);
1299 }
1300
1301
1302 UpdatableInset * InsetText::getFirstLockingInsetOfType(InsetOld::Code c)
1303 {
1304         if (c == lyxCode())
1305                 return this;
1306         if (the_locking_inset)
1307                 return the_locking_inset->getFirstLockingInsetOfType(c);
1308         return 0;
1309 }
1310
1311
1312 bool InsetText::showInsetDialog(BufferView * bv) const
1313 {
1314         if (the_locking_inset)
1315                 return the_locking_inset->showInsetDialog(bv);
1316         return false;
1317 }
1318
1319
1320 void InsetText::getLabelList(std::vector<string> & list) const
1321 {
1322         ParagraphList::const_iterator pit = paragraphs.begin();
1323         ParagraphList::const_iterator pend = paragraphs.end();
1324         for (; pit != pend; ++pit) {
1325                 InsetList::const_iterator beg = pit->insetlist.begin();
1326                 InsetList::const_iterator end = pit->insetlist.end();
1327                 for (; beg != end; ++beg)
1328                         beg->inset->getLabelList(list);
1329         }
1330 }
1331
1332
1333 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1334                         bool selectall)
1335 {
1336         if (the_locking_inset) {
1337                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1338                 return;
1339         }
1340
1341         if ((paragraphs.size() == 1 && paragraphs.begin()->empty())
1342             || cpar()->empty()) {
1343                 text_.setFont(font, toggleall);
1344                 return;
1345         }
1346
1347
1348         if (text_.selection.set())
1349                 recordUndo(bv, Undo::ATOMIC, text_.cursor.par());
1350
1351         if (selectall) {
1352                 text_.cursorTop();
1353                 text_.selection.cursor = text_.cursor;
1354                 text_.cursorBottom();
1355                 text_.setSelection();
1356         }
1357
1358         text_.toggleFree(font, toggleall);
1359
1360         if (selectall)
1361                 text_.clearSelection();
1362
1363         bv->fitCursor();
1364         updateLocal(bv, true);
1365 }
1366
1367
1368 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1369 {
1370         if (cpos() == cpar()->size())
1371                 return false;
1372         InsetOld * inset = cpar()->getInset(cpos());
1373         if (!isHighlyEditableInset(inset))
1374                 return false;
1375         FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1376         inset->localDispatch(cmd);
1377         if (!the_locking_inset)
1378                 return false;
1379         updateLocal(bv, false);
1380         return true;
1381 }
1382
1383
1384 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1385                                       mouse_button::state button)
1386 {
1387         int dummyx = x;
1388         int dummyy = y + dim_.asc;
1389         InsetOld * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1390         // we only do the edit() call if the inset was hit by the mouse
1391         // or if it is a highly editable inset. So we should call this
1392         // function from our own edit with button < 0.
1393         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1394         // WRONG
1395         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1396                 return false;
1397
1398         if (!inset)
1399                 return false;
1400         if (x < 0)
1401                 x = dim_.wid;
1402         if (y < 0)
1403                 y = dim_.des;
1404         inset_x = cx() - top_x;
1405         inset_y = cy();
1406         FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1407         inset->localDispatch(cmd);
1408         if (!the_locking_inset)
1409                 return false;
1410         updateLocal(bv, false);
1411         return true;
1412 }
1413
1414
1415 void InsetText::markNew(bool track_changes)
1416 {
1417         ParagraphList::iterator pit = paragraphs.begin();
1418         ParagraphList::iterator end = paragraphs.end();
1419         for (; pit != end; ++pit) {
1420                 if (track_changes) {
1421                         pit->trackChanges();
1422                 } else {
1423                         // no-op when not tracking
1424                         pit->cleanChanges();
1425                 }
1426         }
1427 }
1428
1429
1430 void InsetText::setText(string const & data, LyXFont const & font)
1431 {
1432         clear(false);
1433         for (unsigned int i = 0; i < data.length(); ++i)
1434                 paragraphs.begin()->insertChar(i, data[i], font);
1435 }
1436
1437
1438 void InsetText::setAutoBreakRows(bool flag)
1439 {
1440         if (flag != autoBreakRows) {
1441                 autoBreakRows = flag;
1442                 if (!flag)
1443                         removeNewlines();
1444         }
1445 }
1446
1447
1448 void InsetText::setDrawFrame(DrawFrame how)
1449 {
1450         drawFrame_ = how;
1451 }
1452
1453
1454 void InsetText::setFrameColor(EnumLColor col)
1455 {
1456         frame_color = col;
1457 }
1458
1459
1460 int InsetText::cx() const
1461 {
1462         int x = text_.cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
1463         if (the_locking_inset) {
1464                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1465                 if (font.isVisibleRightToLeft())
1466                         x -= the_locking_inset->width();
1467         }
1468         return x;
1469 }
1470
1471
1472 int InsetText::cy() const
1473 {
1474         return text_.cursor.y() - dim_.asc + TEXT_TO_INSET_OFFSET;
1475 }
1476
1477
1478 pos_type InsetText::cpos() const
1479 {
1480         return text_.cursor.pos();
1481 }
1482
1483
1484 ParagraphList::iterator InsetText::cpar() const
1485 {
1486         return text_.cursor.par();
1487 }
1488
1489
1490 bool InsetText::cboundary() const
1491 {
1492         return text_.cursor.boundary();
1493 }
1494
1495
1496 RowList::iterator InsetText::crow() const
1497 {
1498         return text_.cursorRow();
1499 }
1500
1501
1502 LyXText * InsetText::getLyXText(BufferView const * bv,
1503                                 bool const recursive) const
1504 {
1505         setViewCache(bv);
1506         if (recursive && the_locking_inset)
1507                 return the_locking_inset->getLyXText(bv, true);
1508         return &text_;
1509 }
1510
1511
1512 void InsetText::setViewCache(BufferView const * bv) const
1513 {
1514         if (bv) {
1515                 if (bv != text_.bv_owner) {
1516                         //lyxerr << "setting view cache from "
1517                         //      << text_.bv_owner << " to " << bv << "\n";
1518                         text_.init(const_cast<BufferView *>(bv));
1519                 }
1520                 text_.bv_owner = const_cast<BufferView *>(bv);
1521         }
1522 }
1523
1524
1525 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
1526 {
1527         if (recursive) {
1528                 /// then remove all LyXText in text-insets
1529                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1530                          const_cast<ParagraphList&>(paragraphs).end(),
1531                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
1532         }
1533 }
1534
1535
1536 void InsetText::removeNewlines()
1537 {
1538         ParagraphList::iterator it = paragraphs.begin();
1539         ParagraphList::iterator end = paragraphs.end();
1540         for (; it != end; ++it)
1541                 for (int i = 0; i < it->size(); ++i)
1542                         if (it->isNewline(i))
1543                                 it->erase(i);
1544 }
1545
1546
1547 int InsetText::scroll(bool recursive) const
1548 {
1549         int sx = UpdatableInset::scroll(false);
1550
1551         if (recursive && the_locking_inset)
1552                 sx += the_locking_inset->scroll(recursive);
1553
1554         return sx;
1555 }
1556
1557
1558 void InsetText::clearSelection(BufferView *)
1559 {
1560         text_.clearSelection();
1561 }
1562
1563
1564 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
1565 {
1566         Painter & pain = bv->painter();
1567         int w = dim_.wid;
1568         int h = dim_.asc + dim_.des;
1569         int ty = baseline - dim_.asc;
1570
1571         if (ty < 0) {
1572                 h += ty;
1573                 ty = 0;
1574         }
1575         if (ty + h > pain.paperHeight())
1576                 h = pain.paperHeight();
1577         if (top_x + w > pain.paperWidth())
1578                 w = pain.paperWidth();
1579         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
1580 }
1581
1582
1583 ParagraphList * InsetText::getParagraphs(int i) const
1584 {
1585         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
1586 }
1587
1588
1589 LyXCursor const & InsetText::cursor(BufferView * bv) const
1590 {
1591         if (the_locking_inset)
1592                 return the_locking_inset->cursor(bv);
1593         return getLyXText(bv)->cursor;
1594 }
1595
1596
1597 InsetOld * InsetText::getInsetFromID(int id_arg) const
1598 {
1599         if (id_arg == id())
1600                 return const_cast<InsetText *>(this);
1601
1602         ParagraphList::const_iterator pit = paragraphs.begin();
1603         ParagraphList::const_iterator pend = paragraphs.end();
1604         for (; pit != pend; ++pit) {
1605                 InsetList::const_iterator it = pit->insetlist.begin();
1606                 InsetList::const_iterator end = pit->insetlist.end();
1607                 for (; it != end; ++it) {
1608                         if (it->inset->id() == id_arg)
1609                                 return it->inset;
1610                         InsetOld * in = it->inset->getInsetFromID(id_arg);
1611                         if (in)
1612                                 return in;
1613                 }
1614         }
1615         return 0;
1616 }
1617
1618
1619 WordLangTuple const
1620 InsetText::selectNextWordToSpellcheck(BufferView * bv, float & value) const
1621 {
1622         WordLangTuple word;
1623         if (the_locking_inset) {
1624                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
1625                 if (!word.word().empty()) {
1626                         value += cy();
1627                         return word;
1628                 }
1629                 // we have to go on checking so move cursor to the next char
1630                 text_.cursor.pos(text_.cursor.pos() + 1);
1631         }
1632         word = text_.selectNextWordToSpellcheck(value);
1633         if (word.word().empty())
1634                 bv->unlockInset(const_cast<InsetText *>(this));
1635         else
1636                 value = cy();
1637         return word;
1638 }
1639
1640
1641 void InsetText::selectSelectedWord(BufferView * bv)
1642 {
1643         if (the_locking_inset) {
1644                 the_locking_inset->selectSelectedWord(bv);
1645                 return;
1646         }
1647         getLyXText(bv)->selectSelectedWord();
1648         updateLocal(bv, false);
1649 }
1650
1651
1652 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
1653 {
1654         if (the_locking_inset) {
1655                 if (the_locking_inset->nextChange(bv, length))
1656                         return true;
1657                 text_.cursorRight(true);
1658         }
1659         lyx::find::SearchResult result =
1660                 lyx::find::findNextChange(bv, &text_, length);
1661
1662         if (result == lyx::find::SR_FOUND) {
1663                 LyXCursor cur = text_.cursor;
1664                 bv->unlockInset(bv->theLockingInset());
1665                 if (bv->lockInset(this))
1666                         locked = true;
1667                 text_.cursor = cur;
1668                 text_.setSelectionRange(length);
1669                 updateLocal(bv, false);
1670         }
1671         return result != lyx::find::SR_NOT_FOUND;
1672 }
1673
1674
1675 bool InsetText::searchForward(BufferView * bv, string const & str,
1676                               bool cs, bool mw)
1677 {
1678         if (the_locking_inset) {
1679                 if (the_locking_inset->searchForward(bv, str, cs, mw))
1680                         return true;
1681                 text_.cursorRight(true);
1682         }
1683         lyx::find::SearchResult result =
1684                 lyx::find::find(bv, &text_, str, true, cs, mw);
1685
1686         if (result == lyx::find::SR_FOUND) {
1687                 LyXCursor cur = text_.cursor;
1688                 bv->unlockInset(bv->theLockingInset());
1689                 if (bv->lockInset(this))
1690                         locked = true;
1691                 text_.cursor = cur;
1692                 text_.setSelectionRange(str.length());
1693                 updateLocal(bv, false);
1694         }
1695         return result != lyx::find::SR_NOT_FOUND;
1696 }
1697
1698
1699 bool InsetText::searchBackward(BufferView * bv, string const & str,
1700                                bool cs, bool mw)
1701 {
1702         if (the_locking_inset) {
1703                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
1704                         return true;
1705         }
1706         if (!locked) {
1707                 ParagraphList::iterator pit = boost::prior(paragraphs.end());
1708                 text_.setCursor(pit, pit->size());
1709         }
1710         lyx::find::SearchResult result =
1711                 lyx::find::find(bv, &text_, str, false, cs, mw);
1712
1713         if (result == lyx::find::SR_FOUND) {
1714                 LyXCursor cur = text_.cursor;
1715                 bv->unlockInset(bv->theLockingInset());
1716                 if (bv->lockInset(this))
1717                         locked = true;
1718                 text_.cursor = cur;
1719                 text_.setSelectionRange(str.length());
1720                 updateLocal(bv, false);
1721         }
1722         return result != lyx::find::SR_NOT_FOUND;
1723 }
1724
1725
1726 bool InsetText::checkInsertChar(LyXFont & font)
1727 {
1728         return owner() ? owner()->checkInsertChar(font) : true;
1729 }
1730
1731
1732 void InsetText::collapseParagraphs(BufferView * bv)
1733 {
1734         while (paragraphs.size() > 1) {
1735                 ParagraphList::iterator first_par = paragraphs.begin();
1736                 ParagraphList::iterator next_par = boost::next(first_par);
1737                 size_t const first_par_size = first_par->size();
1738
1739                 if (!first_par->empty() &&
1740                     !next_par->empty() &&
1741                     !first_par->isSeparator(first_par_size - 1)) {
1742                         first_par->insertChar(first_par_size, ' ');
1743                 }
1744
1745                 if (text_.selection.set()) {
1746                         if (text_.selection.start.par() == next_par) {
1747                                 text_.selection.start.par(first_par);
1748                                 text_.selection.start.pos(
1749                                         text_.selection.start.pos() + first_par_size);
1750                         }
1751                         if (text_.selection.end.par() == next_par) {
1752                                 text_.selection.end.par(first_par);
1753                                 text_.selection.end.pos(
1754                                         text_.selection.end.pos() + first_par_size);
1755                         }
1756                 }
1757
1758                 mergeParagraph(bv->buffer()->params(), paragraphs, first_par);
1759         }
1760 }
1761
1762
1763 void InsetText::getDrawFont(LyXFont & font) const
1764 {
1765         if (!owner())
1766                 return;
1767         owner()->getDrawFont(font);
1768 }
1769
1770
1771 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
1772 {
1773 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
1774 // And it probably does. You have to take a look at this John. (Lgb)
1775 #warning John, have a look here. (Lgb)
1776         ParagraphList::iterator pit = plist.begin();
1777         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
1778         ++pit;
1779         mergeParagraph(buffer->params(), paragraphs, boost::prior(ins));
1780
1781         ParagraphList::iterator pend = plist.end();
1782         for (; pit != pend; ++pit)
1783                 paragraphs.push_back(*pit);
1784 }
1785
1786
1787 void InsetText::addPreview(PreviewLoader & loader) const
1788 {
1789         ParagraphList::const_iterator pit = paragraphs.begin();
1790         ParagraphList::const_iterator pend = paragraphs.end();
1791
1792         for (; pit != pend; ++pit) {
1793                 InsetList::const_iterator it  = pit->insetlist.begin();
1794                 InsetList::const_iterator end = pit->insetlist.end();
1795                 for (; it != end; ++it)
1796                         it->inset->addPreview(loader);
1797         }
1798 }