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