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