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