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