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