]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
Rename Paragraph::setBuffer to Paragraph::setInsetBuffers, to avoid
[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 "BranchList.h"
20 #include "Buffer.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "CoordCache.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "DispatchResult.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 "LayoutFile.h"
38 #include "Length.h"
39 #include "Lexer.h"
40 #include "LyX.h"
41 #include "LyXAction.h"
42 #include "lyxfind.h"
43 #include "Layout.h"
44 #include "LyXRC.h"
45 #include "MetricsInfo.h"
46 #include "Paragraph.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
49 #include "RowPainter.h"
50 #include "Session.h"
51 #include "Text.h"
52 #include "TextClass.h"
53 #include "TextMetrics.h"
54 #include "TexRow.h"
55 #include "TocBackend.h"
56 #include "WordLangTuple.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCitation.h"
60 #include "insets/InsetCommand.h" // ChangeRefs
61 #include "insets/InsetExternal.h"
62 #include "insets/InsetGraphics.h"
63 #include "insets/InsetNote.h"
64 #include "insets/InsetRef.h"
65 #include "insets/InsetText.h"
66
67 #include "mathed/MathData.h"
68
69 #include "frontends/alert.h"
70 #include "frontends/Application.h"
71 #include "frontends/Delegates.h"
72 #include "frontends/FontMetrics.h"
73 #include "frontends/NullPainter.h"
74 #include "frontends/Painter.h"
75 #include "frontends/Selection.h"
76
77 #include "support/convert.h"
78 #include "support/debug.h"
79 #include "support/ExceptionMessage.h"
80 #include "support/filetools.h"
81 #include "support/gettext.h"
82 #include "support/lassert.h"
83 #include "support/lstrings.h"
84 #include "support/Package.h"
85 #include "support/types.h"
86
87 #include <cerrno>
88 #include <fstream>
89 #include <functional>
90 #include <iterator>
91 #include <sstream>
92 #include <vector>
93
94 using namespace std;
95 using namespace lyx::support;
96
97 namespace lyx {
98
99 namespace Alert = frontend::Alert;
100
101 namespace {
102
103 /// Return an inset of this class if it exists at the current cursor position
104 template <class T>
105 T * getInsetByCode(Cursor const & cur, InsetCode code)
106 {
107         DocIterator it = cur;
108         Inset * inset = it.nextInset();
109         if (inset && inset->lyxCode() == code)
110                 return static_cast<T*>(inset);
111         return 0;
112 }
113
114
115 /// Note that comparing contents can only be used for InsetCommand
116 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
117         docstring const & contents)
118 {
119         DocIterator tmpdit = dit;
120
121         while (tmpdit) {
122                 Inset const * inset = tmpdit.nextInset();
123                 if (inset) {
124                         bool const valid_code = std::find(codes.begin(), codes.end(),
125                                 inset->lyxCode()) != codes.end();
126                         InsetCommand const * ic = inset->asInsetCommand();
127                         bool const same_or_no_contents =  contents.empty()
128                                 || (ic && (ic->getFirstNonOptParam() == contents));
129
130                         if (valid_code && same_or_no_contents) {
131                                 dit = tmpdit;
132                                 return true;
133                         }
134                 }
135                 tmpdit.forwardInset();
136         }
137
138         return false;
139 }
140
141
142 /// Looks for next inset with one of the given codes.
143 /// Note that same_content can only be used for InsetCommand
144 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
145         bool same_content)
146 {
147         docstring contents;
148         DocIterator tmpdit = dit;
149         tmpdit.forwardInset();
150         if (!tmpdit)
151                 return false;
152
153         Inset const * inset = tmpdit.nextInset();
154         if (same_content && inset) {
155                 InsetCommand const * ic = inset->asInsetCommand();
156                 if (ic) {
157                         bool const valid_code = std::find(codes.begin(), codes.end(),
158                                 ic->lyxCode()) != codes.end();
159                         if (valid_code)
160                                 contents = ic->getFirstNonOptParam();
161                 }
162         }
163
164         if (!findNextInset(tmpdit, codes, contents)) {
165                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
166                         Inset * inset = &tmpdit.bottom().inset();
167                         tmpdit = doc_iterator_begin(&inset->buffer(), inset);
168                         if (!findNextInset(tmpdit, codes, contents))
169                                 return false;
170                 } else {
171                         return false;
172                 }
173         }
174
175         dit = tmpdit;
176         return true;
177 }
178
179
180 /// Looks for next inset with the given code
181 void findInset(DocIterator & dit, InsetCode code, bool same_content)
182 {
183         findInset(dit, vector<InsetCode>(1, code), same_content);
184 }
185
186
187 /// Moves cursor to the next inset with one of the given codes.
188 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
189                bool same_content)
190 {
191         Cursor tmpcur = bv->cursor();
192         if (!findInset(tmpcur, codes, same_content)) {
193                 bv->cursor().message(_("No more insets"));
194                 return;
195         }
196
197         tmpcur.clearSelection();
198         bv->setCursor(tmpcur);
199         bv->showCursor();
200 }
201
202
203 /// Moves cursor to the next inset with given code.
204 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
205 {
206         gotoInset(bv, vector<InsetCode>(1, code), same_content);
207 }
208
209
210 /// A map from a Text to the associated text metrics
211 typedef map<Text const *, TextMetrics> TextMetricsCache;
212
213 enum ScreenUpdateStrategy {
214         NoScreenUpdate,
215         SingleParUpdate,
216         FullScreenUpdate,
217         DecorationUpdate
218 };
219
220 } // namespace
221
222
223 /////////////////////////////////////////////////////////////////////
224 //
225 // BufferView
226 //
227 /////////////////////////////////////////////////////////////////////
228
229 struct BufferView::Private
230 {
231         Private(BufferView & bv) : update_strategy_(FullScreenUpdate),
232                 update_flags_(Update::Force),
233                 wh_(0), cursor_(bv),
234                 anchor_pit_(0), anchor_ypos_(0),
235                 inlineCompletionUniqueChars_(0),
236                 last_inset_(0), clickable_inset_(false),
237                 mouse_position_cache_(),
238                 bookmark_edit_position_(-1), gui_(0),
239                 horiz_scroll_offset_(0), repaint_caret_row_(false)
240         {
241                 xsel_cache_.set = false;
242         }
243
244         ///
245         ScrollbarParameters scrollbarParameters_;
246         ///
247         ScreenUpdateStrategy update_strategy_;
248         ///
249         Update::flags update_flags_;
250         ///
251         CoordCache coord_cache_;
252
253         /// Estimated average par height for scrollbar.
254         int wh_;
255         /// this is used to handle XSelection events in the right manner.
256         struct {
257                 CursorSlice cursor;
258                 CursorSlice anchor;
259                 bool set;
260         } xsel_cache_;
261         ///
262         Cursor cursor_;
263         ///
264         pit_type anchor_pit_;
265         ///
266         int anchor_ypos_;
267         ///
268         vector<int> par_height_;
269
270         ///
271         DocIterator inlineCompletionPos_;
272         ///
273         docstring inlineCompletion_;
274         ///
275         size_t inlineCompletionUniqueChars_;
276
277         /// keyboard mapping object.
278         Intl intl_;
279
280         /// last visited inset.
281         /** kept to send setMouseHover(false).
282           * Not owned, so don't delete.
283           */
284         Inset const * last_inset_;
285         /// are we hovering something that we can click
286         bool clickable_inset_;
287
288         /// position of the mouse at the time of the last mouse move
289         /// This is used to update the hovering status of inset in
290         /// cases where the buffer is scrolled, but the mouse didn't move.
291         Point mouse_position_cache_;
292
293         // cache for id of the paragraph which was edited the last time
294         int bookmark_edit_position_;
295
296         mutable TextMetricsCache text_metrics_;
297
298         /// Whom to notify.
299         /** Not owned, so don't delete.
300           */
301         frontend::GuiBufferViewDelegate * gui_;
302
303         /// Cache for Find Next
304         FuncRequest search_request_cache_;
305
306         ///
307         map<string, Inset *> edited_insets_;
308
309         /// When the row where the cursor lies is scrolled, this
310         /// contains the scroll offset
311         int horiz_scroll_offset_;
312         /// a slice pointing to the start of the row where the cursor
313         /// is (at last draw time)
314         CursorSlice current_row_slice_;
315         /// a slice pointing to the start of the row where cursor was
316         /// at previous draw event
317         CursorSlice last_row_slice_;
318
319         /// a slice pointing to where the cursor has been drawn after the current
320         /// draw() call.
321         CursorSlice caret_slice_;
322         /// indicates whether the caret slice needs to be repainted in this draw() run.
323         bool repaint_caret_row_;
324 };
325
326
327 BufferView::BufferView(Buffer & buf)
328         : width_(0), height_(0), full_screen_(false), buffer_(buf),
329       d(new Private(*this))
330 {
331         d->xsel_cache_.set = false;
332         d->intl_.initKeyMapper(lyxrc.use_kbmap);
333
334         d->cursor_.setBuffer(&buf);
335         d->cursor_.push(buffer_.inset());
336         d->cursor_.resetAnchor();
337         d->cursor_.setCurrentFont();
338
339         buffer_.updatePreviews();
340 }
341
342
343 BufferView::~BufferView()
344 {
345         // current buffer is going to be switched-off, save cursor pos
346         // Ideally, the whole cursor stack should be saved, but session
347         // currently can only handle bottom (whole document) level pit and pos.
348         // That is to say, if a cursor is in a nested inset, it will be
349         // restore to the left of the top level inset.
350         LastFilePosSection::FilePos fp;
351         fp.pit = d->cursor_.bottom().pit();
352         fp.pos = d->cursor_.bottom().pos();
353         theSession().lastFilePos().save(buffer_.fileName(), fp);
354
355         if (d->last_inset_)
356                 d->last_inset_->setMouseHover(this, false);
357
358         delete d;
359 }
360
361
362 int BufferView::rightMargin() const
363 {
364         // The value used to be hardcoded to 10, which is 0.1in at 100dpi
365         int const default_margin = Length(0.1, Length::IN).inPixels(0);
366         // The additional test for the case the outliner is opened.
367         if (!full_screen_ || !lyxrc.full_screen_limit
368             || width_ < lyxrc.full_screen_width + 2 * default_margin)
369                 return default_margin;
370
371         return (width_ - lyxrc.full_screen_width) / 2;
372 }
373
374
375 int BufferView::leftMargin() const
376 {
377         return rightMargin();
378 }
379
380
381 int BufferView::inPixels(Length const & len) const
382 {
383         Font const font = buffer().params().getFont();
384         return len.inPixels(workWidth(), theFontMetrics(font).em());
385 }
386
387
388 bool BufferView::isTopScreen() const
389 {
390         return 0 == d->scrollbarParameters_.min;
391 }
392
393
394 bool BufferView::isBottomScreen() const
395 {
396         return 0 == d->scrollbarParameters_.max;
397 }
398
399
400 Intl & BufferView::getIntl()
401 {
402         return d->intl_;
403 }
404
405
406 Intl const & BufferView::getIntl() const
407 {
408         return d->intl_;
409 }
410
411
412 CoordCache & BufferView::coordCache()
413 {
414         return d->coord_cache_;
415 }
416
417
418 CoordCache const & BufferView::coordCache() const
419 {
420         return d->coord_cache_;
421 }
422
423
424 Buffer & BufferView::buffer()
425 {
426         return buffer_;
427 }
428
429
430 Buffer const & BufferView::buffer() const
431 {
432         return buffer_;
433 }
434
435
436 bool BufferView::needsFitCursor() const
437 {
438         if (cursorStatus(d->cursor_) == CUR_INSIDE) {
439                 frontend::FontMetrics const & fm =
440                         theFontMetrics(d->cursor_.getFont().fontInfo());
441                 int const asc = fm.maxAscent();
442                 int const des = fm.maxDescent();
443                 Point const p = getPos(d->cursor_);
444                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
445                         return false;
446         }
447         return true;
448 }
449
450
451 void BufferView::processUpdateFlags(Update::flags flags)
452 {
453         // The update flags are reset to None after the redraw is actually done
454         d->update_flags_ = d->update_flags_ | flags;
455
456         // This is close to a hot-path.
457         LYXERR(Debug::PAINTING, "BufferView::processUpdateFlags( "
458                         << ((d->update_flags_ & Update::FitCursor) ? "fitcursor " : "")
459                         << ((d->update_flags_ & Update::Force) ? "forceupdate " : "")
460                         << ((d->update_flags_ & Update::ForceDraw) ? "forcedraw " : "")
461                         << ((d->update_flags_ & Update::SinglePar) ? "singlepar " : "")
462                                  << ")  buffer: " << &buffer_);
463
464         // Now do the first drawing step if needed. This consists on updating
465         // the CoordCache in updateMetrics().
466         // The second drawing step is done in WorkArea::redraw() if needed.
467         // FIXME: is this still true now that Buffer::changed() is used all over?
468
469         // Case when no explicit update is requested.
470         if (!d->update_flags_) {
471                 // no need to redraw anything.
472                 d->update_strategy_ = NoScreenUpdate;
473                 return;
474         }
475
476         if (d->update_flags_ == Update::Decoration) {
477                 d->update_strategy_ = DecorationUpdate;
478                 buffer_.changed(false);
479                 return;
480         }
481
482         if (d->update_flags_ == Update::FitCursor
483             || d->update_flags_ == (Update::Decoration | Update::FitCursor)) {
484                 // tell the frontend to update the screen if needed.
485                 if (needsFitCursor()) {
486                         showCursor();
487                         return;
488                 }
489                 if (d->update_flags_ & Update::Decoration) {
490                         d->update_strategy_ = DecorationUpdate;
491                         buffer_.changed(false);
492                         return;
493                 }
494                 // no screen update is needed in principle, but this
495                 // could change if cursor row needs horizontal scrolling.
496                 d->update_strategy_ = NoScreenUpdate;
497                 buffer_.changed(false);
498                 return;
499         }
500
501         // We test against the flags parameter here to honor explicit metrics requests
502         bool const full_metrics = flags & Update::Force || !singleParUpdate();
503
504         if (full_metrics)
505                 // We have to update the full screen metrics.
506                 updateMetrics();
507         if (d->update_flags_ & Update::ForceDraw)
508                 d->update_strategy_ = FullScreenUpdate;
509
510         if (!(d->update_flags_ & Update::FitCursor)) {
511                 // Nothing to do anymore. Trigger a redraw and return.
512                 buffer_.changed(false);
513                 return;
514         }
515
516         if (needsFitCursor()) {
517                 // The cursor is off screen so ensure it is visible.
518                 // refresh it:
519                 showCursor();
520         }
521
522         updateHoveredInset();
523
524         // Trigger a redraw.
525         buffer_.changed(false);
526 }
527
528
529 void BufferView::updateScrollbar()
530 {
531         if (height_ == 0 && width_ == 0)
532                 return;
533
534         // We prefer fixed size line scrolling.
535         d->scrollbarParameters_.single_step = defaultRowHeight();
536         // We prefer full screen page scrolling.
537         d->scrollbarParameters_.page_step = height_;
538
539         Text & t = buffer_.text();
540         TextMetrics & tm = d->text_metrics_[&t];
541
542         LYXERR(Debug::GUI, " Updating scrollbar: height: "
543                 << t.paragraphs().size()
544                 << " curr par: " << d->cursor_.bottom().pit()
545                 << " default height " << defaultRowHeight());
546
547         size_t const parsize = t.paragraphs().size();
548         if (d->par_height_.size() != parsize) {
549                 d->par_height_.clear();
550                 // FIXME: We assume a default paragraph height of 2 rows. This
551                 // should probably be pondered with the screen width.
552                 d->par_height_.resize(parsize, defaultRowHeight() * 2);
553         }
554
555         // Look at paragraph heights on-screen
556         pair<pit_type, ParagraphMetrics const *> first = tm.first();
557         pair<pit_type, ParagraphMetrics const *> last = tm.last();
558         for (pit_type pit = first.first; pit <= last.first; ++pit) {
559                 d->par_height_[pit] = tm.parMetrics(pit).height();
560                 LYXERR(Debug::SCROLLING, "storing height for pit " << pit << " : "
561                         << d->par_height_[pit]);
562         }
563
564         int top_pos = first.second->position() - first.second->ascent();
565         int bottom_pos = last.second->position() + last.second->descent();
566         bool first_visible = first.first == 0 && top_pos >= 0;
567         bool last_visible = last.first + 1 == int(parsize) && bottom_pos <= height_;
568         if (first_visible && last_visible) {
569                 d->scrollbarParameters_.min = 0;
570                 d->scrollbarParameters_.max = 0;
571                 return;
572         }
573
574         d->scrollbarParameters_.min = top_pos;
575         for (size_t i = 0; i != size_t(first.first); ++i)
576                 d->scrollbarParameters_.min -= d->par_height_[i];
577         d->scrollbarParameters_.max = bottom_pos;
578         for (size_t i = last.first + 1; i != parsize; ++i)
579                 d->scrollbarParameters_.max += d->par_height_[i];
580
581         // The reference is the top position so we remove one page.
582         if (lyxrc.scroll_below_document)
583                 d->scrollbarParameters_.max -= minVisiblePart();
584         else
585                 d->scrollbarParameters_.max -= d->scrollbarParameters_.page_step;
586
587         // 0 must be inside the range as it denotes the current position
588         if (d->scrollbarParameters_.max < 0)
589                 d->scrollbarParameters_.max = 0;
590         if (d->scrollbarParameters_.min > 0)
591                 d->scrollbarParameters_.min = 0;
592 }
593
594
595 ScrollbarParameters const & BufferView::scrollbarParameters() const
596 {
597         return d->scrollbarParameters_;
598 }
599
600
601 docstring BufferView::toolTip(int x, int y) const
602 {
603         // Get inset under mouse, if there is one.
604         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
605         if (!covering_inset)
606                 // No inset, no tooltip...
607                 return docstring();
608         return covering_inset->toolTip(*this, x, y);
609 }
610
611
612 string BufferView::contextMenu(int x, int y) const
613 {
614         //If there is a selection, return the containing inset menu
615         if (d->cursor_.selection())
616                 return d->cursor_.inset().contextMenu(*this, x, y);
617
618         // Get inset under mouse, if there is one.
619         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
620         if (covering_inset)
621                 return covering_inset->contextMenu(*this, x, y);
622
623         return buffer_.inset().contextMenu(*this, x, y);
624 }
625
626
627
628 void BufferView::scrollDocView(int const value, bool update)
629 {
630         // The scrollbar values are relative to the top of the screen, therefore the
631         // offset is equal to the target value.
632
633         // No scrolling at all? No need to redraw anything
634         if (value == 0)
635                 return;
636
637         // If the offset is less than 2 screen height, prefer to scroll instead.
638         if (abs(value) <= 2 * height_) {
639                 d->anchor_ypos_ -= value;
640                 buffer_.changed(true);
641                 updateHoveredInset();
642                 return;
643         }
644
645         // cut off at the top
646         if (value <= d->scrollbarParameters_.min) {
647                 DocIterator dit = doc_iterator_begin(&buffer_);
648                 showCursor(dit, false, update);
649                 LYXERR(Debug::SCROLLING, "scroll to top");
650                 return;
651         }
652
653         // cut off at the bottom
654         if (value >= d->scrollbarParameters_.max) {
655                 DocIterator dit = doc_iterator_end(&buffer_);
656                 dit.backwardPos();
657                 showCursor(dit, false, update);
658                 LYXERR(Debug::SCROLLING, "scroll to bottom");
659                 return;
660         }
661
662         // find paragraph at target position
663         int par_pos = d->scrollbarParameters_.min;
664         pit_type i = 0;
665         for (; i != int(d->par_height_.size()); ++i) {
666                 par_pos += d->par_height_[i];
667                 if (par_pos >= value)
668                         break;
669         }
670
671         if (par_pos < value) {
672                 // It seems we didn't find the correct pit so stay on the safe side and
673                 // scroll to bottom.
674                 LYXERR0("scrolling position not found!");
675                 scrollDocView(d->scrollbarParameters_.max, update);
676                 return;
677         }
678
679         DocIterator dit = doc_iterator_begin(&buffer_);
680         dit.pit() = i;
681         LYXERR(Debug::SCROLLING, "value = " << value << " -> scroll to pit " << i);
682         showCursor(dit, false, update);
683 }
684
685
686 // FIXME: this method is not working well.
687 void BufferView::setCursorFromScrollbar()
688 {
689         TextMetrics & tm = d->text_metrics_[&buffer_.text()];
690
691         int const height = 2 * defaultRowHeight();
692         int const first = height;
693         int const last = height_ - height;
694         int newy = 0;
695         Cursor const & oldcur = d->cursor_;
696
697         switch (cursorStatus(oldcur)) {
698         case CUR_ABOVE:
699                 newy = first;
700                 break;
701         case CUR_BELOW:
702                 newy = last;
703                 break;
704         case CUR_INSIDE:
705                 int const y = getPos(oldcur).y_;
706                 newy = min(last, max(y, first));
707                 if (y == newy)
708                         return;
709         }
710         // We reset the cursor because cursorStatus() does not
711         // work when the cursor is within mathed.
712         Cursor cur(*this);
713         cur.reset();
714         tm.setCursorFromCoordinates(cur, 0, newy);
715
716         // update the bufferview cursor and notify insets
717         // FIXME: Care about the d->cursor_ flags to redraw if needed
718         Cursor old = d->cursor_;
719         mouseSetCursor(cur);
720         // the DEPM call in mouseSetCursor() might have destroyed the
721         // paragraph the cursor is in.
722         bool badcursor = old.fixIfBroken();
723         badcursor |= notifyCursorLeavesOrEnters(old, d->cursor_);
724         if (badcursor)
725                 d->cursor_.fixIfBroken();
726 }
727
728
729 Change const BufferView::getCurrentChange() const
730 {
731         if (!d->cursor_.selection())
732                 return Change(Change::UNCHANGED);
733
734         DocIterator dit = d->cursor_.selectionBegin();
735         // The selected content might have been changed (see #7685)
736         dit = dit.getInnerText();
737         return dit.paragraph().lookupChange(dit.pos());
738 }
739
740
741 // this could be used elsewhere as well?
742 // FIXME: This does not work within mathed!
743 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
744 {
745         Point const p = getPos(dit);
746         if (p.y_ < 0)
747                 return CUR_ABOVE;
748         if (p.y_ > workHeight())
749                 return CUR_BELOW;
750         return CUR_INSIDE;
751 }
752
753
754 void BufferView::bookmarkEditPosition()
755 {
756         // Don't eat cpu time for each keystroke
757         if (d->cursor_.paragraph().id() == d->bookmark_edit_position_)
758                 return;
759         saveBookmark(0);
760         d->bookmark_edit_position_ = d->cursor_.paragraph().id();
761 }
762
763
764 void BufferView::saveBookmark(unsigned int idx)
765 {
766         // tentatively save bookmark, id and pos will be used to
767         // acturately locate a bookmark in a 'live' lyx session.
768         // pit and pos will be updated with bottom level pit/pos
769         // when lyx exits.
770         if (!buffer_.isInternal()) {
771                 theSession().bookmarks().save(
772                         buffer_.fileName(),
773                         d->cursor_.bottom().pit(),
774                         d->cursor_.bottom().pos(),
775                         d->cursor_.paragraph().id(),
776                         d->cursor_.pos(),
777                         idx
778                         );
779                 if (idx)
780                         // emit message signal.
781                         message(_("Save bookmark"));
782         }
783 }
784
785
786 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
787         int top_id, pos_type top_pos)
788 {
789         bool success = false;
790         DocIterator dit;
791
792         d->cursor_.clearSelection();
793
794         // if a valid par_id is given, try it first
795         // This is the case for a 'live' bookmark when unique paragraph ID
796         // is used to track bookmarks.
797         if (top_id > 0) {
798                 dit = buffer_.getParFromID(top_id);
799                 if (!dit.atEnd()) {
800                         dit.pos() = min(dit.paragraph().size(), top_pos);
801                         // Some slices of the iterator may not be
802                         // reachable (e.g. closed collapsible inset)
803                         // so the dociterator may need to be
804                         // shortened. Otherwise, setCursor may crash
805                         // lyx when the cursor can not be set to these
806                         // insets.
807                         size_t const n = dit.depth();
808                         for (size_t i = 0; i < n; ++i)
809                                 if (!dit[i].inset().editable()) {
810                                         dit.resize(i);
811                                         break;
812                                 }
813                         success = true;
814                 }
815         }
816
817         // if top_id == 0, or searching through top_id failed
818         // This is the case for a 'restored' bookmark when only bottom
819         // (document level) pit was saved. Because of this, bookmark
820         // restoration is inaccurate. If a bookmark was within an inset,
821         // it will be restored to the left of the outmost inset that contains
822         // the bookmark.
823         if (bottom_pit < int(buffer_.paragraphs().size())) {
824                 dit = doc_iterator_begin(&buffer_);
825
826                 dit.pit() = bottom_pit;
827                 dit.pos() = min(bottom_pos, dit.paragraph().size());
828                 success = true;
829         }
830
831         if (success) {
832                 // Note: only bottom (document) level pit is set.
833                 setCursor(dit);
834                 // set the current font.
835                 d->cursor_.setCurrentFont();
836                 // Do not forget to reset the anchor (see #9912)
837                 d->cursor_.resetAnchor();
838                 // To center the screen on this new position we need the
839                 // paragraph position which is computed at draw() time.
840                 // So we need a redraw!
841                 buffer_.changed(false);
842                 if (needsFitCursor())
843                         showCursor();
844         }
845
846         return success;
847 }
848
849
850 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
851 {
852         if (d->cursor_.real_current_font.isRightToLeft()) {
853                 if (d->intl_.keymap == Intl::PRIMARY)
854                         d->intl_.keyMapSec();
855         } else {
856                 if (d->intl_.keymap == Intl::SECONDARY)
857                         d->intl_.keyMapPrim();
858         }
859
860         d->intl_.getTransManager().translateAndInsert(c, t, cur);
861 }
862
863
864 int BufferView::workWidth() const
865 {
866         return width_;
867 }
868
869
870 void BufferView::recenter()
871 {
872         showCursor(d->cursor_, true, true);
873 }
874
875
876 void BufferView::showCursor()
877 {
878         showCursor(d->cursor_, false, true);
879 }
880
881
882 void BufferView::showCursor(DocIterator const & dit,
883         bool recenter, bool update)
884 {
885         if (scrollToCursor(dit, recenter) && update) {
886                 buffer_.changed(true);
887                 updateHoveredInset();
888         }
889 }
890
891
892 void BufferView::scrollToCursor()
893 {
894         if (scrollToCursor(d->cursor_, false)) {
895                 buffer_.changed(true);
896                 updateHoveredInset();
897         }
898 }
899
900
901 bool BufferView::scrollToCursor(DocIterator const & dit, bool const recenter)
902 {
903         // We are not properly started yet, delay until resizing is
904         // done.
905         if (height_ == 0)
906                 return false;
907
908         LYXERR(Debug::SCROLLING, "recentering!");
909
910         CursorSlice const & bot = dit.bottom();
911         TextMetrics & tm = d->text_metrics_[bot.text()];
912
913         pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
914         int bot_pit = bot.pit();
915         if (bot_pit > max_pit) {
916                 // FIXME: Why does this happen?
917                 LYXERR0("bottom pit is greater that max pit: "
918                         << bot_pit << " > " << max_pit);
919                 bot_pit = max_pit;
920         }
921
922         if (bot_pit == tm.first().first - 1)
923                 tm.newParMetricsUp();
924         else if (bot_pit == tm.last().first + 1)
925                 tm.newParMetricsDown();
926
927         if (tm.contains(bot_pit)) {
928                 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
929                 LBUFERR(!pm.rows().empty());
930                 // FIXME: smooth scrolling doesn't work in mathed.
931                 CursorSlice const & cs = dit.innerTextSlice();
932                 int offset = coordOffset(dit).y_;
933                 int ypos = pm.position() + offset;
934                 Dimension const & row_dim =
935                         pm.getRow(cs.pos(), dit.boundary()).dimension();
936                 int scrolled = 0;
937                 if (recenter)
938                         scrolled = scroll(ypos - height_/2);
939
940                 // We try to visualize the whole row, if the row height is larger than
941                 // the screen height, we scroll to a heuristic value of height_ / 4.
942                 // FIXME: This heuristic value should be replaced by a recursive search
943                 // for a row in the inset that can be visualized completely.
944                 else if (row_dim.height() > height_) {
945                         if (ypos < defaultRowHeight())
946                                 scrolled = scroll(ypos - height_ / 4);
947                         else if (ypos > height_ - defaultRowHeight())
948                                 scrolled = scroll(ypos - 3 * height_ / 4);
949                 }
950
951                 // If the top part of the row falls of the screen, we scroll
952                 // up to align the top of the row with the top of the screen.
953                 else if (ypos - row_dim.ascent() < 0 && ypos < height_) {
954                         int ynew = row_dim.ascent();
955                         scrolled = scrollUp(ynew - ypos);
956                 }
957
958                 // If the bottom of the row falls of the screen, we scroll down.
959                 else if (ypos + row_dim.descent() > height_ && ypos > 0) {
960                         int ynew = height_ - row_dim.descent();
961                         scrolled = scrollDown(ypos - ynew);
962                 }
963
964                 // else, nothing to do, the cursor is already visible so we just return.
965                 return scrolled != 0;
966         }
967
968         // fix inline completion position
969         if (d->inlineCompletionPos_.fixIfBroken())
970                 d->inlineCompletionPos_ = DocIterator();
971
972         tm.redoParagraph(bot_pit);
973         ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
974         int offset = coordOffset(dit).y_;
975
976         d->anchor_pit_ = bot_pit;
977         CursorSlice const & cs = dit.innerTextSlice();
978         Dimension const & row_dim =
979                 pm.getRow(cs.pos(), dit.boundary()).dimension();
980
981         if (recenter)
982                 d->anchor_ypos_ = height_/2;
983         else if (d->anchor_pit_ == 0)
984                 d->anchor_ypos_ = offset + pm.ascent();
985         else if (d->anchor_pit_ == max_pit)
986                 d->anchor_ypos_ = height_ - offset - row_dim.descent();
987         else if (offset > height_)
988                 d->anchor_ypos_ = height_ - offset - defaultRowHeight();
989         else
990                 d->anchor_ypos_ = defaultRowHeight() * 2;
991
992         return true;
993 }
994
995
996 void BufferView::makeDocumentClass()
997 {
998         DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
999         buffer_.params().makeDocumentClass();
1000         updateDocumentClass(olddc);
1001 }
1002
1003
1004 void BufferView::updateDocumentClass(DocumentClassConstPtr olddc)
1005 {
1006         message(_("Converting document to new document class..."));
1007
1008         StableDocIterator backcur(d->cursor_);
1009         ErrorList & el = buffer_.errorList("Class Switch");
1010         cap::switchBetweenClasses(
1011                         olddc, buffer_.params().documentClassPtr(),
1012                         static_cast<InsetText &>(buffer_.inset()), el);
1013
1014         setCursor(backcur.asDocIterator(&buffer_));
1015
1016         buffer_.errors("Class Switch");
1017 }
1018
1019
1020 /** Return the change status at cursor position, taking into account the
1021  * status at each level of the document iterator (a table in a deleted
1022  * footnote is deleted).
1023  * When \param outer is true, the top slice is not looked at.
1024  */
1025 static Change::Type lookupChangeType(DocIterator const & dit, bool outer = false)
1026 {
1027         size_t const depth = dit.depth() - (outer ? 1 : 0);
1028
1029         for (size_t i = 0 ; i < depth ; ++i) {
1030                 CursorSlice const & slice = dit[i];
1031                 if (!slice.inset().inMathed()
1032                     && slice.pos() < slice.paragraph().size()) {
1033                         Change::Type const ch = slice.paragraph().lookupChange(slice.pos()).type;
1034                         if (ch != Change::UNCHANGED)
1035                                 return ch;
1036                 }
1037         }
1038         return Change::UNCHANGED;
1039 }
1040
1041
1042 bool BufferView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1043 {
1044         FuncCode const act = cmd.action();
1045
1046         // Can we use a readonly buffer?
1047         if (buffer_.isReadonly()
1048             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1049             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1050                 if (buffer_.hasReadonlyFlag())
1051                         flag.message(from_utf8(N_("Document is read-only")));
1052                 else
1053                         flag.message(from_utf8(N_("Document has been modified externally")));
1054                 flag.setEnabled(false);
1055                 return true;
1056         }
1057
1058         // Are we in a DELETED change-tracking region?
1059         if (lookupChangeType(d->cursor_, true) == Change::DELETED
1060             && !lyxaction.funcHasFlag(act, LyXAction::ReadOnly)
1061             && !lyxaction.funcHasFlag(act, LyXAction::NoBuffer)) {
1062                 flag.message(from_utf8(N_("This portion of the document is deleted.")));
1063                 flag.setEnabled(false);
1064                 return true;
1065         }
1066
1067         Cursor & cur = d->cursor_;
1068
1069         if (cur.getStatus(cmd, flag))
1070                 return true;
1071
1072         switch (act) {
1073
1074         // FIXME: This is a bit problematic because we don't check if this is
1075         // a document BufferView or not for these LFUNs. We probably have to
1076         // dispatch both to currentBufferView() and, if that fails,
1077         // to documentBufferView(); same as we do now for current Buffer and
1078         // document Buffer. Ideally those LFUN should go to Buffer as they
1079         // operate on the full Buffer and the cursor is only needed either for
1080         // an Undo record or to restore a cursor position. But we don't know
1081         // how to do that inside Buffer of course.
1082         case LFUN_BUFFER_PARAMS_APPLY:
1083         case LFUN_LAYOUT_MODULES_CLEAR:
1084         case LFUN_LAYOUT_MODULE_ADD:
1085         case LFUN_LAYOUT_RELOAD:
1086         case LFUN_TEXTCLASS_APPLY:
1087         case LFUN_TEXTCLASS_LOAD:
1088                 flag.setEnabled(!buffer_.isReadonly());
1089                 break;
1090
1091         case LFUN_UNDO:
1092                 // We do not use the LyXAction flag for readonly because Undo sets the
1093                 // buffer clean/dirty status by itself.
1094                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasUndoStack());
1095                 break;
1096         case LFUN_REDO:
1097                 // We do not use the LyXAction flag for readonly because Redo sets the
1098                 // buffer clean/dirty status by itself.
1099                 flag.setEnabled(!buffer_.isReadonly() && buffer_.undo().hasRedoStack());
1100                 break;
1101         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
1102         case LFUN_FILE_INSERT_PLAINTEXT: {
1103                 docstring const fname = cmd.argument();
1104                 if (!FileName::isAbsolute(to_utf8(fname))) {
1105                         flag.message(_("Absolute filename expected."));
1106                         return false;
1107                 }
1108                 flag.setEnabled(cur.inTexted());
1109                 break;
1110         }
1111         case LFUN_FILE_INSERT:
1112         case LFUN_BOOKMARK_SAVE:
1113                 // FIXME: Actually, these LFUNS should be moved to Text
1114                 flag.setEnabled(cur.inTexted());
1115                 break;
1116
1117         case LFUN_FONT_STATE:
1118         case LFUN_LABEL_INSERT:
1119         case LFUN_INFO_INSERT:
1120         case LFUN_PARAGRAPH_GOTO:
1121         case LFUN_NOTE_NEXT:
1122         case LFUN_REFERENCE_NEXT:
1123         case LFUN_WORD_FIND:
1124         case LFUN_WORD_FIND_FORWARD:
1125         case LFUN_WORD_FIND_BACKWARD:
1126         case LFUN_WORD_REPLACE:
1127         case LFUN_MARK_OFF:
1128         case LFUN_MARK_ON:
1129         case LFUN_MARK_TOGGLE:
1130         case LFUN_SCREEN_RECENTER:
1131         case LFUN_SCREEN_SHOW_CURSOR:
1132         case LFUN_BIBTEX_DATABASE_ADD:
1133         case LFUN_BIBTEX_DATABASE_DEL:
1134         case LFUN_STATISTICS:
1135         case LFUN_KEYMAP_OFF:
1136         case LFUN_KEYMAP_PRIMARY:
1137         case LFUN_KEYMAP_SECONDARY:
1138         case LFUN_KEYMAP_TOGGLE:
1139         case LFUN_INSET_SELECT_ALL:
1140                 flag.setEnabled(true);
1141                 break;
1142
1143         case LFUN_WORD_FINDADV: {
1144                 FindAndReplaceOptions opt;
1145                 istringstream iss(to_utf8(cmd.argument()));
1146                 iss >> opt;
1147                 flag.setEnabled(opt.repl_buf_name.empty()
1148                                 || !buffer_.isReadonly());
1149                 break;
1150         }
1151
1152         case LFUN_LABEL_GOTO:
1153                 flag.setEnabled(!cmd.argument().empty()
1154                     || getInsetByCode<InsetRef>(cur, REF_CODE));
1155                 break;
1156
1157         case LFUN_CHANGES_MERGE:
1158         case LFUN_CHANGE_NEXT:
1159         case LFUN_CHANGE_PREVIOUS:
1160         case LFUN_ALL_CHANGES_ACCEPT:
1161         case LFUN_ALL_CHANGES_REJECT:
1162                 flag.setEnabled(buffer_.areChangesPresent());
1163                 break;
1164
1165         case LFUN_SCREEN_UP:
1166         case LFUN_SCREEN_DOWN:
1167         case LFUN_SCROLL:
1168         case LFUN_SCREEN_UP_SELECT:
1169         case LFUN_SCREEN_DOWN_SELECT:
1170         case LFUN_INSET_FORALL:
1171                 flag.setEnabled(true);
1172                 break;
1173
1174         case LFUN_LAYOUT_TABULAR:
1175                 flag.setEnabled(cur.innerInsetOfType(TABULAR_CODE));
1176                 break;
1177
1178         case LFUN_LAYOUT:
1179                 flag.setEnabled(!cur.inset().forcePlainLayout(cur.idx()));
1180                 break;
1181
1182         case LFUN_LAYOUT_PARAGRAPH:
1183                 flag.setEnabled(cur.inset().allowParagraphCustomization(cur.idx()));
1184                 break;
1185
1186         case LFUN_BRANCH_ADD_INSERT:
1187                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1188                 break;
1189
1190         case LFUN_DIALOG_SHOW_NEW_INSET:
1191                 // FIXME: this is wrong, but I do not understand the
1192                 // intent (JMarc)
1193                 if (cur.inset().lyxCode() == CAPTION_CODE)
1194                         return cur.inset().getStatus(cur, cmd, flag);
1195                 // FIXME we should consider passthru paragraphs too.
1196                 flag.setEnabled(!(cur.inTexted() && cur.paragraph().isPassThru()));
1197                 break;
1198
1199         case LFUN_CITATION_INSERT: {
1200                 FuncRequest fr(LFUN_INSET_INSERT, "citation");
1201                 // FIXME: This could turn in a recursive hell.
1202                 // Shouldn't we use Buffer::getStatus() instead?
1203                 flag.setEnabled(lyx::getStatus(fr).enabled());
1204                 break;
1205         }
1206         case LFUN_INSET_APPLY: {
1207                 string const name = cmd.getArg(0);
1208                 Inset * inset = editedInset(name);
1209                 if (inset) {
1210                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1211                         if (!inset->getStatus(cur, fr, flag)) {
1212                                 // Every inset is supposed to handle this
1213                                 LASSERT(false, break);
1214                         }
1215                 } else {
1216                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1217                         flag = lyx::getStatus(fr);
1218                 }
1219                 break;
1220         }
1221
1222         default:
1223                 return false;
1224         }
1225
1226         return true;
1227 }
1228
1229
1230 Inset * BufferView::editedInset(string const & name) const
1231 {
1232         map<string, Inset *>::const_iterator it = d->edited_insets_.find(name);
1233         return it == d->edited_insets_.end() ? 0 : it->second;
1234 }
1235
1236
1237 void BufferView::editInset(string const & name, Inset * inset)
1238 {
1239         d->edited_insets_[name] = inset;
1240 }
1241
1242
1243 void BufferView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1244 {
1245         LYXERR(Debug::ACTION, "BufferView::dispatch: cmd: " << cmd);
1246
1247         string const argument = to_utf8(cmd.argument());
1248         Cursor & cur = d->cursor_;
1249         Cursor old = cur;
1250
1251         // Don't dispatch function that does not apply to internal buffers.
1252         if (buffer_.isInternal()
1253             && lyxaction.funcHasFlag(cmd.action(), LyXAction::NoInternal))
1254                 return;
1255
1256         // We'll set this back to false if need be.
1257         bool dispatched = true;
1258         buffer_.undo().beginUndoGroup();
1259
1260         FuncCode const act = cmd.action();
1261         switch (act) {
1262
1263         case LFUN_BUFFER_PARAMS_APPLY: {
1264                 DocumentClassConstPtr olddc = buffer_.params().documentClassPtr();
1265                 cur.recordUndoBufferParams();
1266                 istringstream ss(to_utf8(cmd.argument()));
1267                 Lexer lex;
1268                 lex.setStream(ss);
1269                 int const unknown_tokens = buffer_.readHeader(lex);
1270                 if (unknown_tokens != 0) {
1271                         LYXERR0("Warning in LFUN_BUFFER_PARAMS_APPLY!\n"
1272                                                 << unknown_tokens << " unknown token"
1273                                                 << (unknown_tokens == 1 ? "" : "s"));
1274                 }
1275                 updateDocumentClass(olddc);
1276
1277                 // We are most certainly here because of a change in the document
1278                 // It is then better to make sure that all dialogs are in sync with
1279                 // current document settings.
1280                 dr.screenUpdate(Update::Force | Update::FitCursor);
1281                 dr.forceBufferUpdate();
1282                 break;
1283         }
1284
1285         case LFUN_LAYOUT_MODULES_CLEAR: {
1286                 // FIXME: this modifies the document in cap::switchBetweenClasses
1287                 //  without calling recordUndo. Fix this before using
1288                 //  recordUndoBufferParams().
1289                 cur.recordUndoFullBuffer();
1290                 buffer_.params().clearLayoutModules();
1291                 makeDocumentClass();
1292                 dr.screenUpdate(Update::Force);
1293                 dr.forceBufferUpdate();
1294                 break;
1295         }
1296
1297         case LFUN_LAYOUT_MODULE_ADD: {
1298                 BufferParams const & params = buffer_.params();
1299                 if (!params.layoutModuleCanBeAdded(argument)) {
1300                         LYXERR0("Module `" << argument <<
1301                                 "' cannot be added due to failed requirements or "
1302                                 "conflicts with installed modules.");
1303                         break;
1304                 }
1305                 // FIXME: this modifies the document in cap::switchBetweenClasses
1306                 //  without calling recordUndo. Fix this before using
1307                 //  recordUndoBufferParams().
1308                 cur.recordUndoFullBuffer();
1309                 buffer_.params().addLayoutModule(argument);
1310                 makeDocumentClass();
1311                 dr.screenUpdate(Update::Force);
1312                 dr.forceBufferUpdate();
1313                 break;
1314         }
1315
1316         case LFUN_TEXTCLASS_APPLY: {
1317                 // since this shortcircuits, the second call is made only if
1318                 // the first fails
1319                 bool const success =
1320                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1321                         LayoutFileList::get().load(argument, buffer_.filePath());
1322                 if (!success) {
1323                         docstring s = bformat(_("The document class `%1$s' "
1324                                                  "could not be loaded."), from_utf8(argument));
1325                         frontend::Alert::error(_("Could not load class"), s);
1326                         break;
1327                 }
1328
1329                 LayoutFile const * old_layout = buffer_.params().baseClass();
1330                 LayoutFile const * new_layout = &(LayoutFileList::get()[argument]);
1331
1332                 if (old_layout == new_layout)
1333                         // nothing to do
1334                         break;
1335
1336                 // Save the old, possibly modular, layout for use in conversion.
1337                 // FIXME: this modifies the document in cap::switchBetweenClasses
1338                 //  without calling recordUndo. Fix this before using
1339                 //  recordUndoBufferParams().
1340                 cur.recordUndoFullBuffer();
1341                 buffer_.params().setBaseClass(argument);
1342                 makeDocumentClass();
1343                 dr.screenUpdate(Update::Force);
1344                 dr.forceBufferUpdate();
1345                 break;
1346         }
1347
1348         case LFUN_TEXTCLASS_LOAD: {
1349                 // since this shortcircuits, the second call is made only if
1350                 // the first fails
1351                 bool const success =
1352                         LayoutFileList::get().load(argument, buffer_.temppath()) ||
1353                         LayoutFileList::get().load(argument, buffer_.filePath());
1354                 if (!success) {
1355                         docstring s = bformat(_("The document class `%1$s' "
1356                                                  "could not be loaded."), from_utf8(argument));
1357                         frontend::Alert::error(_("Could not load class"), s);
1358                 }
1359                 break;
1360         }
1361
1362         case LFUN_LAYOUT_RELOAD: {
1363                 LayoutFileIndex bc = buffer_.params().baseClassID();
1364                 LayoutFileList::get().reset(bc);
1365                 buffer_.params().setBaseClass(bc);
1366                 makeDocumentClass();
1367                 dr.screenUpdate(Update::Force);
1368                 dr.forceBufferUpdate();
1369                 break;
1370         }
1371
1372         case LFUN_UNDO:
1373                 dr.setMessage(_("Undo"));
1374                 cur.clearSelection();
1375                 if (!cur.textUndo())
1376                         dr.setMessage(_("No further undo information"));
1377                 else
1378                         dr.screenUpdate(Update::Force | Update::FitCursor);
1379                 dr.forceBufferUpdate();
1380                 break;
1381
1382         case LFUN_REDO:
1383                 dr.setMessage(_("Redo"));
1384                 cur.clearSelection();
1385                 if (!cur.textRedo())
1386                         dr.setMessage(_("No further redo information"));
1387                 else
1388                         dr.screenUpdate(Update::Force | Update::FitCursor);
1389                 dr.forceBufferUpdate();
1390                 break;
1391
1392         case LFUN_FONT_STATE:
1393                 dr.setMessage(cur.currentState(false));
1394                 break;
1395
1396         case LFUN_BOOKMARK_SAVE:
1397                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
1398                 break;
1399
1400         case LFUN_LABEL_GOTO: {
1401                 docstring label = cmd.argument();
1402                 if (label.empty()) {
1403                         InsetRef * inset =
1404                                 getInsetByCode<InsetRef>(cur, REF_CODE);
1405                         if (inset) {
1406                                 label = inset->getParam("reference");
1407                                 // persistent=false: use temp_bookmark
1408                                 saveBookmark(0);
1409                         }
1410                 }
1411                 if (!label.empty()) {
1412                         gotoLabel(label);
1413                         // at the moment, this is redundant, since gotoLabel will
1414                         // eventually call LFUN_PARAGRAPH_GOTO, but it seems best
1415                         // to have it here.
1416                         dr.screenUpdate(Update::Force | Update::FitCursor);
1417                 }
1418                 break;
1419         }
1420
1421         case LFUN_PARAGRAPH_GOTO: {
1422                 int const id = convert<int>(cmd.getArg(0));
1423                 pos_type const pos = convert<int>(cmd.getArg(1));
1424                 if (id < 0)
1425                         break;
1426                 string const str_id_end = cmd.getArg(2);
1427                 string const str_pos_end = cmd.getArg(3);
1428                 int i = 0;
1429                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
1430                         b = theBufferList().next(b)) {
1431
1432                         Cursor cur(*this);
1433                         cur.setCursor(b->getParFromID(id));
1434                         if (cur.atEnd()) {
1435                                 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
1436                                 ++i;
1437                                 continue;
1438                         }
1439                         LYXERR(Debug::INFO, "Paragraph " << cur.paragraph().id()
1440                                 << " found in buffer `"
1441                                 << b->absFileName() << "'.");
1442
1443                         if (b == &buffer_) {
1444                                 bool success;
1445                                 if (str_id_end.empty() || str_pos_end.empty()) {
1446                                         // Set the cursor
1447                                         cur.pos() = pos;
1448                                         mouseSetCursor(cur);
1449                                         success = true;
1450                                 } else {
1451                                         int const id_end = convert<int>(str_id_end);
1452                                         pos_type const pos_end = convert<int>(str_pos_end);
1453                                         success = setCursorFromEntries({id, pos},
1454                                                                        {id_end, pos_end});
1455                                 }
1456                                 if (success)
1457                                         dr.screenUpdate(Update::Force | Update::FitCursor);
1458                         } else {
1459                                 // Switch to other buffer view and resend cmd
1460                                 lyx::dispatch(FuncRequest(
1461                                         LFUN_BUFFER_SWITCH, b->absFileName()));
1462                                 lyx::dispatch(cmd);
1463                         }
1464                         break;
1465                 }
1466                 break;
1467         }
1468
1469         case LFUN_NOTE_NEXT:
1470                 gotoInset(this, NOTE_CODE, false);
1471                 break;
1472
1473         case LFUN_REFERENCE_NEXT: {
1474                 vector<InsetCode> tmp;
1475                 tmp.push_back(LABEL_CODE);
1476                 tmp.push_back(REF_CODE);
1477                 gotoInset(this, tmp, true);
1478                 break;
1479         }
1480
1481         case LFUN_CHANGE_NEXT:
1482                 findNextChange(this);
1483                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1484                 dr.screenUpdate(Update::Force | Update::FitCursor);
1485                 break;
1486
1487         case LFUN_CHANGE_PREVIOUS:
1488                 findPreviousChange(this);
1489                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1490                 dr.screenUpdate(Update::Force | Update::FitCursor);
1491                 break;
1492
1493         case LFUN_CHANGES_MERGE:
1494                 if (findNextChange(this) || findPreviousChange(this)) {
1495                         dr.screenUpdate(Update::Force | Update::FitCursor);
1496                         dr.forceBufferUpdate();
1497                         showDialog("changes");
1498                 }
1499                 break;
1500
1501         case LFUN_ALL_CHANGES_ACCEPT:
1502                 // select complete document
1503                 cur.reset();
1504                 cur.selHandle(true);
1505                 buffer_.text().cursorBottom(cur);
1506                 // accept everything in a single step to support atomic undo
1507                 buffer_.text().acceptOrRejectChanges(cur, Text::ACCEPT);
1508                 cur.resetAnchor();
1509                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1510                 dr.screenUpdate(Update::Force | Update::FitCursor);
1511                 dr.forceBufferUpdate();
1512                 break;
1513
1514         case LFUN_ALL_CHANGES_REJECT:
1515                 // select complete document
1516                 cur.reset();
1517                 cur.selHandle(true);
1518                 buffer_.text().cursorBottom(cur);
1519                 // reject everything in a single step to support atomic undo
1520                 // Note: reject does not work recursively; the user may have to repeat the operation
1521                 buffer_.text().acceptOrRejectChanges(cur, Text::REJECT);
1522                 cur.resetAnchor();
1523                 // FIXME: Move this LFUN to Buffer so that we don't have to do this:
1524                 dr.screenUpdate(Update::Force | Update::FitCursor);
1525                 dr.forceBufferUpdate();
1526                 break;
1527
1528         case LFUN_WORD_FIND_FORWARD:
1529         case LFUN_WORD_FIND_BACKWARD: {
1530                 // FIXME THREAD
1531                 // Would it maybe be better if this variable were view specific anyway?
1532                 static docstring last_search;
1533                 docstring searched_string;
1534
1535                 if (!cmd.argument().empty()) {
1536                         last_search = cmd.argument();
1537                         searched_string = cmd.argument();
1538                 } else {
1539                         searched_string = last_search;
1540                 }
1541
1542                 if (searched_string.empty())
1543                         break;
1544
1545                 bool const fw = act == LFUN_WORD_FIND_FORWARD;
1546                 docstring const data =
1547                         find2string(searched_string, true, false, fw);
1548                 bool found = lyxfind(this, FuncRequest(LFUN_WORD_FIND, data));
1549                 if (found)
1550                         dr.screenUpdate(Update::Force | Update::FitCursor);
1551                 break;
1552         }
1553
1554         case LFUN_WORD_FIND: {
1555                 FuncRequest req = cmd;
1556                 if (cmd.argument().empty() && !d->search_request_cache_.argument().empty())
1557                         req = d->search_request_cache_;
1558                 if (req.argument().empty()) {
1559                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "findreplace"));
1560                         break;
1561                 }
1562                 if (lyxfind(this, req))
1563                         dr.screenUpdate(Update::Force | Update::FitCursor);
1564
1565                 d->search_request_cache_ = req;
1566                 break;
1567         }
1568
1569         case LFUN_WORD_REPLACE: {
1570                 bool has_deleted = false;
1571                 if (cur.selection()) {
1572                         DocIterator beg = cur.selectionBegin();
1573                         DocIterator end = cur.selectionEnd();
1574                         if (beg.pit() == end.pit()) {
1575                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1576                                         if (!cur.inMathed() && cur.paragraph().isDeleted(p)) {
1577                                                 has_deleted = true;
1578                                                 break;
1579                                         }
1580                                 }
1581                         }
1582                 }
1583                 if (lyxreplace(this, cmd, has_deleted)) {
1584                         dr.forceBufferUpdate();
1585                         dr.screenUpdate(Update::Force | Update::FitCursor);
1586                 }
1587                 break;
1588         }
1589
1590         case LFUN_WORD_FINDADV: {
1591                 FindAndReplaceOptions opt;
1592                 istringstream iss(to_utf8(cmd.argument()));
1593                 iss >> opt;
1594                 if (findAdv(this, opt)) {
1595                         dr.screenUpdate(Update::Force | Update::FitCursor);
1596                         cur.dispatched();
1597                         dispatched = true;
1598                 } else {
1599                         cur.undispatched();
1600                         dispatched = false;
1601                 }
1602                 break;
1603         }
1604
1605         case LFUN_MARK_OFF:
1606                 cur.clearSelection();
1607                 dr.setMessage(from_utf8(N_("Mark off")));
1608                 break;
1609
1610         case LFUN_MARK_ON:
1611                 cur.clearSelection();
1612                 cur.setMark(true);
1613                 dr.setMessage(from_utf8(N_("Mark on")));
1614                 break;
1615
1616         case LFUN_MARK_TOGGLE:
1617                 cur.selection(false);
1618                 if (cur.mark()) {
1619                         cur.setMark(false);
1620                         dr.setMessage(from_utf8(N_("Mark removed")));
1621                 } else {
1622                         cur.setMark(true);
1623                         dr.setMessage(from_utf8(N_("Mark set")));
1624                 }
1625                 cur.resetAnchor();
1626                 break;
1627
1628         case LFUN_SCREEN_SHOW_CURSOR:
1629                 showCursor();
1630                 break;
1631
1632         case LFUN_SCREEN_RECENTER:
1633                 recenter();
1634                 break;
1635
1636         case LFUN_BIBTEX_DATABASE_ADD: {
1637                 Cursor tmpcur = cur;
1638                 findInset(tmpcur, BIBTEX_CODE, false);
1639                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1640                                                 BIBTEX_CODE);
1641                 if (inset) {
1642                         if (inset->addDatabase(cmd.argument())) {
1643                                 buffer_.invalidateBibfileCache();
1644                                 dr.forceBufferUpdate();
1645                         }
1646                 }
1647                 break;
1648         }
1649
1650         case LFUN_BIBTEX_DATABASE_DEL: {
1651                 Cursor tmpcur = cur;
1652                 findInset(tmpcur, BIBTEX_CODE, false);
1653                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1654                                                 BIBTEX_CODE);
1655                 if (inset) {
1656                         if (inset->delDatabase(cmd.argument())) {
1657                                 buffer_.invalidateBibfileCache();
1658                                 dr.forceBufferUpdate();
1659                         }
1660                 }
1661                 break;
1662         }
1663
1664         case LFUN_STATISTICS: {
1665                 DocIterator from, to;
1666                 if (cur.selection()) {
1667                         from = cur.selectionBegin();
1668                         to = cur.selectionEnd();
1669                 } else {
1670                         from = doc_iterator_begin(&buffer_);
1671                         to = doc_iterator_end(&buffer_);
1672                 }
1673                 buffer_.updateStatistics(from, to);
1674                 int const words = buffer_.wordCount();
1675                 int const chars = buffer_.charCount(false);
1676                 int const chars_blanks = buffer_.charCount(true);
1677                 docstring message;
1678                 if (cur.selection())
1679                         message = _("Statistics for the selection:");
1680                 else
1681                         message = _("Statistics for the document:");
1682                 message += "\n\n";
1683                 if (words != 1)
1684                         message += bformat(_("%1$d words"), words);
1685                 else
1686                         message += _("One word");
1687                 message += "\n";
1688                 if (chars_blanks != 1)
1689                         message += bformat(_("%1$d characters (including blanks)"),
1690                                           chars_blanks);
1691                 else
1692                         message += _("One character (including blanks)");
1693                 message += "\n";
1694                 if (chars != 1)
1695                         message += bformat(_("%1$d characters (excluding blanks)"),
1696                                           chars);
1697                 else
1698                         message += _("One character (excluding blanks)");
1699
1700                 Alert::information(_("Statistics"), message);
1701         }
1702                 break;
1703
1704         case LFUN_SCREEN_UP:
1705         case LFUN_SCREEN_DOWN: {
1706                 Point p = getPos(cur);
1707                 // This code has been commented out to enable to scroll down a
1708                 // document, even if there are large insets in it (see bug #5465).
1709                 /*if (p.y_ < 0 || p.y_ > height_) {
1710                         // The cursor is off-screen so recenter before proceeding.
1711                         showCursor();
1712                         p = getPos(cur);
1713                 }*/
1714                 int const scrolled = scroll(act == LFUN_SCREEN_UP
1715                         ? -height_ : height_);
1716                 if (act == LFUN_SCREEN_UP && scrolled > -height_)
1717                         p = Point(0, 0);
1718                 if (act == LFUN_SCREEN_DOWN && scrolled < height_)
1719                         p = Point(width_, height_);
1720                 bool const in_texted = cur.inTexted();
1721                 cur.setCursor(doc_iterator_begin(cur.buffer()));
1722                 cur.selHandle(false);
1723                 buffer_.changed(true);
1724                 updateHoveredInset();
1725
1726                 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_,
1727                         true, act == LFUN_SCREEN_UP);
1728                 //FIXME: what to do with cur.x_target()?
1729                 bool update = in_texted && cur.bv().checkDepm(cur, old);
1730                 cur.finishUndo();
1731
1732                 if (update || cur.mark())
1733                         dr.screenUpdate(Update::Force | Update::FitCursor);
1734                 if (update)
1735                         dr.forceBufferUpdate();
1736                 break;
1737         }
1738
1739         case LFUN_SCROLL: {
1740                 string const scroll_type = cmd.getArg(0);
1741                 int scroll_step = 0;
1742                 if (scroll_type == "line")
1743                         scroll_step = d->scrollbarParameters_.single_step;
1744                 else if (scroll_type == "page")
1745                         scroll_step = d->scrollbarParameters_.page_step;
1746                 else
1747                         return;
1748                 string const scroll_quantity = cmd.getArg(1);
1749                 if (scroll_quantity == "up")
1750                         scrollUp(scroll_step);
1751                 else if (scroll_quantity == "down")
1752                         scrollDown(scroll_step);
1753                 else {
1754                         int const scroll_value = convert<int>(scroll_quantity);
1755                         if (scroll_value)
1756                                 scroll(scroll_step * scroll_value);
1757                 }
1758                 buffer_.changed(true);
1759                 updateHoveredInset();
1760                 dr.forceBufferUpdate();
1761                 break;
1762         }
1763
1764         case LFUN_SCREEN_UP_SELECT: {
1765                 // FIXME: why is the algorithm different from LFUN_SCREEN_UP?
1766                 cur.selHandle(true);
1767                 if (isTopScreen()) {
1768                         lyx::dispatch(FuncRequest(LFUN_BUFFER_BEGIN_SELECT));
1769                         cur.finishUndo();
1770                         break;
1771                 }
1772                 int y = getPos(cur).y_;
1773                 int const ymin = y - height_ + defaultRowHeight();
1774                 while (y > ymin && cur.up())
1775                         y = getPos(cur).y_;
1776
1777                 cur.finishUndo();
1778                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1779                 break;
1780         }
1781
1782         case LFUN_SCREEN_DOWN_SELECT: {
1783                 // FIXME: why is the algorithm different from LFUN_SCREEN_DOWN?
1784                 cur.selHandle(true);
1785                 if (isBottomScreen()) {
1786                         lyx::dispatch(FuncRequest(LFUN_BUFFER_END_SELECT));
1787                         cur.finishUndo();
1788                         break;
1789                 }
1790                 int y = getPos(cur).y_;
1791                 int const ymax = y + height_ - defaultRowHeight();
1792                 while (y < ymax && cur.down())
1793                         y = getPos(cur).y_;
1794
1795                 cur.finishUndo();
1796                 dr.screenUpdate(Update::SinglePar | Update::FitCursor);
1797                 break;
1798         }
1799
1800
1801         case LFUN_INSET_SELECT_ALL: {
1802                 // true if all cells are selected
1803                 bool const all_selected = cur.depth() > 1
1804                     && cur.selBegin().at_begin()
1805                     && cur.selEnd().at_end();
1806                 // true if some cells are selected
1807                 bool const cells_selected = cur.depth() > 1
1808                     && cur.selBegin().at_cell_begin()
1809                         && cur.selEnd().at_cell_end();
1810                 if (all_selected || (cells_selected && !cur.inset().isTable())) {
1811                         // All the contents of the inset if selected, or only at
1812                         // least one cell but inset is not a table.
1813                         // Select the inset from outside.
1814                         cur.pop();
1815                         cur.resetAnchor();
1816                         cur.selection(true);
1817                         cur.posForward();
1818                 } else if (cells_selected) {
1819                         // At least one complete cell is selected and inset is a table.
1820                         // Select all cells
1821                         cur.idx() = 0;
1822                         cur.pos() = 0;
1823                         cur.resetAnchor();
1824                         cur.selection(true);
1825                         cur.idx() = cur.lastidx();
1826                         cur.pos() = cur.lastpos();
1827                 } else {
1828                         // select current cell
1829                         cur.pit() = 0;
1830                         cur.pos() = 0;
1831                         cur.resetAnchor();
1832                         cur.selection(true);
1833                         cur.pit() = cur.lastpit();
1834                         cur.pos() = cur.lastpos();
1835                 }
1836                 cur.setCurrentFont();
1837                 dr.screenUpdate(Update::Force);
1838                 break;
1839         }
1840
1841
1842         // This would be in Buffer class if only Cursor did not
1843         // require a bufferview
1844         case LFUN_INSET_FORALL: {
1845                 docstring const name = from_utf8(cmd.getArg(0));
1846                 string const commandstr = cmd.getLongArg(1);
1847                 FuncRequest const fr = lyxaction.lookupFunc(commandstr);
1848
1849                 // an arbitrary number to limit number of iterations
1850                 const int max_iter = 100000;
1851                 int iterations = 0;
1852                 Cursor & cur = d->cursor_;
1853                 Cursor const savecur = cur;
1854                 cur.reset();
1855                 if (!cur.nextInset())
1856                         cur.forwardInset();
1857                 cur.beginUndoGroup();
1858                 while(cur && iterations < max_iter) {
1859                         Inset * const ins = cur.nextInset();
1860                         if (!ins)
1861                                 break;
1862                         docstring insname = ins->layoutName();
1863                         while (!insname.empty()) {
1864                                 if (insname == name || name == from_utf8("*")) {
1865                                         cur.recordUndo();
1866                                         lyx::dispatch(fr, dr);
1867                                         ++iterations;
1868                                         break;
1869                                 }
1870                                 size_t const i = insname.rfind(':');
1871                                 if (i == string::npos)
1872                                         break;
1873                                 insname = insname.substr(0, i);
1874                         }
1875                         // if we did not delete the inset, skip it
1876                         if (!cur.nextInset() || cur.nextInset() == ins)
1877                                 cur.forwardInset();
1878                 }
1879                 cur = savecur;
1880                 cur.fixIfBroken();
1881                 /** This is a dummy undo record only to remember the cursor
1882                  * that has just been set; this will be used on a redo action
1883                  * (see ticket #10097)
1884
1885                  * FIXME: a better fix would be to have a way to set the
1886                  * cursor value directly, but I am not sure it is worth it.
1887                  */
1888                 cur.recordUndo();
1889                 cur.endUndoGroup();
1890                 dr.screenUpdate(Update::Force);
1891                 dr.forceBufferUpdate();
1892
1893                 if (iterations >= max_iter) {
1894                         dr.setError(true);
1895                         dr.setMessage(bformat(_("`inset-forall' interrupted because number of actions is larger than %1$d"), max_iter));
1896                 } else
1897                         dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d insets"), from_utf8(commandstr), iterations));
1898                 break;
1899         }
1900
1901
1902         case LFUN_BRANCH_ADD_INSERT: {
1903                 docstring branch_name = from_utf8(cmd.getArg(0));
1904                 if (branch_name.empty())
1905                         if (!Alert::askForText(branch_name, _("Branch name")) ||
1906                                                 branch_name.empty())
1907                                 break;
1908
1909                 DispatchResult drtmp;
1910                 buffer_.dispatch(FuncRequest(LFUN_BRANCH_ADD, branch_name), drtmp);
1911                 if (drtmp.error()) {
1912                         Alert::warning(_("Branch already exists"), drtmp.message());
1913                         break;
1914                 }
1915                 BranchList & branch_list = buffer_.params().branchlist();
1916                 vector<docstring> const branches =
1917                         getVectorFromString(branch_name, branch_list.separator());
1918                 for (vector<docstring>::const_iterator it = branches.begin();
1919                      it != branches.end(); ++it) {
1920                         branch_name = *it;
1921                         lyx::dispatch(FuncRequest(LFUN_BRANCH_INSERT, branch_name));
1922                 }
1923                 break;
1924         }
1925
1926         case LFUN_KEYMAP_OFF:
1927                 getIntl().keyMapOn(false);
1928                 break;
1929
1930         case LFUN_KEYMAP_PRIMARY:
1931                 getIntl().keyMapPrim();
1932                 break;
1933
1934         case LFUN_KEYMAP_SECONDARY:
1935                 getIntl().keyMapSec();
1936                 break;
1937
1938         case LFUN_KEYMAP_TOGGLE:
1939                 getIntl().toggleKeyMap();
1940                 break;
1941
1942         case LFUN_DIALOG_SHOW_NEW_INSET: {
1943                 string const name = cmd.getArg(0);
1944                 string data = trim(to_utf8(cmd.argument()).substr(name.size()));
1945                 if (decodeInsetParam(name, data, buffer_))
1946                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, name + " " + data));
1947                 else
1948                         lyxerr << "Inset type '" << name <<
1949                         "' not recognized in LFUN_DIALOG_SHOW_NEW_INSET" <<  endl;
1950                 break;
1951         }
1952
1953         case LFUN_CITATION_INSERT: {
1954                 if (argument.empty()) {
1955                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW_NEW_INSET, "citation"));
1956                         break;
1957                 }
1958                 // we can have one optional argument, delimited by '|'
1959                 // citation-insert <key>|<text_before>
1960                 // this should be enhanced to also support text_after
1961                 // and citation style
1962                 string arg = argument;
1963                 string opt1;
1964                 if (contains(argument, "|")) {
1965                         arg = token(argument, '|', 0);
1966                         opt1 = token(argument, '|', 1);
1967                 }
1968
1969                 // if our cursor is directly in front of or behind a citation inset,
1970                 // we will instead add the new key to it.
1971                 Inset * inset = cur.nextInset();
1972                 if (!inset || inset->lyxCode() != CITE_CODE)
1973                         inset = cur.prevInset();
1974                 if (inset && inset->lyxCode() == CITE_CODE) {
1975                         InsetCitation * icite = static_cast<InsetCitation *>(inset);
1976                         if (icite->addKey(arg)) {
1977                                 dr.forceBufferUpdate();
1978                                 dr.screenUpdate(Update::FitCursor | Update::SinglePar);
1979                                 if (!opt1.empty())
1980                                         LYXERR0("Discarding optional argument to citation-insert.");
1981                         }
1982                         dispatched = true;
1983                         break;
1984                 }
1985                 InsetCommandParams icp(CITE_CODE);
1986                 icp["key"] = from_utf8(arg);
1987                 if (!opt1.empty())
1988                         icp["before"] = from_utf8(opt1);
1989                 string icstr = InsetCommand::params2string(icp);
1990                 FuncRequest fr(LFUN_INSET_INSERT, icstr);
1991                 lyx::dispatch(fr);
1992                 break;
1993         }
1994
1995         case LFUN_INSET_APPLY: {
1996                 string const name = cmd.getArg(0);
1997                 Inset * inset = editedInset(name);
1998                 if (!inset) {
1999                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2000                         lyx::dispatch(fr);
2001                         break;
2002                 }
2003                 // put cursor in front of inset.
2004                 if (!setCursorFromInset(inset)) {
2005                         LASSERT(false, break);
2006                 }
2007                 cur.recordUndo();
2008                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2009                 inset->dispatch(cur, fr);
2010                 dr.screenUpdate(cur.result().screenUpdate());
2011                 if (cur.result().needBufferUpdate())
2012                         dr.forceBufferUpdate();
2013                 break;
2014         }
2015
2016         // FIXME:
2017         // The change of language of buffer belongs to the Buffer class.
2018         // We have to do it here because we need a cursor for Undo.
2019         // When Undo::recordUndoBufferParams() is implemented someday
2020         // LFUN_BUFFER_LANGUAGE should be handled by the Buffer class.
2021         case LFUN_BUFFER_LANGUAGE: {
2022                 Language const * oldL = buffer_.params().language;
2023                 Language const * newL = languages.getLanguage(argument);
2024                 if (!newL || oldL == newL)
2025                         break;
2026                 if (oldL->rightToLeft() == newL->rightToLeft()) {
2027                         cur.recordUndoFullBuffer();
2028                         buffer_.changeLanguage(oldL, newL);
2029                         cur.setCurrentFont();
2030                         dr.forceBufferUpdate();
2031                 }
2032                 break;
2033         }
2034
2035         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2036         case LFUN_FILE_INSERT_PLAINTEXT: {
2037                 bool const as_paragraph = (act == LFUN_FILE_INSERT_PLAINTEXT_PARA);
2038                 string const fname = to_utf8(cmd.argument());
2039                 if (!FileName::isAbsolute(fname))
2040                         dr.setMessage(_("Absolute filename expected."));
2041                 else
2042                         insertPlaintextFile(FileName(fname), as_paragraph);
2043                 break;
2044         }
2045
2046         default:
2047                 // OK, so try the Buffer itself...
2048                 buffer_.dispatch(cmd, dr);
2049                 dispatched = dr.dispatched();
2050                 break;
2051         }
2052
2053         buffer_.undo().endUndoGroup();
2054         dr.dispatched(dispatched);
2055
2056         // NOTE: The code below is copied from Cursor::dispatch. If you
2057         // need to modify this, please update the other one too.
2058
2059         // notify insets we just entered/left
2060         if (cursor() != old) {
2061                 old.beginUndoGroup();
2062                 old.fixIfBroken();
2063                 bool badcursor = notifyCursorLeavesOrEnters(old, cursor());
2064                 if (badcursor) {
2065                         cursor().fixIfBroken();
2066                         resetInlineCompletionPos();
2067                 }
2068                 old.endUndoGroup();
2069         }
2070 }
2071
2072
2073 docstring const BufferView::requestSelection()
2074 {
2075         Cursor & cur = d->cursor_;
2076
2077         LYXERR(Debug::SELECTION, "requestSelection: cur.selection: " << cur.selection());
2078         if (!cur.selection()) {
2079                 d->xsel_cache_.set = false;
2080                 return docstring();
2081         }
2082
2083         LYXERR(Debug::SELECTION, "requestSelection: xsel_cache.set: " << d->xsel_cache_.set);
2084         if (!d->xsel_cache_.set ||
2085             cur.top() != d->xsel_cache_.cursor ||
2086             cur.realAnchor().top() != d->xsel_cache_.anchor)
2087         {
2088                 d->xsel_cache_.cursor = cur.top();
2089                 d->xsel_cache_.anchor = cur.realAnchor().top();
2090                 d->xsel_cache_.set = cur.selection();
2091                 return cur.selectionAsString(false);
2092         }
2093         return docstring();
2094 }
2095
2096
2097 void BufferView::clearSelection()
2098 {
2099         d->cursor_.clearSelection();
2100         // Clear the selection buffer. Otherwise a subsequent
2101         // middle-mouse-button paste would use the selection buffer,
2102         // not the more current external selection.
2103         cap::clearSelection();
2104         d->xsel_cache_.set = false;
2105         // The buffer did not really change, but this causes the
2106         // redraw we need because we cleared the selection above.
2107         buffer_.changed(false);
2108 }
2109
2110
2111 void BufferView::resize(int width, int height)
2112 {
2113         // Update from work area
2114         width_ = width;
2115         height_ = height;
2116
2117         // Clear the paragraph height cache.
2118         d->par_height_.clear();
2119         // Redo the metrics.
2120         updateMetrics();
2121 }
2122
2123
2124 Inset const * BufferView::getCoveringInset(Text const & text,
2125                 int x, int y) const
2126 {
2127         TextMetrics & tm = d->text_metrics_[&text];
2128         Inset * inset = tm.checkInsetHit(x, y);
2129         if (!inset)
2130                 return 0;
2131
2132         if (!inset->descendable(*this))
2133                 // No need to go further down if the inset is not
2134                 // descendable.
2135                 return inset;
2136
2137         size_t cell_number = inset->nargs();
2138         // Check all the inner cell.
2139         for (size_t i = 0; i != cell_number; ++i) {
2140                 Text const * inner_text = inset->getText(i);
2141                 if (inner_text) {
2142                         // Try deeper.
2143                         Inset const * inset_deeper =
2144                                 getCoveringInset(*inner_text, x, y);
2145                         if (inset_deeper)
2146                                 return inset_deeper;
2147                 }
2148         }
2149
2150         return inset;
2151 }
2152
2153
2154 void BufferView::updateHoveredInset() const
2155 {
2156         // Get inset under mouse, if there is one.
2157         int const x = d->mouse_position_cache_.x_;
2158         int const y = d->mouse_position_cache_.y_;
2159         Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
2160
2161         d->clickable_inset_ = covering_inset && covering_inset->clickable(*this, x, y);
2162
2163         if (covering_inset == d->last_inset_)
2164                 // Same inset, no need to do anything...
2165                 return;
2166
2167         bool need_redraw = false;
2168         if (d->last_inset_) {
2169                 // Remove the hint on the last hovered inset (if any).
2170                 need_redraw |= d->last_inset_->setMouseHover(this, false);
2171                 d->last_inset_ = 0;
2172         }
2173
2174         if (covering_inset && covering_inset->setMouseHover(this, true)) {
2175                 need_redraw = true;
2176                 // Only the insets that accept the hover state, do
2177                 // clear the last_inset_, so only set the last_inset_
2178                 // member if the hovered setting is accepted.
2179                 d->last_inset_ = covering_inset;
2180         }
2181
2182         if (need_redraw) {
2183                 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
2184                                 << d->mouse_position_cache_.x_ << ", "
2185                                 << d->mouse_position_cache_.y_ << ")");
2186
2187                 d->update_strategy_ = DecorationUpdate;
2188
2189                 // This event (moving without mouse click) is not passed further.
2190                 // This should be changed if it is further utilized.
2191                 buffer_.changed(false);
2192         }
2193 }
2194
2195
2196 void BufferView::clearLastInset(Inset * inset) const
2197 {
2198         if (d->last_inset_ != inset) {
2199                 LYXERR0("Wrong last_inset!");
2200                 LATTEST(false);
2201         }
2202         d->last_inset_ = 0;
2203 }
2204
2205
2206 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
2207 {
2208         //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
2209
2210         // This is only called for mouse related events including
2211         // LFUN_FILE_OPEN generated by drag-and-drop.
2212         FuncRequest cmd = cmd0;
2213
2214         Cursor old = cursor();
2215         Cursor cur(*this);
2216         cur.push(buffer_.inset());
2217         cur.selection(d->cursor_.selection());
2218
2219         // Either the inset under the cursor or the
2220         // surrounding Text will handle this event.
2221
2222         // make sure we stay within the screen...
2223         cmd.set_y(min(max(cmd.y(), -1), height_));
2224
2225         d->mouse_position_cache_.x_ = cmd.x();
2226         d->mouse_position_cache_.y_ = cmd.y();
2227
2228         if (cmd.action() == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
2229                 updateHoveredInset();
2230                 return;
2231         }
2232
2233         // Build temporary cursor.
2234         Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x(), cmd.y());
2235         if (inset) {
2236                 // If inset is not editable, cur.pos() might point behind the
2237                 // inset (depending on cmd.x(), cmd.y()). This is needed for
2238                 // editing to fix bug 9628, but e.g. the context menu needs a
2239                 // cursor in front of the inset.
2240                 if ((inset->hasSettings() || !inset->contextMenuName().empty()
2241                      || inset->lyxCode() == SEPARATOR_CODE) &&
2242                     cur.nextInset() != inset && cur.prevInset() == inset)
2243                         cur.posBackward();
2244         } else if (cur.inTexted() && cur.pos()
2245                         && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
2246                 // Always place cursor in front of a separator inset.
2247                 cur.posBackward();
2248         }
2249
2250         // Put anchor at the same position.
2251         cur.resetAnchor();
2252
2253         cur.beginUndoGroup();
2254
2255         // Try to dispatch to an non-editable inset near this position
2256         // via the temp cursor. If the inset wishes to change the real
2257         // cursor it has to do so explicitly by using
2258         //  cur.bv().cursor() = cur;  (or similar)
2259         if (inset)
2260                 inset->dispatch(cur, cmd);
2261
2262         // Now dispatch to the temporary cursor. If the real cursor should
2263         // be modified, the inset's dispatch has to do so explicitly.
2264         if (!inset || !cur.result().dispatched())
2265                 cur.dispatch(cmd);
2266
2267         // Notify left insets
2268         if (cur != old) {
2269                 bool badcursor = old.fixIfBroken() | cur.fixIfBroken();
2270                 badcursor |= notifyCursorLeavesOrEnters(old, cur);
2271                 if (badcursor)
2272                         cursor().fixIfBroken();
2273         }
2274
2275         cur.endUndoGroup();
2276
2277         // Do we have a selection?
2278         theSelection().haveSelection(cursor().selection());
2279
2280         if (cur.needBufferUpdate()) {
2281                 cur.clearBufferUpdate();
2282                 buffer().updateBuffer();
2283         }
2284
2285         // If the command has been dispatched,
2286         if (cur.result().dispatched() || cur.result().screenUpdate())
2287                 processUpdateFlags(cur.result().screenUpdate());
2288 }
2289
2290
2291 int BufferView::minVisiblePart()
2292 {
2293         return 2 * defaultRowHeight();
2294 }
2295
2296
2297 int BufferView::scroll(int y)
2298 {
2299         if (y > 0)
2300                 return scrollDown(y);
2301         if (y < 0)
2302                 return scrollUp(-y);
2303         return 0;
2304 }
2305
2306
2307 int BufferView::scrollDown(int offset)
2308 {
2309         Text * text = &buffer_.text();
2310         TextMetrics & tm = d->text_metrics_[text];
2311         int const ymax = height_ + offset;
2312         while (true) {
2313                 pair<pit_type, ParagraphMetrics const *> last = tm.last();
2314                 int bottom_pos = last.second->position() + last.second->descent();
2315                 if (lyxrc.scroll_below_document)
2316                         bottom_pos += height_ - minVisiblePart();
2317                 if (last.first + 1 == int(text->paragraphs().size())) {
2318                         if (bottom_pos <= height_)
2319                                 return 0;
2320                         offset = min(offset, bottom_pos - height_);
2321                         break;
2322                 }
2323                 if (bottom_pos > ymax)
2324                         break;
2325                 tm.newParMetricsDown();
2326         }
2327         d->anchor_ypos_ -= offset;
2328         return -offset;
2329 }
2330
2331
2332 int BufferView::scrollUp(int offset)
2333 {
2334         Text * text = &buffer_.text();
2335         TextMetrics & tm = d->text_metrics_[text];
2336         int ymin = - offset;
2337         while (true) {
2338                 pair<pit_type, ParagraphMetrics const *> first = tm.first();
2339                 int top_pos = first.second->position() - first.second->ascent();
2340                 if (first.first == 0) {
2341                         if (top_pos >= 0)
2342                                 return 0;
2343                         offset = min(offset, - top_pos);
2344                         break;
2345                 }
2346                 if (top_pos < ymin)
2347                         break;
2348                 tm.newParMetricsUp();
2349         }
2350         d->anchor_ypos_ += offset;
2351         return offset;
2352 }
2353
2354
2355 bool BufferView::setCursorFromRow(int row)
2356 {
2357         TexRow::TextEntry start, end;
2358         tie(start,end) = buffer_.texrow().getEntriesFromRow(row);
2359         LYXERR(Debug::LATEX,
2360                "setCursorFromRow: for row " << row << ", TexRow has found "
2361                "start (id=" << start.id << ",pos=" << start.pos << "), "
2362                "end (id=" << end.id << ",pos=" << end.pos << ")");
2363         return setCursorFromEntries(start, end);
2364 }
2365
2366
2367 bool BufferView::setCursorFromEntries(TexRow::TextEntry start,
2368                                       TexRow::TextEntry end)
2369 {
2370         DocIterator dit_start, dit_end;
2371         tie(dit_start,dit_end) =
2372                 TexRow::getDocIteratorsFromEntries(start, end, buffer_);
2373         if (!dit_start)
2374                 return false;
2375         // Setting selection start
2376         d->cursor_.clearSelection();
2377         setCursor(dit_start);
2378         // Setting selection end
2379         if (dit_end) {
2380                 d->cursor_.resetAnchor();
2381                 setCursorSelectionTo(dit_end);
2382         }
2383         return true;
2384 }
2385
2386
2387 bool BufferView::setCursorFromInset(Inset const * inset)
2388 {
2389         // are we already there?
2390         if (cursor().nextInset() == inset)
2391                 return true;
2392
2393         // Inset is not at cursor position. Find it in the document.
2394         Cursor cur(*this);
2395         cur.reset();
2396         while (cur && cur.nextInset() != inset)
2397                 cur.forwardInset();
2398
2399         if (cur) {
2400                 setCursor(cur);
2401                 return true;
2402         }
2403         return false;
2404 }
2405
2406
2407 void BufferView::gotoLabel(docstring const & label)
2408 {
2409         ListOfBuffers bufs = buffer().allRelatives();
2410         ListOfBuffers::iterator it = bufs.begin();
2411         for (; it != bufs.end(); ++it) {
2412                 Buffer const * buf = *it;
2413
2414                 // find label
2415                 shared_ptr<Toc> toc = buf->tocBackend().toc("label");
2416                 Toc::const_iterator toc_it = toc->begin();
2417                 Toc::const_iterator end = toc->end();
2418                 for (; toc_it != end; ++toc_it) {
2419                         if (label == toc_it->str()) {
2420                                 lyx::dispatch(toc_it->action());
2421                                 return;
2422                         }
2423                 }
2424         }
2425 }
2426
2427
2428 TextMetrics const & BufferView::textMetrics(Text const * t) const
2429 {
2430         return const_cast<BufferView *>(this)->textMetrics(t);
2431 }
2432
2433
2434 TextMetrics & BufferView::textMetrics(Text const * t)
2435 {
2436         LBUFERR(t);
2437         TextMetricsCache::iterator tmc_it  = d->text_metrics_.find(t);
2438         if (tmc_it == d->text_metrics_.end()) {
2439                 tmc_it = d->text_metrics_.insert(
2440                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
2441         }
2442         return tmc_it->second;
2443 }
2444
2445
2446 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
2447                 pit_type pit) const
2448 {
2449         return textMetrics(t).parMetrics(pit);
2450 }
2451
2452
2453 int BufferView::workHeight() const
2454 {
2455         return height_;
2456 }
2457
2458
2459 void BufferView::setCursor(DocIterator const & dit)
2460 {
2461         d->cursor_.reset();
2462         size_t const n = dit.depth();
2463         for (size_t i = 0; i < n; ++i)
2464                 dit[i].inset().edit(d->cursor_, true);
2465
2466         d->cursor_.setCursor(dit);
2467         d->cursor_.selection(false);
2468         d->cursor_.setCurrentFont();
2469         // FIXME
2470         // It seems on general grounds as if this is probably needed, but
2471         // it is not yet clear.
2472         // See bug #7394 and r38388.
2473         // d->cursor.resetAnchor();
2474 }
2475
2476
2477 void BufferView::setCursorSelectionTo(DocIterator const & dit)
2478 {
2479         size_t const n = dit.depth();
2480         for (size_t i = 0; i < n; ++i)
2481                 dit[i].inset().edit(d->cursor_, true);
2482
2483         d->cursor_.selection(true);
2484         d->cursor_.setCursorSelectionTo(dit);
2485         d->cursor_.setCurrentFont();
2486 }
2487
2488
2489 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
2490 {
2491         // Would be wrong to delete anything if we have a selection.
2492         if (cur.selection())
2493                 return false;
2494
2495         bool need_anchor_change = false;
2496         bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
2497                 need_anchor_change);
2498
2499         if (need_anchor_change)
2500                 cur.resetAnchor();
2501
2502         if (!changed)
2503                 return false;
2504
2505         d->cursor_ = cur;
2506
2507         // we would rather not do this here, but it needs to be done before
2508         // the changed() signal is sent.
2509         buffer_.updateBuffer();
2510
2511         buffer_.changed(true);
2512         return true;
2513 }
2514
2515
2516 bool BufferView::mouseSetCursor(Cursor & cur, bool const select)
2517 {
2518         LASSERT(&cur.bv() == this, return false);
2519
2520         if (!select)
2521                 // this event will clear selection so we save selection for
2522                 // persistent selection
2523                 cap::saveSelection(cursor());
2524
2525         d->cursor_.macroModeClose();
2526         // If a macro has been finalized, the cursor might have been broken
2527         cur.fixIfBroken();
2528
2529         // Has the cursor just left the inset?
2530         bool const leftinset = (&d->cursor_.inset() != &cur.inset());
2531         if (leftinset)
2532                 d->cursor_.fixIfBroken();
2533
2534         // do the dEPM magic if needed
2535         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
2536         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
2537         // the leftinset bool would not be necessary (badcursor instead).
2538         bool update = leftinset;
2539
2540         if (select) {
2541                 d->cursor_.setSelection();
2542                 d->cursor_.setCursorSelectionTo(cur);
2543         } else {
2544                 if (d->cursor_.inTexted())
2545                         update |= checkDepm(cur, d->cursor_);
2546                 d->cursor_.resetAnchor();
2547                 d->cursor_.setCursor(cur);
2548                 d->cursor_.clearSelection();
2549         }
2550         d->cursor_.boundary(cur.boundary());
2551         d->cursor_.finishUndo();
2552         d->cursor_.setCurrentFont();
2553         if (update)
2554                 cur.forceBufferUpdate();
2555         return update;
2556 }
2557
2558
2559 void BufferView::putSelectionAt(DocIterator const & cur,
2560                                 int length, bool backwards)
2561 {
2562         d->cursor_.clearSelection();
2563
2564         setCursor(cur);
2565
2566         if (length) {
2567                 if (backwards) {
2568                         d->cursor_.pos() += length;
2569                         d->cursor_.setSelection(d->cursor_, -length);
2570                 } else
2571                         d->cursor_.setSelection(d->cursor_, length);
2572         }
2573 }
2574
2575
2576 bool BufferView::selectIfEmpty(DocIterator & cur)
2577 {
2578         if ((cur.inTexted() && !cur.paragraph().empty())
2579             || (cur.inMathed() && !cur.cell().empty()))
2580                 return false;
2581
2582         pit_type const beg_pit = cur.pit();
2583         if (beg_pit > 0) {
2584                 // The paragraph associated to this item isn't
2585                 // the first one, so it can be selected
2586                 cur.backwardPos();
2587         } else {
2588                 // We have to resort to select the space between the
2589                 // end of this item and the begin of the next one
2590                 cur.forwardPos();
2591         }
2592         if (cur.empty()) {
2593                 // If it is the only item in the document,
2594                 // nothing can be selected
2595                 return false;
2596         }
2597         pit_type const end_pit = cur.pit();
2598         pos_type const end_pos = cur.pos();
2599         d->cursor_.clearSelection();
2600         d->cursor_.reset();
2601         d->cursor_.setCursor(cur);
2602         d->cursor_.pit() = beg_pit;
2603         d->cursor_.pos() = 0;
2604         d->cursor_.selection(false);
2605         d->cursor_.resetAnchor();
2606         d->cursor_.pit() = end_pit;
2607         d->cursor_.pos() = end_pos;
2608         d->cursor_.setSelection();
2609         return true;
2610 }
2611
2612
2613 Cursor & BufferView::cursor()
2614 {
2615         return d->cursor_;
2616 }
2617
2618
2619 Cursor const & BufferView::cursor() const
2620 {
2621         return d->cursor_;
2622 }
2623
2624
2625 pit_type BufferView::anchor_ref() const
2626 {
2627         return d->anchor_pit_;
2628 }
2629
2630
2631 bool BufferView::singleParUpdate()
2632 {
2633         Text & buftext = buffer_.text();
2634         pit_type const bottom_pit = d->cursor_.bottom().pit();
2635         TextMetrics & tm = textMetrics(&buftext);
2636         int old_height = tm.parMetrics(bottom_pit).height();
2637
2638         // make sure inline completion pointer is ok
2639         if (d->inlineCompletionPos_.fixIfBroken())
2640                 d->inlineCompletionPos_ = DocIterator();
2641
2642         // In Single Paragraph mode, rebreak only
2643         // the (main text, not inset!) paragraph containing the cursor.
2644         // (if this paragraph contains insets etc., rebreaking will
2645         // recursively descend)
2646         tm.redoParagraph(bottom_pit);
2647         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
2648         if (pm.height() != old_height)
2649                 // Paragraph height has changed so we cannot proceed to
2650                 // the singlePar optimisation.
2651                 return false;
2652
2653         tm.updatePosCache(bottom_pit);
2654         d->update_strategy_ = SingleParUpdate;
2655
2656         LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
2657                 << " y2: " << pm.position() + pm.descent()
2658                 << " pit: " << bottom_pit
2659                 << " singlepar: 1");
2660         return true;
2661 }
2662
2663
2664 void BufferView::updateMetrics()
2665 {
2666         if (height_ == 0 || width_ == 0)
2667                 return;
2668
2669         Text & buftext = buffer_.text();
2670         pit_type const npit = int(buftext.paragraphs().size());
2671
2672         // Clear out the position cache in case of full screen redraw,
2673         d->coord_cache_.clear();
2674
2675         // Clear out paragraph metrics to avoid having invalid metrics
2676         // in the cache from paragraphs not relayouted below
2677         // The complete text metrics will be redone.
2678         d->text_metrics_.clear();
2679
2680         TextMetrics & tm = textMetrics(&buftext);
2681
2682         // make sure inline completion pointer is ok
2683         if (d->inlineCompletionPos_.fixIfBroken())
2684                 d->inlineCompletionPos_ = DocIterator();
2685
2686         if (d->anchor_pit_ >= npit)
2687                 // The anchor pit must have been deleted...
2688                 d->anchor_pit_ = npit - 1;
2689
2690         // Rebreak anchor paragraph.
2691         tm.redoParagraph(d->anchor_pit_);
2692         ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
2693
2694         // position anchor
2695         if (d->anchor_pit_ == 0) {
2696                 int scrollRange = d->scrollbarParameters_.max - d->scrollbarParameters_.min;
2697
2698                 // Complete buffer visible? Then it's easy.
2699                 if (scrollRange == 0)
2700                         d->anchor_ypos_ = anchor_pm.ascent();
2701                 else {
2702                         // avoid empty space above the first row
2703                         d->anchor_ypos_ = min(d->anchor_ypos_, anchor_pm.ascent());
2704                 }
2705         }
2706         anchor_pm.setPosition(d->anchor_ypos_);
2707         tm.updatePosCache(d->anchor_pit_);
2708
2709         LYXERR(Debug::PAINTING, "metrics: "
2710                 << " anchor pit = " << d->anchor_pit_
2711                 << " anchor ypos = " << d->anchor_ypos_);
2712
2713         // Redo paragraphs above anchor if necessary.
2714         int y1 = d->anchor_ypos_ - anchor_pm.ascent();
2715         // We are now just above the anchor paragraph.
2716         pit_type pit1 = d->anchor_pit_ - 1;
2717         for (; pit1 >= 0 && y1 >= 0; --pit1) {
2718                 tm.redoParagraph(pit1);
2719                 ParagraphMetrics & pm = tm.par_metrics_[pit1];
2720                 y1 -= pm.descent();
2721                 // Save the paragraph position in the cache.
2722                 pm.setPosition(y1);
2723                 tm.updatePosCache(pit1);
2724                 y1 -= pm.ascent();
2725         }
2726
2727         // Redo paragraphs below the anchor if necessary.
2728         int y2 = d->anchor_ypos_ + anchor_pm.descent();
2729         // We are now just below the anchor paragraph.
2730         pit_type pit2 = d->anchor_pit_ + 1;
2731         for (; pit2 < npit && y2 <= height_; ++pit2) {
2732                 tm.redoParagraph(pit2);
2733                 ParagraphMetrics & pm = tm.par_metrics_[pit2];
2734                 y2 += pm.ascent();
2735                 // Save the paragraph position in the cache.
2736                 pm.setPosition(y2);
2737                 tm.updatePosCache(pit2);
2738                 y2 += pm.descent();
2739         }
2740
2741         LYXERR(Debug::PAINTING, "Metrics: "
2742                 << " anchor pit = " << d->anchor_pit_
2743                 << " anchor ypos = " << d->anchor_ypos_
2744                 << " y1 = " << y1
2745                 << " y2 = " << y2
2746                 << " pit1 = " << pit1
2747                 << " pit2 = " << pit2);
2748
2749         // It is not necessary anymore to compute metrics, but a redraw is needed
2750         d->update_flags_ = (d->update_flags_ & ~Update::Force) | Update::ForceDraw;
2751
2752         // Now update the positions of insets in the cache.
2753         updatePosCache();
2754
2755         if (lyxerr.debugging(Debug::WORKAREA)) {
2756                 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
2757                 d->coord_cache_.dump();
2758         }
2759 }
2760
2761
2762 void BufferView::updatePosCache()
2763 {
2764         // this is the "nodraw" drawing stage: only set the positions of the
2765         // insets in metrics cache.
2766         frontend::NullPainter np;
2767         draw(np, false);
2768 }
2769
2770
2771 void BufferView::insertLyXFile(FileName const & fname)
2772 {
2773         LASSERT(d->cursor_.inTexted(), return);
2774
2775         // Get absolute path of file and add ".lyx"
2776         // to the filename if necessary
2777         FileName filename = fileSearch(string(), fname.absFileName(), "lyx");
2778
2779         docstring const disp_fn = makeDisplayPath(filename.absFileName());
2780         // emit message signal.
2781         message(bformat(_("Inserting document %1$s..."), disp_fn));
2782
2783         docstring res;
2784         Buffer buf(filename.absFileName(), false);
2785         if (buf.loadLyXFile() == Buffer::ReadSuccess) {
2786                 ErrorList & el = buffer_.errorList("Parse");
2787                 // Copy the inserted document error list into the current buffer one.
2788                 el = buf.errorList("Parse");
2789                 buffer_.undo().recordUndo(d->cursor_);
2790                 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
2791                                              buf.params().documentClassPtr(), el);
2792                 res = _("Document %1$s inserted.");
2793         } else {
2794                 res = _("Could not insert document %1$s");
2795         }
2796
2797         buffer_.changed(true);
2798         // emit message signal.
2799         message(bformat(res, disp_fn));
2800 }
2801
2802
2803 Point BufferView::coordOffset(DocIterator const & dit) const
2804 {
2805         int x = 0;
2806         int y = 0;
2807         int lastw = 0;
2808
2809         // Addup contribution of nested insets, from inside to outside,
2810         // keeping the outer paragraph for a special handling below
2811         for (size_t i = dit.depth() - 1; i >= 1; --i) {
2812                 CursorSlice const & sl = dit[i];
2813                 int xx = 0;
2814                 int yy = 0;
2815
2816                 // get relative position inside sl.inset()
2817                 sl.inset().cursorPos(*this, sl, dit.boundary() && (i + 1 == dit.depth()), xx, yy);
2818
2819                 // Make relative position inside of the edited inset relative to sl.inset()
2820                 x += xx;
2821                 y += yy;
2822
2823                 // In case of an RTL inset, the edited inset will be positioned to the left
2824                 // of xx:yy
2825                 if (sl.text()) {
2826                         bool boundary_i = dit.boundary() && i + 1 == dit.depth();
2827                         bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
2828                         if (rtl)
2829                                 x -= lastw;
2830                 }
2831
2832                 // remember width for the case that sl.inset() is positioned in an RTL inset
2833                 lastw = sl.inset().dimension(*this).wid;
2834
2835                 //lyxerr << "Cursor::getPos, i: "
2836                 // << i << " x: " << xx << " y: " << y << endl;
2837         }
2838
2839         // Add contribution of initial rows of outermost paragraph
2840         CursorSlice const & sl = dit[0];
2841         TextMetrics const & tm = textMetrics(sl.text());
2842         ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
2843
2844         LBUFERR(!pm.rows().empty());
2845         y -= pm.rows()[0].ascent();
2846 #if 1
2847         // FIXME: document this mess
2848         size_t rend;
2849         if (sl.pos() > 0 && dit.depth() == 1) {
2850                 int pos = sl.pos();
2851                 if (pos && dit.boundary())
2852                         --pos;
2853 //              lyxerr << "coordOffset: boundary:" << dit.boundary() << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
2854                 rend = pm.pos2row(pos);
2855         } else
2856                 rend = pm.pos2row(sl.pos());
2857 #else
2858         size_t rend = pm.pos2row(sl.pos());
2859 #endif
2860         for (size_t rit = 0; rit != rend; ++rit)
2861                 y += pm.rows()[rit].height();
2862         y += pm.rows()[rend].ascent();
2863
2864         TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
2865
2866         // Make relative position from the nested inset now bufferview absolute.
2867         int xx = bottom_tm.cursorX(dit.bottom(), dit.boundary() && dit.depth() == 1);
2868         x += xx;
2869
2870         // In the RTL case place the nested inset at the left of the cursor in
2871         // the outer paragraph
2872         bool boundary_1 = dit.boundary() && 1 == dit.depth();
2873         bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
2874         if (rtl)
2875                 x -= lastw;
2876
2877         return Point(x, y);
2878 }
2879
2880
2881 Point BufferView::getPos(DocIterator const & dit) const
2882 {
2883         if (!paragraphVisible(dit))
2884                 return Point(-1, -1);
2885
2886         CursorSlice const & bot = dit.bottom();
2887         TextMetrics const & tm = textMetrics(bot.text());
2888
2889         // offset from outer paragraph
2890         Point p = coordOffset(dit);
2891         p.y_ += tm.parMetrics(bot.pit()).position();
2892         return p;
2893 }
2894
2895
2896 bool BufferView::paragraphVisible(DocIterator const & dit) const
2897 {
2898         CursorSlice const & bot = dit.bottom();
2899         TextMetrics const & tm = textMetrics(bot.text());
2900
2901         return tm.contains(bot.pit());
2902 }
2903
2904
2905 void BufferView::caretPosAndHeight(Point & p, int & h) const
2906 {
2907         Cursor const & cur = cursor();
2908         Font const font = cur.real_current_font;
2909         frontend::FontMetrics const & fm = theFontMetrics(font);
2910         int const asc = fm.maxAscent();
2911         int const des = fm.maxDescent();
2912         h = asc + des;
2913         p = getPos(cur);
2914         p.y_ -= asc;
2915 }
2916
2917
2918 bool BufferView::cursorInView(Point const & p, int h) const
2919 {
2920         Cursor const & cur = cursor();
2921         // does the cursor touch the screen ?
2922         if (p.y_ + h < 0 || p.y_ >= workHeight() || !paragraphVisible(cur))
2923                 return false;
2924         return true;
2925 }
2926
2927
2928 int BufferView::horizScrollOffset() const
2929 {
2930         return d->horiz_scroll_offset_;
2931 }
2932
2933
2934 int BufferView::horizScrollOffset(Text const * text,
2935                                   pit_type pit, pos_type pos) const
2936 {
2937         // Is this a row that is currently scrolled?
2938         if (!d->current_row_slice_.empty()
2939             && &text->inset() == d->current_row_slice_.inset().asInsetText()
2940             && pit ==  d->current_row_slice_.pit()
2941             && pos ==  d->current_row_slice_.pos())
2942                 return d->horiz_scroll_offset_;
2943         return 0;
2944 }
2945
2946
2947 bool BufferView::hadHorizScrollOffset(Text const * text,
2948                                       pit_type pit, pos_type pos) const
2949 {
2950         return !d->last_row_slice_.empty()
2951                && &text->inset() == d->last_row_slice_.inset().asInsetText()
2952                && pit ==  d->last_row_slice_.pit()
2953                && pos ==  d->last_row_slice_.pos();
2954 }
2955
2956
2957 void BufferView::setCurrentRowSlice(CursorSlice const & rowSlice)
2958 {
2959         // nothing to do if the cursor was already on this row
2960         if (d->current_row_slice_ == rowSlice) {
2961                 d->last_row_slice_ = CursorSlice();
2962                 return;
2963         }
2964
2965         // if the (previous) current row was scrolled, we have to
2966         // remember it in order to repaint it next time.
2967         if (d->horiz_scroll_offset_ != 0)
2968                 d->last_row_slice_ = d->current_row_slice_;
2969         else
2970                 d->last_row_slice_ = CursorSlice();
2971
2972         // Since we changed row, the scroll offset is not valid anymore
2973         d->horiz_scroll_offset_ = 0;
2974         d->current_row_slice_ = rowSlice;
2975 }
2976
2977
2978 namespace {
2979
2980 bool sliceInRow(CursorSlice const & cs, Text const * text, Row const & row)
2981 {
2982         return !cs.empty() && cs.text() == text && cs.pit() == row.pit()
2983                 && row.pos() <= cs.pos() && cs.pos() <= row.endpos();
2984 }
2985
2986 }
2987
2988
2989 bool BufferView::needRepaint(Text const * text, Row const & row) const
2990 {
2991         return d->repaint_caret_row_ && sliceInRow(d->caret_slice_, text, row);
2992 }
2993
2994
2995 void BufferView::checkCursorScrollOffset()
2996 {
2997         CursorSlice rowSlice = d->cursor_.bottom();
2998         TextMetrics const & tm = textMetrics(rowSlice.text());
2999
3000         // Stop if metrics have not been computed yet, since it means
3001         // that there is nothing to do.
3002         if (!tm.contains(rowSlice.pit()))
3003                 return;
3004         ParagraphMetrics const & pm = tm.parMetrics(rowSlice.pit());
3005         Row const & row = pm.getRow(rowSlice.pos(),
3006                                     d->cursor_.boundary() && rowSlice == d->cursor_.top());
3007         rowSlice.pos() = row.pos();
3008
3009         // Set the row on which the cursor lives.
3010         setCurrentRowSlice(rowSlice);
3011
3012         // Current x position of the cursor in pixels
3013         int cur_x = getPos(d->cursor_).x_;
3014
3015         // Horizontal scroll offset of the cursor row in pixels
3016         int offset = d->horiz_scroll_offset_;
3017         int const MARGIN = 2 * theFontMetrics(d->cursor_.real_current_font).em()
3018                            + row.right_margin;
3019         if (row.right_x() <= workWidth() - row.right_margin) {
3020                 // Row is narrower than the work area, no offset needed.
3021                 offset = 0;
3022         } else {
3023                 if (cur_x - offset < MARGIN) {
3024                         // cursor would be too far right
3025                         offset = cur_x - MARGIN;
3026                 } else if (cur_x - offset > workWidth() - MARGIN) {
3027                         // cursor would be too far left
3028                         offset = cur_x - workWidth() + MARGIN;
3029                 }
3030                 // Correct the offset to make sure that we do not scroll too much
3031                 if (offset < 0)
3032                         offset = 0;
3033                 if (row.right_x() - offset < workWidth() - row.right_margin)
3034                         offset = row.right_x() - workWidth() + row.right_margin;
3035         }
3036
3037         //lyxerr << "cur_x=" << cur_x << ", offset=" << offset << ", row.wid=" << row.width() << ", margin=" << MARGIN << endl;
3038
3039         if (offset != d->horiz_scroll_offset_)
3040                 LYXERR(Debug::PAINTING, "Horiz. scroll offset changed from "
3041                        << d->horiz_scroll_offset_ << " to " << offset);
3042
3043         if (d->update_strategy_ == NoScreenUpdate
3044             && (offset != d->horiz_scroll_offset_
3045                 || !d->last_row_slice_.empty())) {
3046                 // FIXME: if one uses SingleParUpdate, then home/end
3047                 // will not work on long rows. Why?
3048                 d->update_strategy_ = FullScreenUpdate;
3049         }
3050
3051         d->horiz_scroll_offset_ = offset;
3052 }
3053
3054
3055 void BufferView::draw(frontend::Painter & pain, bool paint_caret)
3056 {
3057         if (height_ == 0 || width_ == 0)
3058                 return;
3059         LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
3060
3061         Text & text = buffer_.text();
3062         TextMetrics const & tm = d->text_metrics_[&text];
3063         int const y = tm.first().second->position();
3064         PainterInfo pi(this, pain);
3065
3066         /**  A repaint of the previous caret row is needed if there is
3067          *  caret painted on screen and either
3068          *   1/ a new caret has to be painted at a place different from
3069          *      the existing one;
3070          *   2/ there is no need for a caret anymore.
3071          */
3072         d->repaint_caret_row_ = !d->caret_slice_.empty() &&
3073                 ((paint_caret && d->cursor_.top() != d->caret_slice_)
3074                  || ! paint_caret);
3075
3076         // Check whether the row where the cursor lives needs to be scrolled.
3077         // Update the drawing strategy if needed.
3078         checkCursorScrollOffset();
3079
3080         switch (d->update_strategy_) {
3081
3082         case NoScreenUpdate:
3083                 // no screen painting is actually needed. In nodraw stage
3084                 // however, the different coordinates of insets and paragraphs
3085                 // needs to be updated.
3086                 LYXERR(Debug::PAINTING, "Strategy: NoScreenUpdate");
3087                 pi.full_repaint = false;
3088                 if (pain.isNull()) {
3089                         pi.full_repaint = true;
3090                         tm.draw(pi, 0, y);
3091                 } else if (d->repaint_caret_row_) {
3092                         pi.full_repaint = false;
3093                         tm.draw(pi, 0, y);
3094                 }
3095                 break;
3096
3097         case SingleParUpdate:
3098                 pi.full_repaint = false;
3099                 LYXERR(Debug::PAINTING, "Strategy: SingleParUpdate");
3100                 // In general, only the current row of the outermost paragraph
3101                 // will be redrawn. Particular cases where selection spans
3102                 // multiple paragraph are correctly detected in TextMetrics.
3103                 tm.draw(pi, 0, y);
3104                 break;
3105
3106         case DecorationUpdate:
3107                 // FIXME: We should also distinguish DecorationUpdate to avoid text
3108                 // drawing if possible. This is not possible to do easily right now
3109                 // because of the single backing pixmap.
3110
3111         case FullScreenUpdate:
3112
3113                 LYXERR(Debug::PAINTING,
3114                        ((d->update_strategy_ == FullScreenUpdate)
3115                         ? "Strategy: FullScreenUpdate"
3116                         : "Strategy: DecorationUpdate"));
3117
3118                 // The whole screen, including insets, will be refreshed.
3119                 pi.full_repaint = true;
3120
3121                 // Clear background.
3122                 pain.fillRectangle(0, 0, width_, height_,
3123                         pi.backgroundColor(&buffer_.inset()));
3124
3125                 // Draw everything.
3126                 tm.draw(pi, 0, y);
3127
3128                 // and possibly grey out below
3129                 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3130                 int const y2 = lastpm.second->position() + lastpm.second->descent();
3131
3132                 if (y2 < height_) {
3133                         Color color = buffer().isInternal()
3134                                 ? Color_background : Color_bottomarea;
3135                         pain.fillRectangle(0, y2, width_, height_ - y2, color);
3136                 }
3137                 break;
3138         }
3139         LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING  ***");
3140
3141         // The scrollbar needs an update.
3142         updateScrollbar();
3143
3144         // Normalize anchor for next time
3145         pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
3146         pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
3147         for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
3148                 ParagraphMetrics const & pm = tm.parMetrics(pit);
3149                 if (pm.position() + pm.descent() > 0) {
3150                         d->anchor_pit_ = pit;
3151                         d->anchor_ypos_ = pm.position();
3152                         break;
3153                 }
3154         }
3155         LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
3156                 << "  anchor ypos = " << d->anchor_ypos_);
3157
3158         if (!pain.isNull()) {
3159                 // reset the update flags, everything has been done
3160                 d->update_flags_ = Update::None;
3161         }
3162
3163         // Remember what has just been done for the next draw() step
3164         if (paint_caret)
3165                 d->caret_slice_ = d->cursor_.top();
3166         else
3167                 d->caret_slice_ = CursorSlice();
3168 }
3169
3170
3171 void BufferView::message(docstring const & msg)
3172 {
3173         if (d->gui_)
3174                 d->gui_->message(msg);
3175 }
3176
3177
3178 void BufferView::showDialog(string const & name)
3179 {
3180         if (d->gui_)
3181                 d->gui_->showDialog(name, string());
3182 }
3183
3184
3185 void BufferView::showDialog(string const & name,
3186         string const & data, Inset * inset)
3187 {
3188         if (d->gui_)
3189                 d->gui_->showDialog(name, data, inset);
3190 }
3191
3192
3193 void BufferView::updateDialog(string const & name, string const & data)
3194 {
3195         if (d->gui_)
3196                 d->gui_->updateDialog(name, data);
3197 }
3198
3199
3200 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
3201 {
3202         d->gui_ = gui;
3203 }
3204
3205
3206 // FIXME: Move this out of BufferView again
3207 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
3208 {
3209         if (!fname.isReadableFile()) {
3210                 docstring const error = from_ascii(strerror(errno));
3211                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3212                 docstring const text =
3213                   bformat(_("Could not read the specified document\n"
3214                             "%1$s\ndue to the error: %2$s"), file, error);
3215                 Alert::error(_("Could not read file"), text);
3216                 return docstring();
3217         }
3218
3219         if (!fname.isReadableFile()) {
3220                 docstring const file = makeDisplayPath(fname.absFileName(), 50);
3221                 docstring const text =
3222                   bformat(_("%1$s\n is not readable."), file);
3223                 Alert::error(_("Could not open file"), text);
3224                 return docstring();
3225         }
3226
3227         // FIXME UNICODE: We don't know the encoding of the file
3228         docstring file_content = fname.fileContents("UTF-8");
3229         if (file_content.empty()) {
3230                 Alert::error(_("Reading not UTF-8 encoded file"),
3231                              _("The file is not UTF-8 encoded.\n"
3232                                "It will be read as local 8Bit-encoded.\n"
3233                                "If this does not give the correct result\n"
3234                                "then please change the encoding of the file\n"
3235                                "to UTF-8 with a program other than LyX.\n"));
3236                 file_content = fname.fileContents("local8bit");
3237         }
3238
3239         return normalize_c(file_content);
3240 }
3241
3242
3243 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
3244 {
3245         docstring const tmpstr = contentsOfPlaintextFile(f);
3246
3247         if (tmpstr.empty())
3248                 return;
3249
3250         Cursor & cur = cursor();
3251         cap::replaceSelection(cur);
3252         buffer_.undo().recordUndo(cur);
3253         if (asParagraph)
3254                 cur.innerText()->insertStringAsParagraphs(cur, tmpstr, cur.current_font);
3255         else
3256                 cur.innerText()->insertStringAsLines(cur, tmpstr, cur.current_font);
3257
3258         buffer_.changed(true);
3259 }
3260
3261
3262 docstring const & BufferView::inlineCompletion() const
3263 {
3264         return d->inlineCompletion_;
3265 }
3266
3267
3268 size_t const & BufferView::inlineCompletionUniqueChars() const
3269 {
3270         return d->inlineCompletionUniqueChars_;
3271 }
3272
3273
3274 DocIterator const & BufferView::inlineCompletionPos() const
3275 {
3276         return d->inlineCompletionPos_;
3277 }
3278
3279
3280 void BufferView::resetInlineCompletionPos()
3281 {
3282         d->inlineCompletionPos_ = DocIterator();
3283 }
3284
3285
3286 bool samePar(DocIterator const & a, DocIterator const & b)
3287 {
3288         if (a.empty() && b.empty())
3289                 return true;
3290         if (a.empty() || b.empty())
3291                 return false;
3292         if (a.depth() != b.depth())
3293                 return false;
3294         return &a.innerParagraph() == &b.innerParagraph();
3295 }
3296
3297
3298 void BufferView::setInlineCompletion(Cursor const & cur, DocIterator const & pos,
3299         docstring const & completion, size_t uniqueChars)
3300 {
3301         uniqueChars = min(completion.size(), uniqueChars);
3302         bool changed = d->inlineCompletion_ != completion
3303                 || d->inlineCompletionUniqueChars_ != uniqueChars;
3304         bool singlePar = true;
3305         d->inlineCompletion_ = completion;
3306         d->inlineCompletionUniqueChars_ = min(completion.size(), uniqueChars);
3307
3308         //lyxerr << "setInlineCompletion pos=" << pos << " completion=" << completion << " uniqueChars=" << uniqueChars << std::endl;
3309
3310         // at new position?
3311         DocIterator const & old = d->inlineCompletionPos_;
3312         if (old != pos) {
3313                 //lyxerr << "inlineCompletionPos changed" << std::endl;
3314                 // old or pos are in another paragraph?
3315                 if ((!samePar(cur, pos) && !pos.empty())
3316                     || (!samePar(cur, old) && !old.empty())) {
3317                         singlePar = false;
3318                         //lyxerr << "different paragraph" << std::endl;
3319                 }
3320                 d->inlineCompletionPos_ = pos;
3321         }
3322
3323         // set update flags
3324         if (changed) {
3325                 if (singlePar && !(cur.result().screenUpdate() & Update::Force))
3326                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
3327                 else
3328                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::Force);
3329         }
3330 }
3331
3332
3333 bool BufferView::clickableInset() const
3334 {
3335         return d->clickable_inset_;
3336 }
3337
3338 } // namespace lyx