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