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