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