]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
d632b12177753d6933efe11b5d042e82b6af39b3
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "EmbeddedFiles.h"
28 #include "ErrorList.h"
29 #include "factory.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Intl.h"
34 #include "InsetIterator.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LyX.h"
38 #include "lyxfind.h"
39 #include "LyXFunc.h"
40 #include "Layout.h"
41 #include "LyXRC.h"
42 #include "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
47 #include "Session.h"
48 #include "Text.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
51 #include "TexRow.h"
52 #include "VSpace.h"
53 #include "WordLangTuple.h"
54
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetCommand.h" // ChangeRefs
57 #include "insets/InsetRef.h"
58 #include "insets/InsetText.h"
59
60 #include "frontends/alert.h"
61 #include "frontends/Application.h"
62 #include "frontends/Delegates.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/Painter.h"
65 #include "frontends/Selection.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/ExceptionMessage.h"
72 #include "support/FileFilterList.h"
73 #include "support/filetools.h"
74 #include "support/gettext.h"
75 #include "support/lstrings.h"
76 #include "support/Package.h"
77 #include "support/types.h"
78
79 #include <cerrno>
80 #include <fstream>
81 #include <functional>
82 #include <iterator>
83 #include <vector>
84
85 using namespace std;
86 using namespace lyx::support;
87
88 namespace lyx {
89
90 namespace Alert = frontend::Alert;
91
92 namespace {
93
94 /// Return an inset of this class if it exists at the current cursor position
95 template <class T>
96 T * getInsetByCode(Cursor const & cur, InsetCode code)
97 {
98         DocIterator it = cur;
99         Inset * inset = it.nextInset();
100         if (inset && inset->lyxCode() == code)
101                 return static_cast<T*>(inset);
102         return 0;
103 }
104
105
106 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
107         bool same_content);
108
109 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
110         docstring const & contents)
111 {
112         DocIterator tmpdit = dit;
113
114         while (tmpdit) {
115                 Inset const * inset = tmpdit.nextInset();
116                 if (inset
117                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
118                     && (contents.empty() ||
119                     static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
120                         dit = tmpdit;
121                         return true;
122                 }
123                 tmpdit.forwardInset();
124         }
125
126         return false;
127 }
128
129
130 /// Looks for next inset with one of the given codes.
131 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
132         bool same_content)
133 {
134         docstring contents;
135         DocIterator tmpdit = dit;
136         tmpdit.forwardInset();
137         if (!tmpdit)
138                 return false;
139
140         if (same_content) {
141                 Inset const * inset = tmpdit.nextInset();
142                 if (inset
143                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
144                         contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
145                 }
146         }
147
148         if (!findNextInset(tmpdit, codes, contents)) {
149                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
150                         tmpdit  = doc_iterator_begin(tmpdit.bottom().inset());
151                         if (!findNextInset(tmpdit, codes, contents))
152                                 return false;
153                 } else
154                         return false;
155         }
156
157         dit = tmpdit;
158         return true;
159 }
160
161
162 /// Looks for next inset with the given code
163 void findInset(DocIterator & dit, InsetCode code, bool same_content)
164 {
165         findInset(dit, vector<InsetCode>(1, code), same_content);
166 }
167
168
169 /// Moves cursor to the next inset with one of the given codes.
170 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
171                bool same_content)
172 {
173         Cursor tmpcur = bv->cursor();
174         if (!findInset(tmpcur, codes, same_content)) {
175                 bv->cursor().message(_("No more insets"));
176                 return;
177         }
178
179         tmpcur.clearSelection();
180         bv->setCursor(tmpcur);
181         bv->showCursor();
182 }
183
184
185 /// Moves cursor to the next inset with given code.
186 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
187 {
188         gotoInset(bv, vector<InsetCode>(1, code), same_content);
189 }
190
191
192 /// A map from a Text to the associated text metrics
193 typedef map<Text const *, TextMetrics> TextMetricsCache;
194
195 enum ScreenUpdateStrategy {
196         NoScreenUpdate,
197         SingleParUpdate,
198         FullScreenUpdate,
199         DecorationUpdate
200 };
201
202 } // anon namespace
203
204
205 /////////////////////////////////////////////////////////////////////
206 //
207 // BufferView
208 //
209 /////////////////////////////////////////////////////////////////////
210
211 struct BufferView::Private
212 {
213         Private(BufferView & bv): wh_(0), cursor_(bv),
214                 anchor_pit_(0), anchor_ypos_(0),
215                 last_inset_(0), gui_(0)
216         {}
217
218         ///
219         ScrollbarParameters scrollbarParameters_;
220         ///
221         ScreenUpdateStrategy update_strategy_;
222         ///
223         CoordCache coord_cache_;
224
225         /// Estimated average par height for scrollbar.
226         int wh_;
227         /// this is used to handle XSelection events in the right manner.
228         struct {
229                 CursorSlice cursor;
230                 CursorSlice anchor;
231                 bool set;
232         } xsel_cache_;
233         ///
234         Cursor cursor_;
235         ///
236         pit_type anchor_pit_;
237         ///
238         int anchor_ypos_;
239         ///
240         vector<int> par_height_;
241
242         /// keyboard mapping object.
243         Intl intl_;
244
245         /// last visited inset.
246         /** kept to send setMouseHover(false).
247           * Not owned, so don't delete.
248           */
249         Inset * last_inset_;
250
251         mutable TextMetricsCache text_metrics_;
252
253         /// Whom to notify.
254         /** Not owned, so don't delete.
255           */
256         frontend::GuiBufferViewDelegate * gui_;
257 };
258
259
260 BufferView::BufferView(Buffer & buf)
261         : width_(0), height_(0), buffer_(buf), d(new Private(*this))
262 {
263         d->xsel_cache_.set = false;
264         d->intl_.initKeyMapper(lyxrc.use_kbmap);
265
266         d->cursor_.push(buffer_.inset());
267         d->cursor_.resetAnchor();
268         d->cursor_.setCurrentFont();
269
270         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
271                 graphics::Previews::get().generateBufferPreviews(buffer_);
272 }
273
274
275 BufferView::~BufferView()
276 {
277         // current buffer is going to be switched-off, save cursor pos
278         // Ideally, the whole cursor stack should be saved, but session
279         // currently can only handle bottom (whole document) level pit and pos.
280         // That is to say, if a cursor is in a nested inset, it will be
281         // restore to the left of the top level inset.
282         LastFilePosSection::FilePos fp;
283         fp.pit = d->cursor_.bottom().pit();
284         fp.pos = d->cursor_.bottom().pos();
285         LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
286
287         delete d;
288 }
289
290
291 Intl & BufferView::getIntl()
292 {
293         return d->intl_;
294 }
295
296
297 Intl const & BufferView::getIntl() const
298 {
299         return d->intl_;
300 }
301
302
303 CoordCache & BufferView::coordCache()
304 {
305         return d->coord_cache_;
306 }
307
308
309 CoordCache const & BufferView::coordCache() const
310 {
311         return d->coord_cache_;
312 }
313
314
315 Buffer & BufferView::buffer()
316 {
317         return buffer_;
318 }
319
320
321 Buffer const & BufferView::buffer() const
322 {
323         return buffer_;
324 }
325
326
327 bool BufferView::fitCursor()
328 {
329         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
330                 frontend::FontMetrics const & fm =
331                         theFontMetrics(d->cursor_.getFont().fontInfo());
332                 int const asc = fm.maxAscent();
333                 int const des = fm.maxDescent();
334                 Point const p = getPos(d->cursor_, d->cursor_.boundary());
335                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
336                         return false;
337         }
338         return true;
339 }
340
341
342 void BufferView::processUpdateFlags(Update::flags flags)
343 {
344         // last_inset_ points to the last visited inset. This pointer may become
345         // invalid because of keyboard editing. Since all such operations
346         // causes screen update(), I reset last_inset_ to avoid such a problem.
347         d->last_inset_ = 0;
348         // This is close to a hot-path.
349         LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
350                 << "[fitcursor = " << (flags & Update::FitCursor)
351                 << ", forceupdate = " << (flags & Update::Force)
352                 << ", singlepar = " << (flags & Update::SinglePar)
353                 << "]  buffer: " << &buffer_);
354
355         buffer_.updateMacros();
356
357         // Now do the first drawing step if needed. This consists on updating
358         // the CoordCache in updateMetrics().
359         // The second drawing step is done in WorkArea::redraw() if needed.
360
361         // Case when no explicit update is requested.
362         if (!flags) {
363                 // no need to redraw anything.
364                 d->update_strategy_ = NoScreenUpdate;
365                 return;
366         }
367
368         if (flags == Update::Decoration) {
369                 d->update_strategy_ = DecorationUpdate;
370                 buffer_.changed();
371                 return;
372         }
373
374         if (flags == Update::FitCursor
375                 || flags == (Update::Decoration | Update::FitCursor)) {
376                 // tell the frontend to update the screen if needed.
377                 if (fitCursor()) {
378                         showCursor();
379                         return;
380                 }
381                 if (flags & Update::Decoration) {
382                         d->update_strategy_ = DecorationUpdate;
383                         buffer_.changed();
384                         return;
385                 }
386                 // no screen update is needed.
387                 d->update_strategy_ = NoScreenUpdate;
388                 return;
389         }
390
391         bool const full_metrics = flags & Update::Force || !singleParUpdate();
392
393         if (full_metrics)
394                 // We have to update the full screen metrics.
395                 updateMetrics();
396
397         if (!(flags & Update::FitCursor)) {
398                 // Nothing to do anymore. Trigger a redraw and return
399                 buffer_.changed();
400                 return;
401         }
402
403         // updateMetrics() does not update paragraph position
404         // This is done at draw() time. So we need a redraw!
405         buffer_.changed();
406
407         if (fitCursor()) {
408                 // The cursor is off screen so ensure it is visible.
409                 // refresh it:
410                 showCursor();
411         }
412 }
413
414
415 void BufferView::updateScrollbar()
416 {
417         if (height_ == 0)
418                 return;
419
420         // We prefer fixed size line scrolling.
421         d->scrollbarParameters_.single_step = defaultRowHeight();
422         // We prefer full screen page scrolling.
423         d->scrollbarParameters_.page_step = height_;
424
425         Text & t = buffer_.text();
426         TextMetrics & tm = d->text_metrics_[&t];                
427
428         LYXERR(Debug::GUI, " Updating scrollbar: height: "
429                 << t.paragraphs().size()
430                 << " curr par: " << d->cursor_.bottom().pit()
431                 << " default height " << defaultRowHeight());
432
433         int const parsize = int(t.paragraphs().size());
434         if (d->par_height_.size() != parsize) {
435                 d->par_height_.clear();
436                 // FIXME: We assume a default paragraph height of 2 rows. This
437                 // should probably be pondered with the screen width.
438                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
439         }
440
441         // Look at paragraph heights on-screen
442         pair<pit_type, ParagraphMetrics const *> first = tm.first();
443         pair<pit_type, ParagraphMetrics const *> last = tm.last();
444         for (pit_type pit = first.first; pit <= last.first; ++pit) {
445                 d->par_height_[pit] = tm.parMetrics(pit).height();
446                 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
447                         << d->par_height_[pit]);
448         }
449
450         int top_pos = first.second->position() - first.second->ascent();
451         int bottom_pos = last.second->position() + last.second->descent();
452         bool first_visible = first.first == 0 && top_pos >= 0;
453         bool last_visible = last.first == parsize  - 1 && bottom_pos <= height_;
454         if (first_visible && last_visible) {
455                 d->scrollbarParameters_.min = 0;
456                 d->scrollbarParameters_.max = 0;
457                 return;
458         }
459
460         d->scrollbarParameters_.min = top_pos;
461         for (size_t i = 0; i != first.first; ++i)
462                 d->scrollbarParameters_.min -= d->par_height_[i];
463         d->scrollbarParameters_.max = bottom_pos;
464         for (size_t i = last.first + 1; i != parsize; ++i)
465                 d->scrollbarParameters_.max += d->par_height_[i];
466
467         d->scrollbarParameters_.position = 0;
468         // The reference is the top position so we remove one page.
469         d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
470 }
471
472
473 ScrollbarParameters const & BufferView::scrollbarParameters() const
474 {
475         return d->scrollbarParameters_;
476 }
477
478
479 docstring BufferView::toolTip(int x, int y) const
480 {
481         // Get inset under mouse, if there is one.
482         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
483         if (!covering_inset)
484                 // No inset, no tooltip...
485                 return docstring();
486         return covering_inset->toolTip(*this, x, y);
487 }
488
489
490 docstring BufferView::contextMenu(int x, int y) const
491 {
492         // Get inset under mouse, if there is one.
493         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
494         if (covering_inset)
495                 return covering_inset->contextMenu(*this, x, y);
496
497         // FIXME: Do something more elaborate here.
498         return from_ascii("edit");
499 }
500
501
502 void BufferView::scrollDocView(int value)
503 {
504         // cut off at the top
505         if (value <= d->scrollbarParameters_.min) {
506                 DocIterator dit = doc_iterator_begin(buffer_.inset());
507                 showCursor(dit);
508                 LYXERR(Debug::SCROLLING, "scroll to top");
509                 return;
510         }
511
512         // cut off at the bottom
513         if (value >= d->scrollbarParameters_.max) {
514                 DocIterator dit = doc_iterator_end(buffer_.inset());
515                 dit.backwardPos();
516                 showCursor(dit);
517                 LYXERR(Debug::SCROLLING, "scroll to bottom");
518                 return;
519         }
520
521
522         int const offset = value - d->scrollbarParameters_.position;
523         // If the offset is less than 2 screen height, prefer to scroll instead.
524         if (abs(offset) <= 2 * height_) {
525                 scroll(offset);
526                 return;
527         }
528
529         // find paragraph at target position
530         int par_pos = d->scrollbarParameters_.min;
531         pit_type i = 0;
532         for (; i != d->par_height_.size(); ++i) {
533                 par_pos += d->par_height_[i];
534                 if (par_pos >= value)
535                         break;
536         }
537
538         if (par_pos < value) {
539                 // It seems we didn't find the correct pit so stay on the safe side and
540                 // scroll to bottom.
541                 LYXERR0("scrolling position not found!");
542                 scrollDocView(d->scrollbarParameters_.max);
543                 return;
544         }
545
546         DocIterator dit = doc_iterator_begin(buffer_.inset());
547         dit.pit() = i;
548         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
549         showCursor(dit);
550 }
551
552
553 // FIXME: this method is not working well.
554 void BufferView::setCursorFromScrollbar()
555 {
556         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
557
558         int const height = 2 * defaultRowHeight();
559         int const first = height;
560         int const last = height_ - height;
561         Cursor & cur = d->cursor_;
562
563         switch (cursorStatus(cur)) {
564         case CUR_ABOVE:
565                 // We reset the cursor because cursorStatus() does not
566                 // work when the cursor is within mathed.
567                 cur.reset(buffer_.inset());
568                 tm.setCursorFromCoordinates(cur, 0, first);
569                 cur.clearSelection();
570                 break;
571         case CUR_BELOW:
572                 // We reset the cursor because cursorStatus() does not
573                 // work when the cursor is within mathed.
574                 cur.reset(buffer_.inset());
575                 tm.setCursorFromCoordinates(cur, 0, last);
576                 cur.clearSelection();
577                 break;
578         case CUR_INSIDE:
579                 int const y = getPos(cur, cur.boundary()).y_;
580                 int const newy = min(last, max(y, first));
581                 if (y != newy) {
582                         cur.reset(buffer_.inset());
583                         tm.setCursorFromCoordinates(cur, 0, newy);
584                 }
585         }
586 }
587
588
589 Change const BufferView::getCurrentChange() const
590 {
591         if (!d->cursor_.selection())
592                 return Change(Change::UNCHANGED);
593
594         DocIterator dit = d->cursor_.selectionBegin();
595         return dit.paragraph().lookupChange(dit.pos());
596 }
597
598
599 // this could be used elsewhere as well?
600 // FIXME: This does not work within mathed!
601 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
602 {
603         Point const p = getPos(dit, dit.boundary());
604         if (p.y_ < 0)
605                 return CUR_ABOVE;
606         if (p.y_ > workHeight())
607                 return CUR_BELOW;
608         return CUR_INSIDE;
609 }
610
611
612 void BufferView::saveBookmark(unsigned int idx)
613 {
614         // tenatively save bookmark, id and pos will be used to
615         // acturately locate a bookmark in a 'live' lyx session.
616         // pit and pos will be updated with bottom level pit/pos
617         // when lyx exits.
618         LyX::ref().session().bookmarks().save(
619                 buffer_.fileName(),
620                 d->cursor_.bottom().pit(),
621                 d->cursor_.bottom().pos(),
622                 d->cursor_.paragraph().id(),
623                 d->cursor_.pos(),
624                 idx
625         );
626         if (idx)
627                 // emit message signal.
628                 message(_("Save bookmark"));
629 }
630
631
632 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
633         int top_id, pos_type top_pos)
634 {
635         bool success = false;
636         DocIterator doc_it;
637
638         d->cursor_.clearSelection();
639
640         // if a valid par_id is given, try it first
641         // This is the case for a 'live' bookmark when unique paragraph ID
642         // is used to track bookmarks.
643         if (top_id > 0) {
644                 ParIterator par = buffer_.getParFromID(top_id);
645                 if (par != buffer_.par_iterator_end()) {
646                         doc_it = makeDocIterator(par, min(par->size(), top_pos));
647                         // Some slices of the iterator may not be
648                         // reachable (e.g. closed collapsable inset)
649                         // so the dociterator may need to be
650                         // shortened. Otherwise, setCursor may crash
651                         // lyx when the cursor can not be set to these
652                         // insets.
653                         size_t const n = doc_it.depth();
654                         for (size_t i = 0; i < n; ++i)
655                                 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
656                                         doc_it.resize(i);
657                                         break;
658                                 }
659                         success = true;
660                 }
661         }
662
663         // if top_id == 0, or searching through top_id failed
664         // This is the case for a 'restored' bookmark when only bottom
665         // (document level) pit was saved. Because of this, bookmark
666         // restoration is inaccurate. If a bookmark was within an inset,
667         // it will be restored to the left of the outmost inset that contains
668         // the bookmark.
669         if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
670                 doc_it = doc_iterator_begin(buffer_.inset());
671                 doc_it.pit() = bottom_pit;
672                 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
673                 success = true;
674         }
675
676         if (success) {
677                 // Note: only bottom (document) level pit is set.
678                 setCursor(doc_it);
679                 // set the current font.
680                 d->cursor_.setCurrentFont();
681                 // To center the screen on this new position we need the
682                 // paragraph position which is computed at draw() time.
683                 // So we need a redraw!
684                 buffer_.changed();
685                 if (fitCursor())
686                         showCursor();
687         }
688
689         return success;
690 }
691
692
693 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
694 {
695         if (lyxrc.rtl_support) {
696                 if (d->cursor_.real_current_font.isRightToLeft()) {
697                         if (d->intl_.keymap == Intl::PRIMARY)
698                                 d->intl_.keyMapSec();
699                 } else {
700                         if (d->intl_.keymap == Intl::SECONDARY)
701                                 d->intl_.keyMapPrim();
702                 }
703         }
704
705         d->intl_.getTransManager().translateAndInsert(c, t, cur);
706 }
707
708
709 int BufferView::workWidth() const
710 {
711         return width_;
712 }
713
714
715 void BufferView::showCursor()
716 {
717         showCursor(d->cursor_);
718 }
719
720
721 void BufferView::showCursor(DocIterator const & dit)
722 {
723         // We are not properly started yet, delay until resizing is
724         // done.
725         if (height_ == 0)
726                 return;
727
728         LYXERR(Debug::SCROLLING, "recentering!");
729
730         CursorSlice const & bot = dit.bottom();
731         TextMetrics & tm = d->text_metrics_[bot.text()];
732
733         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
734         int bot_pit = bot.pit();
735         if (bot_pit > max_pit) {
736                 // FIXME: Why does this happen?
737                 LYXERR0("bottom pit is greater that max pit: "
738                         << bot_pit << " > " << max_pit);
739                 bot_pit = max_pit;
740         }
741
742         if (bot_pit == tm.first().first - 1)
743                 tm.newParMetricsUp();
744         else if (bot_pit == tm.last().first + 1)
745                 tm.newParMetricsDown();
746
747         if (tm.has(bot_pit)) {
748                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
749                 BOOST_ASSERT(!pm.rows().empty());
750                 // FIXME: smooth scrolling doesn't work in mathed.
751                 CursorSlice const & cs = dit.innerTextSlice();
752                 int offset = coordOffset(dit, dit.boundary()).y_;
753                 int ypos = pm.position() + offset;
754                 Dimension const & row_dim =
755                         pm.getRow(cs.pos(), dit.boundary()).dimension();
756                 if (ypos - row_dim.ascent() < 0)
757                         scrollUp(- ypos + row_dim.ascent());
758                 else if (ypos + row_dim.descent() > height_)
759                         scrollDown(ypos - height_ + row_dim.descent());
760                 // else, nothing to do, the cursor is already visible so we just return.
761                 return;
762         }
763
764         tm.redoParagraph(bot_pit);
765         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
766         int offset = coordOffset(dit, dit.boundary()).y_;
767
768         d->anchor_pit_ = bot_pit;
769         CursorSlice const & cs = dit.innerTextSlice();
770         Dimension const & row_dim =
771                 pm.getRow(cs.pos(), dit.boundary()).dimension();
772
773         if (d->anchor_pit_ == 0)
774                 d->anchor_ypos_ = offset + pm.ascent();
775         else if (d->anchor_pit_ == max_pit)
776                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
777         else
778                 d->anchor_ypos_ = defaultRowHeight() * 2 - offset - row_dim.descent();
779
780         updateMetrics();
781         buffer_.changed();
782 }
783
784
785 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
786 {
787         FuncStatus flag;
788
789         Cursor & cur = d->cursor_;
790
791         switch (cmd.action) {
792
793         case LFUN_UNDO:
794                 flag.enabled(buffer_.undo().hasUndoStack());
795                 break;
796         case LFUN_REDO:
797                 flag.enabled(buffer_.undo().hasRedoStack());
798                 break;
799         case LFUN_FILE_INSERT:
800         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
801         case LFUN_FILE_INSERT_PLAINTEXT:
802         case LFUN_BOOKMARK_SAVE:
803                 // FIXME: Actually, these LFUNS should be moved to Text
804                 flag.enabled(cur.inTexted());
805                 break;
806         case LFUN_FONT_STATE:
807         case LFUN_LABEL_INSERT:
808         case LFUN_INFO_INSERT:
809         case LFUN_PARAGRAPH_GOTO:
810         case LFUN_NOTE_NEXT:
811         case LFUN_REFERENCE_NEXT:
812         case LFUN_WORD_FIND:
813         case LFUN_WORD_REPLACE:
814         case LFUN_MARK_OFF:
815         case LFUN_MARK_ON:
816         case LFUN_MARK_TOGGLE:
817         case LFUN_SCREEN_RECENTER:
818         case LFUN_BIBTEX_DATABASE_ADD:
819         case LFUN_BIBTEX_DATABASE_DEL:
820         case LFUN_STATISTICS:
821         case LFUN_NEXT_INSET_TOGGLE:
822                 flag.enabled(true);
823                 break;
824
825         case LFUN_LABEL_GOTO: {
826                 flag.enabled(!cmd.argument().empty()
827                     || getInsetByCode<InsetRef>(cur, REF_CODE));
828                 break;
829         }
830
831         case LFUN_CHANGES_TRACK:
832                 flag.enabled(true);
833                 flag.setOnOff(buffer_.params().trackChanges);
834                 break;
835
836         case LFUN_CHANGES_OUTPUT:
837                 flag.enabled(true);
838                 flag.setOnOff(buffer_.params().outputChanges);
839                 break;
840
841         case LFUN_CHANGES_MERGE:
842         case LFUN_CHANGE_NEXT:
843         case LFUN_ALL_CHANGES_ACCEPT:
844         case LFUN_ALL_CHANGES_REJECT:
845                 // TODO: context-sensitive enabling of LFUNs
846                 // In principle, these command should only be enabled if there
847                 // is a change in the document. However, without proper
848                 // optimizations, this will inevitably result in poor performance.
849                 flag.enabled(true);
850                 break;
851
852         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
853                 flag.setOnOff(buffer_.params().compressed);
854                 break;
855         }
856         
857         case LFUN_BUFFER_TOGGLE_EMBEDDING: {
858                 flag.setOnOff(buffer_.params().embedded);
859                 break;
860         }
861
862         case LFUN_SCREEN_UP:
863         case LFUN_SCREEN_DOWN:
864         case LFUN_SCROLL:
865                 flag.enabled(true);
866                 break;
867
868         // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
869         // everywhere else before this can enabled:
870         case LFUN_SCREEN_UP_SELECT:
871         case LFUN_SCREEN_DOWN_SELECT:
872                 flag.enabled(false);
873                 break;
874
875         case LFUN_LAYOUT_TABULAR:
876                 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
877                 break;
878
879         case LFUN_LAYOUT:
880         case LFUN_LAYOUT_PARAGRAPH:
881                 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
882                 break;
883
884         case LFUN_INSET_SETTINGS: {
885                 InsetCode code = cur.inset().lyxCode();
886                 bool enable = false;
887                 switch (code) {
888                         case TABULAR_CODE:
889                                 enable = cmd.argument() == "tabular";
890                                 break;
891                         case ERT_CODE:
892                                 enable = cmd.argument() == "ert";
893                                 break;
894                         case FLOAT_CODE:
895                                 enable = cmd.argument() == "float";
896                                 break;
897                         case WRAP_CODE:
898                                 enable = cmd.argument() == "wrap";
899                                 break;
900                         case NOTE_CODE:
901                                 enable = cmd.argument() == "note";
902                                 break;
903                         case BRANCH_CODE:
904                                 enable = cmd.argument() == "branch";
905                                 break;
906                         case BOX_CODE:
907                                 enable = cmd.argument() == "box";
908                                 break;
909                         case LISTINGS_CODE:
910                                 enable = cmd.argument() == "listings";
911                                 break;
912                         default:
913                                 break;
914                 }
915                 flag.enabled(enable);
916                 break;
917         }
918
919         case LFUN_DIALOG_SHOW_NEW_INSET:
920                 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
921                         cur.inset().lyxCode() != LISTINGS_CODE);
922                 if (cur.inset().lyxCode() == CAPTION_CODE) {
923                         FuncStatus flag;
924                         if (cur.inset().getStatus(cur, cmd, flag))
925                                 return flag;
926                 }
927                 break;
928
929         default:
930                 flag.enabled(false);
931         }
932
933         return flag;
934 }
935
936
937 bool BufferView::dispatch(FuncRequest const & cmd)
938 {
939         //lyxerr << [ cmd = " << cmd << "]" << endl;
940
941         // Make sure that the cached BufferView is correct.
942         LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
943                 << " arg[" << to_utf8(cmd.argument()) << ']'
944                 << " x[" << cmd.x << ']'
945                 << " y[" << cmd.y << ']'
946                 << " button[" << cmd.button() << ']');
947
948         Cursor & cur = d->cursor_;
949
950         switch (cmd.action) {
951
952         case LFUN_UNDO:
953                 cur.message(_("Undo"));
954                 cur.clearSelection();
955                 if (!cur.textUndo())
956                         cur.message(_("No further undo information"));
957                 else
958                         processUpdateFlags(Update::Force | Update::FitCursor);
959                 break;
960
961         case LFUN_REDO:
962                 cur.message(_("Redo"));
963                 cur.clearSelection();
964                 if (!cur.textRedo())
965                         cur.message(_("No further redo information"));
966                 else
967                         processUpdateFlags(Update::Force | Update::FitCursor);
968                 break;
969
970         case LFUN_FONT_STATE:
971                 cur.message(cur.currentState());
972                 break;
973
974         case LFUN_BOOKMARK_SAVE:
975                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
976                 break;
977
978         case LFUN_LABEL_GOTO: {
979                 docstring label = cmd.argument();
980                 if (label.empty()) {
981                         InsetRef * inset =
982                                 getInsetByCode<InsetRef>(d->cursor_,
983                                                          REF_CODE);
984                         if (inset) {
985                                 label = inset->getParam("reference");
986                                 // persistent=false: use temp_bookmark
987                                 saveBookmark(0);
988                         }
989                 }
990
991                 if (!label.empty())
992                         gotoLabel(label);
993                 break;
994         }
995
996         case LFUN_PARAGRAPH_GOTO: {
997                 int const id = convert<int>(to_utf8(cmd.argument()));
998                 int i = 0;
999                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1000                         b = theBufferList().next(b)) {
1001
1002                         ParIterator par = b->getParFromID(id);
1003                         if (par == b->par_iterator_end()) {
1004                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1005                         } else {
1006                                 LYXERR(Debug::INFO, "Paragraph " << par->id()
1007                                         << " found in buffer `"
1008                                         << b->absFileName() << "'.");
1009
1010                                 if (b == &buffer_) {
1011                                         // Set the cursor
1012                                         setCursor(makeDocIterator(par, 0));
1013                                         showCursor();
1014                                 } else {
1015                                         // Switch to other buffer view and resend cmd
1016                                         theLyXFunc().dispatch(FuncRequest(
1017                                                 LFUN_BUFFER_SWITCH, b->absFileName()));
1018                                         theLyXFunc().dispatch(cmd);
1019                                 }
1020                                 break;
1021                         }
1022                         ++i;
1023                 }
1024                 break;
1025         }
1026
1027         case LFUN_NOTE_NEXT:
1028                 gotoInset(this, NOTE_CODE, false);
1029                 break;
1030
1031         case LFUN_REFERENCE_NEXT: {
1032                 vector<InsetCode> tmp;
1033                 tmp.push_back(LABEL_CODE);
1034                 tmp.push_back(REF_CODE);
1035                 gotoInset(this, tmp, true);
1036                 break;
1037         }
1038
1039         case LFUN_CHANGES_TRACK:
1040                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1041                 break;
1042
1043         case LFUN_CHANGES_OUTPUT:
1044                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1045                 if (buffer_.params().outputChanges) {
1046                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1047                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1048                                           LaTeXFeatures::isAvailable("xcolor");
1049
1050                         if (!dvipost && !xcolorsoul) {
1051                                 Alert::warning(_("Changes not shown in LaTeX output"),
1052                                                _("Changes will not be highlighted in LaTeX output, "
1053                                                  "because neither dvipost nor xcolor/soul are installed.\n"
1054                                                  "Please install these packages or redefine "
1055                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1056                         } else if (!xcolorsoul) {
1057                                 Alert::warning(_("Changes not shown in LaTeX output"),
1058                                                _("Changes will not be highlighted in LaTeX output "
1059                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
1060                                                  "Please install both packages or redefine "
1061                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1062                         }
1063                 }
1064                 break;
1065
1066         case LFUN_CHANGE_NEXT:
1067                 findNextChange(this);
1068                 break;
1069
1070         case LFUN_CHANGES_MERGE:
1071                 if (findNextChange(this))
1072                         showDialog("changes");
1073                 break;
1074
1075         case LFUN_ALL_CHANGES_ACCEPT:
1076                 // select complete document
1077                 d->cursor_.reset(buffer_.inset());
1078                 d->cursor_.selHandle(true);
1079                 buffer_.text().cursorBottom(d->cursor_);
1080                 // accept everything in a single step to support atomic undo
1081                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1082                 break;
1083
1084         case LFUN_ALL_CHANGES_REJECT:
1085                 // select complete document
1086                 d->cursor_.reset(buffer_.inset());
1087                 d->cursor_.selHandle(true);
1088                 buffer_.text().cursorBottom(d->cursor_);
1089                 // reject everything in a single step to support atomic undo
1090                 // Note: reject does not work recursively; the user may have to repeat the operation
1091                 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1092                 break;
1093
1094         case LFUN_WORD_FIND:
1095                 find(this, cmd);
1096                 break;
1097
1098         case LFUN_WORD_REPLACE: {
1099                 bool has_deleted = false;
1100                 if (cur.selection()) {
1101                         DocIterator beg = cur.selectionBegin();
1102                         DocIterator end = cur.selectionEnd();
1103                         if (beg.pit() == end.pit()) {
1104                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1105                                         if (cur.paragraph().isDeleted(p))
1106                                                 has_deleted = true;
1107                                 }
1108                         }
1109                 }
1110                 replace(this, cmd, has_deleted);
1111                 break;
1112         }
1113
1114         case LFUN_MARK_OFF:
1115                 cur.clearSelection();
1116                 cur.resetAnchor();
1117                 cur.message(from_utf8(N_("Mark off")));
1118                 break;
1119
1120         case LFUN_MARK_ON:
1121                 cur.clearSelection();
1122                 cur.mark() = true;
1123                 cur.resetAnchor();
1124                 cur.message(from_utf8(N_("Mark on")));
1125                 break;
1126
1127         case LFUN_MARK_TOGGLE:
1128                 cur.clearSelection();
1129                 if (cur.mark()) {
1130                         cur.mark() = false;
1131                         cur.message(from_utf8(N_("Mark removed")));
1132                 } else {
1133                         cur.mark() = true;
1134                         cur.message(from_utf8(N_("Mark set")));
1135                 }
1136                 cur.resetAnchor();
1137                 break;
1138
1139         case LFUN_SCREEN_RECENTER:
1140                 showCursor();
1141                 break;
1142
1143         case LFUN_BIBTEX_DATABASE_ADD: {
1144                 Cursor tmpcur = d->cursor_;
1145                 findInset(tmpcur, BIBTEX_CODE, false);
1146                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1147                                                 BIBTEX_CODE);
1148                 if (inset) {
1149                         if (inset->addDatabase(to_utf8(cmd.argument())))
1150                                 buffer_.updateBibfilesCache();
1151                 }
1152                 break;
1153         }
1154
1155         case LFUN_BIBTEX_DATABASE_DEL: {
1156                 Cursor tmpcur = d->cursor_;
1157                 findInset(tmpcur, BIBTEX_CODE, false);
1158                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1159                                                 BIBTEX_CODE);
1160                 if (inset) {
1161                         if (inset->delDatabase(to_utf8(cmd.argument())))
1162                                 buffer_.updateBibfilesCache();
1163                 }
1164                 break;
1165         }
1166
1167         case LFUN_STATISTICS: {
1168                 DocIterator from, to;
1169                 if (cur.selection()) {
1170                         from = cur.selectionBegin();
1171                         to = cur.selectionEnd();
1172                 } else {
1173                         from = doc_iterator_begin(buffer_.inset());
1174                         to = doc_iterator_end(buffer_.inset());
1175                 }
1176                 int const words = countWords(from, to);
1177                 int const chars = countChars(from, to, false);
1178                 int const chars_blanks = countChars(from, to, true);
1179                 docstring message;
1180                 if (cur.selection())
1181                         message = _("Statistics for the selection:");
1182                 else
1183                         message = _("Statistics for the document:");
1184                 message += "\n\n";
1185                 if (words != 1)
1186                         message += bformat(_("%1$d words"), words);
1187                 else
1188                         message += _("One word");
1189                 message += "\n";
1190                 if (chars_blanks != 1)
1191                         message += bformat(_("%1$d characters (including blanks)"),
1192                                           chars_blanks);
1193                 else
1194                         message += _("One character (including blanks)");
1195                 message += "\n";
1196                 if (chars != 1)
1197                         message += bformat(_("%1$d characters (excluding blanks)"),
1198                                           chars);
1199                 else
1200                         message += _("One character (excluding blanks)");
1201
1202                 Alert::information(_("Statistics"), message);
1203         }
1204                 break;
1205
1206         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1207                 // turn compression on/off
1208                 buffer_.params().compressed = !buffer_.params().compressed;
1209                 break;
1210         
1211         case LFUN_BUFFER_TOGGLE_EMBEDDING: {
1212                 // turn embedding on/off
1213                 try {
1214                         buffer_.embeddedFiles().enable(!buffer_.params().embedded, buffer_);
1215                 } catch (ExceptionMessage const & message) {
1216                         Alert::error(message.title_, message.details_);
1217                 }
1218                 break;
1219         }
1220
1221         case LFUN_NEXT_INSET_TOGGLE: {
1222                 // this is the real function we want to invoke
1223                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1224                 // if there is an inset at cursor, see whether it
1225                 // wants to toggle.
1226                 Inset * inset = cur.nextInset();
1227                 if (inset) {
1228                         if (inset->isActive()) {
1229                                 Cursor tmpcur = cur;
1230                                 tmpcur.pushBackward(*inset);
1231                                 inset->dispatch(tmpcur, tmpcmd);
1232                                 if (tmpcur.result().dispatched()) {
1233                                         cur.dispatched();
1234                                 }
1235                         } else if (inset->editable() == Inset::IS_EDITABLE) {
1236                                 inset->edit(cur, true);
1237                         }
1238                 }
1239                 // if it did not work, try the underlying inset.
1240                 if (!cur.result().dispatched())
1241                         cur.dispatch(tmpcmd);
1242
1243                 if (!cur.result().dispatched())
1244                         // It did not work too; no action needed.
1245                         break;
1246                 cur.clearSelection();
1247                 processUpdateFlags(Update::SinglePar | Update::FitCursor);
1248                 break;
1249         }
1250
1251         case LFUN_SCREEN_UP:
1252         case LFUN_SCREEN_DOWN: {
1253                 Point p = getPos(cur, cur.boundary());
1254                 if (p.y_ < 0 || p.y_ > height_) {
1255                         // The cursor is off-screen so recenter before proceeding.
1256                         showCursor();
1257                         p = getPos(cur, cur.boundary());
1258                 }
1259                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1260                 cur.reset(buffer_.inset());
1261                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1262                 //FIXME: what to do with cur.x_target()?
1263                 cur.finishUndo();
1264                 break;
1265         }
1266
1267         case LFUN_SCROLL:
1268                 lfunScroll(cmd);
1269                 break;
1270
1271         case LFUN_SCREEN_UP_SELECT:
1272         case LFUN_SCREEN_DOWN_SELECT: {
1273                 // Those two are not ready yet for consumption.
1274                 return false;
1275
1276                 cur.selHandle(true);
1277                 size_t initial_depth = cur.depth();
1278                 Point const p = getPos(cur, cur.boundary());
1279                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1280                 // FIXME: We need to verify if the cursor stayed within an inset...
1281                 //cur.reset(buffer_.inset());
1282                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1283                 cur.finishUndo();
1284                 while (cur.depth() > initial_depth) {
1285                         cur.forwardInset();
1286                 }
1287                 // FIXME: we need to do a redraw again because of the selection
1288                 // But no screen update is needed.
1289                 d->update_strategy_ = NoScreenUpdate;
1290                 buffer_.changed();
1291                 break;
1292         }
1293
1294         default:
1295                 return false;
1296         }
1297
1298         return true;
1299 }
1300
1301
1302 docstring const BufferView::requestSelection()
1303 {
1304         Cursor & cur = d->cursor_;
1305
1306         if (!cur.selection()) {
1307                 d->xsel_cache_.set = false;
1308                 return docstring();
1309         }
1310
1311         if (!d->xsel_cache_.set ||
1312             cur.top() != d->xsel_cache_.cursor ||
1313             cur.anchor_.top() != d->xsel_cache_.anchor)
1314         {
1315                 d->xsel_cache_.cursor = cur.top();
1316                 d->xsel_cache_.anchor = cur.anchor_.top();
1317                 d->xsel_cache_.set = cur.selection();
1318                 return cur.selectionAsString(false);
1319         }
1320         return docstring();
1321 }
1322
1323
1324 void BufferView::clearSelection()
1325 {
1326         d->cursor_.clearSelection();
1327         // Clear the selection buffer. Otherwise a subsequent
1328         // middle-mouse-button paste would use the selection buffer,
1329         // not the more current external selection.
1330         cap::clearSelection();
1331         d->xsel_cache_.set = false;
1332         // The buffer did not really change, but this causes the
1333         // redraw we need because we cleared the selection above.
1334         buffer_.changed();
1335 }
1336
1337
1338 void BufferView::resize(int width, int height)
1339 {
1340         // Update from work area
1341         width_ = width;
1342         height_ = height;
1343
1344         // Clear the paragraph height cache.
1345         d->par_height_.clear();
1346
1347         updateMetrics();
1348 }
1349
1350
1351 Inset const * BufferView::getCoveringInset(Text const & text,
1352                 int x, int y) const
1353 {
1354         TextMetrics & tm = d->text_metrics_[&text];
1355         Inset * inset = tm.checkInsetHit(x, y);
1356         if (!inset)
1357                 return 0;
1358
1359         if (!inset->descendable())
1360                 // No need to go further down if the inset is not
1361                 // descendable.
1362                 return inset;
1363
1364         size_t cell_number = inset->nargs();
1365         // Check all the inner cell.
1366         for (size_t i = 0; i != cell_number; ++i) {
1367                 Text const * inner_text = inset->getText(i);
1368                 if (inner_text) {
1369                         // Try deeper.
1370                         Inset const * inset_deeper =
1371                                 getCoveringInset(*inner_text, x, y);
1372                         if (inset_deeper)
1373                                 return inset_deeper;
1374                 }
1375         }
1376
1377         return inset;
1378 }
1379
1380
1381 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1382 {
1383         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1384
1385         // This is only called for mouse related events including
1386         // LFUN_FILE_OPEN generated by drag-and-drop.
1387         FuncRequest cmd = cmd0;
1388
1389         Cursor cur(*this);
1390         cur.push(buffer_.inset());
1391         cur.selection() = d->cursor_.selection();
1392
1393         // Either the inset under the cursor or the
1394         // surrounding Text will handle this event.
1395
1396         // make sure we stay within the screen...
1397         cmd.y = min(max(cmd.y, -1), height_);
1398
1399         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1400
1401                 // Get inset under mouse, if there is one.
1402                 Inset const * covering_inset =
1403                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1404                 if (covering_inset == d->last_inset_)
1405                         // Same inset, no need to do anything...
1406                         return;
1407
1408                 bool need_redraw = false;
1409                 // const_cast because of setMouseHover().
1410                 Inset * inset = const_cast<Inset *>(covering_inset);
1411                 if (d->last_inset_)
1412                         // Remove the hint on the last hovered inset (if any).
1413                         need_redraw |= d->last_inset_->setMouseHover(false);
1414                 if (inset)
1415                         // Highlighted the newly hovered inset (if any).
1416                         need_redraw |= inset->setMouseHover(true);
1417                 d->last_inset_ = inset;
1418                 if (!need_redraw)
1419                         return;
1420
1421                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1422                         << cmd.x << ", " << cmd.y << ")");
1423
1424                 d->update_strategy_ = DecorationUpdate;
1425
1426                 // This event (moving without mouse click) is not passed further.
1427                 // This should be changed if it is further utilized.
1428                 buffer_.changed();
1429                 return;
1430         }
1431
1432         // Build temporary cursor.
1433         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1434
1435         // Put anchor at the same position.
1436         cur.resetAnchor();
1437
1438         // Try to dispatch to an non-editable inset near this position
1439         // via the temp cursor. If the inset wishes to change the real
1440         // cursor it has to do so explicitly by using
1441         //  cur.bv().cursor() = cur;  (or similar)
1442         if (inset)
1443                 inset->dispatch(cur, cmd);
1444
1445         // Now dispatch to the temporary cursor. If the real cursor should
1446         // be modified, the inset's dispatch has to do so explicitly.
1447         if (!cur.result().dispatched())
1448                 cur.dispatch(cmd);
1449
1450         //Do we have a selection?
1451         theSelection().haveSelection(cursor().selection());
1452
1453         // If the command has been dispatched,
1454         if (cur.result().dispatched()
1455                 // an update is asked,
1456                 && cur.result().update())
1457                 processUpdateFlags(cur.result().update());
1458 }
1459
1460
1461 void BufferView::lfunScroll(FuncRequest const & cmd)
1462 {
1463         string const scroll_type = cmd.getArg(0);
1464         int const scroll_step = 
1465                 (scroll_type == "line")? d->scrollbarParameters_.single_step
1466                 : (scroll_type == "page")? d->scrollbarParameters_.page_step : 0;
1467         if (scroll_step == 0)
1468                 return;
1469         string const scroll_quantity = cmd.getArg(1);
1470         if (scroll_quantity == "up")
1471                 scrollUp(scroll_step);
1472         else if (scroll_quantity == "down")
1473                 scrollDown(scroll_step);
1474         else {
1475                 int const scroll_value = convert<int>(scroll_quantity);
1476                 if (scroll_value)
1477                         scroll(scroll_step * scroll_value);
1478         }
1479 }
1480
1481
1482 void BufferView::scroll(int y)
1483 {
1484         if (y > 0)
1485                 scrollDown(y);
1486         else if (y < 0)
1487                 scrollUp(-y);
1488 }
1489
1490
1491 void BufferView::scrollDown(int offset)
1492 {
1493         Text * text = &buffer_.text();
1494         TextMetrics & tm = d->text_metrics_[text];
1495         int ymax = height_ + offset;
1496         while (true) {
1497                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1498                 int bottom_pos = last.second->position() + last.second->descent();
1499                 if (last.first + 1 == int(text->paragraphs().size())) {
1500                         if (bottom_pos <= height_)
1501                                 return;
1502                         offset = min(offset, bottom_pos - height_);
1503                         break;
1504                 }
1505                 if (bottom_pos > ymax)
1506                         break;
1507                 tm.newParMetricsDown();
1508         }
1509         d->anchor_ypos_ -= offset;
1510         updateMetrics();
1511         buffer_.changed();
1512 }
1513
1514
1515 void BufferView::scrollUp(int offset)
1516 {
1517         Text * text = &buffer_.text();
1518         TextMetrics & tm = d->text_metrics_[text];
1519         int ymin = - offset;
1520         while (true) {
1521                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1522                 int top_pos = first.second->position() - first.second->ascent();
1523                 if (first.first == 0) {
1524                         if (top_pos >= 0)
1525                                 return;
1526                         offset = min(offset, - top_pos);
1527                         break;
1528                 }
1529                 if (top_pos < ymin)
1530                         break;
1531                 tm.newParMetricsUp();
1532         }
1533         d->anchor_ypos_ += offset;
1534         updateMetrics();
1535         buffer_.changed();
1536 }
1537
1538
1539 void BufferView::setCursorFromRow(int row)
1540 {
1541         int tmpid = -1;
1542         int tmppos = -1;
1543
1544         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1545
1546         d->cursor_.reset(buffer_.inset());
1547         if (tmpid == -1)
1548                 buffer_.text().setCursor(d->cursor_, 0, 0);
1549         else
1550                 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1551 }
1552
1553
1554 void BufferView::gotoLabel(docstring const & label)
1555 {
1556         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1557                 vector<docstring> labels;
1558                 it->getLabelList(buffer_, labels);
1559                 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1560                         setCursor(it);
1561                         showCursor();
1562                         return;
1563                 }
1564         }
1565 }
1566
1567
1568 TextMetrics const & BufferView::textMetrics(Text const * t) const
1569 {
1570         return const_cast<BufferView *>(this)->textMetrics(t);
1571 }
1572
1573
1574 TextMetrics & BufferView::textMetrics(Text const * t)
1575 {
1576         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
1577         if (tmc_it == d->text_metrics_.end()) {
1578                 tmc_it = d->text_metrics_.insert(
1579                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1580         }
1581         return tmc_it->second;
1582 }
1583
1584
1585 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1586                 pit_type pit) const
1587 {
1588         return textMetrics(t).parMetrics(pit);
1589 }
1590
1591
1592 int BufferView::workHeight() const
1593 {
1594         return height_;
1595 }
1596
1597
1598 void BufferView::setCursor(DocIterator const & dit)
1599 {
1600         size_t const n = dit.depth();
1601         for (size_t i = 0; i < n; ++i)
1602                 dit[i].inset().edit(d->cursor_, true);
1603
1604         d->cursor_.setCursor(dit);
1605         d->cursor_.selection() = false;
1606 }
1607
1608
1609 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1610 {
1611         // Would be wrong to delete anything if we have a selection.
1612         if (cur.selection())
1613                 return false;
1614
1615         bool need_anchor_change = false;
1616         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1617                 need_anchor_change);
1618
1619         if (need_anchor_change)
1620                 cur.resetAnchor();
1621
1622         if (!changed)
1623                 return false;
1624
1625         d->cursor_ = cur;
1626
1627         updateLabels(buffer_);
1628
1629         updateMetrics();
1630         buffer_.changed();
1631         return true;
1632 }
1633
1634
1635 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1636 {
1637         BOOST_ASSERT(&cur.bv() == this);
1638
1639         if (!select)
1640                 // this event will clear selection so we save selection for
1641                 // persistent selection
1642                 cap::saveSelection(cursor());
1643
1644         // Has the cursor just left the inset?
1645         bool badcursor = false;
1646         bool leftinset = (&d->cursor_.inset() != &cur.inset());
1647         if (leftinset)
1648                 badcursor = notifyCursorLeaves(d->cursor_, cur);
1649
1650         // FIXME: shift-mouse selection doesn't work well across insets.
1651         bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1652
1653         // do the dEPM magic if needed
1654         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1655         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1656         // the leftinset bool would not be necessary (badcursor instead).
1657         bool update = leftinset;
1658         if (!do_selection && !badcursor && d->cursor_.inTexted())
1659                 update |= checkDepm(cur, d->cursor_);
1660
1661         // if the cursor was in an empty script inset and the new
1662         // position is in the nucleus of the inset, notifyCursorLeaves
1663         // will kill the script inset itself. So we check all the
1664         // elements of the cursor to make sure that they are correct.
1665         // For an example, see bug 2933:
1666         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1667         // The code below could maybe be moved to a DocIterator method.
1668         //lyxerr << "cur before " << cur <<endl;
1669         DocIterator dit(cur.inset());
1670         dit.push_back(cur.bottom());
1671         size_t i = 1;
1672         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1673                 dit.push_back(cur[i]);
1674                 ++i;
1675         }
1676         //lyxerr << "5 cur after" << dit <<endl;
1677
1678         d->cursor_.setCursor(dit);
1679         d->cursor_.boundary(cur.boundary());
1680         if (do_selection)
1681                 d->cursor_.setSelection();
1682         else
1683                 d->cursor_.clearSelection();
1684
1685         d->cursor_.finishUndo();
1686         d->cursor_.setCurrentFont();
1687         return update;
1688 }
1689
1690
1691 void BufferView::putSelectionAt(DocIterator const & cur,
1692                                 int length, bool backwards)
1693 {
1694         d->cursor_.clearSelection();
1695
1696         setCursor(cur);
1697
1698         if (length) {
1699                 if (backwards) {
1700                         d->cursor_.pos() += length;
1701                         d->cursor_.setSelection(d->cursor_, -length);
1702                 } else
1703                         d->cursor_.setSelection(d->cursor_, length);
1704         }
1705 }
1706
1707
1708 Cursor & BufferView::cursor()
1709 {
1710         return d->cursor_;
1711 }
1712
1713
1714 Cursor const & BufferView::cursor() const
1715 {
1716         return d->cursor_;
1717 }
1718
1719
1720 pit_type BufferView::anchor_ref() const
1721 {
1722         return d->anchor_pit_;
1723 }
1724
1725
1726 bool BufferView::singleParUpdate()
1727 {
1728         Text & buftext = buffer_.text();
1729         pit_type const bottom_pit = d->cursor_.bottom().pit();
1730         TextMetrics & tm = textMetrics(&buftext);
1731         int old_height = tm.parMetrics(bottom_pit).height();
1732
1733         // In Single Paragraph mode, rebreak only
1734         // the (main text, not inset!) paragraph containing the cursor.
1735         // (if this paragraph contains insets etc., rebreaking will
1736         // recursively descend)
1737         tm.redoParagraph(bottom_pit);
1738         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1739         if (pm.height() != old_height)
1740                 // Paragraph height has changed so we cannot proceed to
1741                 // the singlePar optimisation.
1742                 return false;
1743
1744         d->update_strategy_ = SingleParUpdate;
1745
1746         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1747                 << " y2: " << pm.position() + pm.descent()
1748                 << " pit: " << bottom_pit
1749                 << " singlepar: 1");
1750         return true;
1751 }
1752
1753
1754 void BufferView::updateMetrics()
1755 {
1756         Text & buftext = buffer_.text();
1757         pit_type const npit = int(buftext.paragraphs().size());
1758
1759         // Clear out the position cache in case of full screen redraw,
1760         d->coord_cache_.clear();
1761
1762         // Clear out paragraph metrics to avoid having invalid metrics
1763         // in the cache from paragraphs not relayouted below
1764         // The complete text metrics will be redone.
1765         d->text_metrics_.clear();
1766
1767         TextMetrics & tm = textMetrics(&buftext);
1768
1769         // Rebreak anchor paragraph.
1770         tm.redoParagraph(d->anchor_pit_);
1771         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1772         anchor_pm.setPosition(d->anchor_ypos_);
1773
1774         LYXERR(Debug::PAINTING, "metrics: "
1775                 << " anchor pit = " << d->anchor_pit_
1776                 << " anchor ypos = " << d->anchor_ypos_);
1777
1778         // Redo paragraphs above anchor if necessary.
1779         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1780         // We are now just above the anchor paragraph.
1781         pit_type pit1 = d->anchor_pit_ - 1;
1782         for (; pit1 >= 0 && y1 >= 0; --pit1) {
1783                 tm.redoParagraph(pit1);
1784                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1785                 y1 -= pm.descent();
1786                 // Save the paragraph position in the cache.
1787                 pm.setPosition(y1);
1788                 y1 -= pm.ascent();
1789         }
1790
1791         // Redo paragraphs below the anchor if necessary.
1792         int y2 = d->anchor_ypos_ + anchor_pm.descent();
1793         // We are now just below the anchor paragraph.
1794         pit_type pit2 = d->anchor_pit_ + 1;
1795         for (; pit2 < npit && y2 <= height_; ++pit2) {
1796                 tm.redoParagraph(pit2);
1797                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1798                 y2 += pm.ascent();
1799                 // Save the paragraph position in the cache.
1800                 pm.setPosition(y2);
1801                 y2 += pm.descent();
1802         }
1803
1804         LYXERR(Debug::PAINTING, "Metrics: "
1805                 << " anchor pit = " << d->anchor_pit_
1806                 << " anchor ypos = " << d->anchor_ypos_
1807                 << " y1 = " << y1
1808                 << " y2 = " << y2
1809                 << " pit1 = " << pit1
1810                 << " pit2 = " << pit2);
1811
1812         d->update_strategy_ = FullScreenUpdate;
1813
1814         if (lyxerr.debugging(Debug::WORKAREA)) {
1815                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1816                 d->coord_cache_.dump();
1817         }
1818 }
1819
1820
1821 void BufferView::insertLyXFile(FileName const & fname)
1822 {
1823         BOOST_ASSERT(d->cursor_.inTexted());
1824
1825         // Get absolute path of file and add ".lyx"
1826         // to the filename if necessary
1827         FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1828
1829         docstring const disp_fn = makeDisplayPath(filename.absFilename());
1830         // emit message signal.
1831         message(bformat(_("Inserting document %1$s..."), disp_fn));
1832
1833         docstring res;
1834         Buffer buf("", false);
1835         if (buf.loadLyXFile(filename)) {
1836                 ErrorList & el = buffer_.errorList("Parse");
1837                 // Copy the inserted document error list into the current buffer one.
1838                 el = buf.errorList("Parse");
1839                 buffer_.undo().recordUndo(d->cursor_);
1840                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1841                                              buf.params().getTextClassPtr(), el);
1842                 res = _("Document %1$s inserted.");
1843         } else {
1844                 res = _("Could not insert document %1$s");
1845         }
1846
1847         updateMetrics();
1848         buffer_.changed();
1849         // emit message signal.
1850         message(bformat(res, disp_fn));
1851         buffer_.errors("Parse");
1852 }
1853
1854
1855 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1856 {
1857         int x = 0;
1858         int y = 0;
1859         int lastw = 0;
1860
1861         // Addup contribution of nested insets, from inside to outside,
1862         // keeping the outer paragraph for a special handling below
1863         for (size_t i = dit.depth() - 1; i >= 1; --i) {
1864                 CursorSlice const & sl = dit[i];
1865                 int xx = 0;
1866                 int yy = 0;
1867                 
1868                 // get relative position inside sl.inset()
1869                 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1870                 
1871                 // Make relative position inside of the edited inset relative to sl.inset()
1872                 x += xx;
1873                 y += yy;
1874                 
1875                 // In case of an RTL inset, the edited inset will be positioned to the left
1876                 // of xx:yy
1877                 if (sl.text()) {
1878                         bool boundary_i = boundary && i + 1 == dit.depth();
1879                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1880                         if (rtl)
1881                                 x -= lastw;
1882                 }
1883
1884                 // remember width for the case that sl.inset() is positioned in an RTL inset
1885                 if (i && dit[i - 1].text()) {
1886                         // If this Inset is inside a Text Inset, retrieve the Dimension
1887                         // from the containing text instead of using Inset::dimension() which
1888                         // might not be implemented.
1889                         // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1890                         // elimination of Inset::dim_ cache. This coordOffset() method needs
1891                         // to be rewritten in light of the new design.
1892                         Dimension const & dim = parMetrics(dit[i - 1].text(),
1893                                 dit[i - 1].pit()).insetDimension(&sl.inset());
1894                         lastw = dim.wid;
1895                 } else {
1896                         Dimension const dim = sl.inset().dimension(*this);
1897                         lastw = dim.wid;
1898                 }
1899                 
1900                 //lyxerr << "Cursor::getPos, i: "
1901                 // << i << " x: " << xx << " y: " << y << endl;
1902         }
1903
1904         // Add contribution of initial rows of outermost paragraph
1905         CursorSlice const & sl = dit[0];
1906         TextMetrics const & tm = textMetrics(sl.text());
1907         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1908         BOOST_ASSERT(!pm.rows().empty());
1909         y -= pm.rows()[0].ascent();
1910 #if 1
1911         // FIXME: document this mess
1912         size_t rend;
1913         if (sl.pos() > 0 && dit.depth() == 1) {
1914                 int pos = sl.pos();
1915                 if (pos && boundary)
1916                         --pos;
1917 //              lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1918                 rend = pm.pos2row(pos);
1919         } else
1920                 rend = pm.pos2row(sl.pos());
1921 #else
1922         size_t rend = pm.pos2row(sl.pos());
1923 #endif
1924         for (size_t rit = 0; rit != rend; ++rit)
1925                 y += pm.rows()[rit].height();
1926         y += pm.rows()[rend].ascent();
1927         
1928         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1929         
1930         // Make relative position from the nested inset now bufferview absolute.
1931         int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1932         x += xx;
1933         
1934         // In the RTL case place the nested inset at the left of the cursor in 
1935         // the outer paragraph
1936         bool boundary_1 = boundary && 1 == dit.depth();
1937         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1938         if (rtl)
1939                 x -= lastw;
1940         
1941         return Point(x, y);
1942 }
1943
1944
1945 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1946 {
1947         CursorSlice const & bot = dit.bottom();
1948         TextMetrics const & tm = textMetrics(bot.text());
1949         if (!tm.has(bot.pit()))
1950                 return Point(-1, -1);
1951
1952         Point p = coordOffset(dit, boundary); // offset from outer paragraph
1953         p.y_ += tm.parMetrics(bot.pit()).position();
1954         return p;
1955 }
1956
1957
1958 void BufferView::draw(frontend::Painter & pain)
1959 {
1960         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1961         Text & text = buffer_.text();
1962         TextMetrics const & tm = d->text_metrics_[&text];
1963         int const y = tm.first().second->position();
1964         PainterInfo pi(this, pain);
1965
1966         switch (d->update_strategy_) {
1967
1968         case NoScreenUpdate:
1969                 // If no screen painting is actually needed, only some the different
1970                 // coordinates of insets and paragraphs needs to be updated.
1971                 pi.full_repaint = true;
1972                 pi.pain.setDrawingEnabled(false);
1973                 tm.draw(pi, 0, y);
1974                 break;
1975
1976         case SingleParUpdate:
1977                 pi.full_repaint = false;
1978                 // In general, only the current row of the outermost paragraph
1979                 // will be redrawn. Particular cases where selection spans
1980                 // multiple paragraph are correctly detected in TextMetrics.
1981                 tm.draw(pi, 0, y);
1982                 break;
1983
1984         case DecorationUpdate:
1985                 // FIXME: We should also distinguish DecorationUpdate to avoid text
1986                 // drawing if possible. This is not possible to do easily right now
1987                 // because of the single backing pixmap.
1988
1989         case FullScreenUpdate:
1990                 // The whole screen, including insets, will be refreshed.
1991                 pi.full_repaint = true;
1992
1993                 // Clear background.
1994                 pain.fillRectangle(0, 0, width_, height_,
1995                         buffer_.inset().backgroundColor());
1996
1997                 // Draw everything.
1998                 tm.draw(pi, 0, y);
1999
2000                 // and possibly grey out below
2001                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2002                 int const y2 = lastpm.second->position() + lastpm.second->descent();
2003                 if (y2 < height_)
2004                         pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
2005                 break;
2006         }
2007         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
2008
2009         // The scrollbar needs an update.
2010         updateScrollbar();
2011
2012         // Normalize anchor for next time
2013         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
2014         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
2015         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
2016                 ParagraphMetrics const & pm = tm.parMetrics(pit);
2017                 if (pm.position() + pm.descent() > 0) {
2018                         d->anchor_pit_ = pit;
2019                         d->anchor_ypos_ = pm.position();
2020                         break;
2021                 }
2022         }
2023         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
2024                 << "  anchor ypos = " << d->anchor_ypos_);
2025 }
2026
2027
2028 void BufferView::message(docstring const & msg)
2029 {
2030         if (d->gui_)
2031                 d->gui_->message(msg);
2032 }
2033
2034
2035 void BufferView::showDialog(string const & name)
2036 {
2037         if (d->gui_)
2038                 d->gui_->showDialog(name, string());
2039 }
2040
2041
2042 void BufferView::showDialog(string const & name,
2043         string const & data, Inset * inset)
2044 {
2045         if (d->gui_)
2046                 d->gui_->showDialog(name, data, inset);
2047 }
2048
2049
2050 void BufferView::updateDialog(string const & name, string const & data)
2051 {
2052         if (d->gui_)
2053                 d->gui_->updateDialog(name, data);
2054 }
2055
2056
2057 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
2058 {
2059         d->gui_ = gui;
2060 }
2061
2062
2063 // FIXME: Move this out of BufferView again
2064 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
2065 {
2066         if (!fname.isReadableFile()) {
2067                 docstring const error = from_ascii(strerror(errno));
2068                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2069                 docstring const text =
2070                   bformat(_("Could not read the specified document\n"
2071                             "%1$s\ndue to the error: %2$s"), file, error);
2072                 Alert::error(_("Could not read file"), text);
2073                 return docstring();
2074         }
2075
2076         if (!fname.isReadableFile()) {
2077                 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2078                 docstring const text =
2079                   bformat(_("%1$s\n is not readable."), file);
2080                 Alert::error(_("Could not open file"), text);
2081                 return docstring();
2082         }
2083
2084         // FIXME UNICODE: We don't know the encoding of the file
2085         docstring file_content = fname.fileContents("UTF-8");
2086         if (file_content.empty()) {
2087                 Alert::error(_("Reading not UTF-8 encoded file"),
2088                              _("The file is not UTF-8 encoded.\n"
2089                                "It will be read as local 8Bit-encoded.\n"
2090                                "If this does not give the correct result\n"
2091                                "then please change the encoding of the file\n"
2092                                "to UTF-8 with a program other than LyX.\n"));
2093                 file_content = fname.fileContents("local8bit");
2094         }
2095
2096         return normalize_c(file_content);
2097 }
2098
2099
2100 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2101 {
2102         docstring const tmpstr = contentsOfPlaintextFile(f);
2103
2104         if (tmpstr.empty())
2105                 return;
2106
2107         Cursor & cur = cursor();
2108         cap::replaceSelection(cur);
2109         buffer_.undo().recordUndo(cur);
2110         if (asParagraph)
2111                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2112         else
2113                 cur.innerText()->insertStringAsLines(cur, tmpstr);
2114
2115         updateMetrics();
2116         buffer_.changed();
2117 }
2118
2119 } // namespace lyx