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