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