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