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