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