]> git.lyx.org Git - features.git/blob - src/BufferView.cpp
Polish revision 18825 and fix some remaining issues with child documents. The diff...
[features.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "bufferview_funcs.h"
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "debug.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 "gettext.h"
34 #include "Intl.h"
35 #include "InsetIterator.h"
36 #include "Language.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "Layout.h"
43 #include "Text.h"
44 #include "TextClass.h"
45 #include "LyXRC.h"
46 #include "Session.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
51 #include "TexRow.h"
52 #include "toc.h"
53 #include "Undo.h"
54 #include "VSpace.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66
67 #include "graphics/Previews.h"
68
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
74
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
77
78 #include <functional>
79 #include <vector>
80
81
82 namespace lyx {
83
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
93
94 using std::distance;
95 using std::endl;
96 using std::istringstream;
97 using std::make_pair;
98 using std::min;
99 using std::max;
100 using std::mem_fun_ref;
101 using std::string;
102 using std::vector;
103
104 namespace Alert = frontend::Alert;
105
106 namespace {
107
108 /// Return an inset of this class if it exists at the current cursor position
109 template <class T>
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
111 {
112         T * inset = 0;
113         DocIterator it = cur;
114         if (it.nextInset() &&
115             it.nextInset()->lyxCode() == code) {
116                 inset = static_cast<T*>(it.nextInset());
117         }
118         return inset;
119 }
120
121 } // anon namespace
122
123
124 BufferView::BufferView()
125         : width_(0), height_(0), buffer_(0), wh_(0),
126           cursor_(*this),
127           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128           intl_(new Intl), last_inset_(0)
129 {
130         xsel_cache_.set = false;
131         intl_->initKeyMapper(lyxrc.use_kbmap);
132 }
133
134
135 BufferView::~BufferView()
136 {
137 }
138
139
140 Buffer * BufferView::buffer() const
141 {
142         return buffer_;
143 }
144
145
146 void BufferView::setBuffer(Buffer * b)
147 {
148         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149                             << "[ b = " << b << "]" << endl;
150
151         if (buffer_) {
152                 // Save the actual cursor position and anchor inside the
153                 // buffer so that it can be restored in case we rechange
154                 // to this buffer later on.
155                 buffer_->saveCursor(cursor_.selectionBegin(),
156                                     cursor_.selectionEnd());
157                 // update bookmark pit of the current buffer before switch
158                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159                         BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160                         if (buffer()->fileName() != bm.filename.absFilename())
161                                 continue;
162                         // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163                         // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
164                         pit_type new_pit;
165                         pos_type new_pos;
166                         int new_id;
167                         boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168                         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169                                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
170                 }
171                 // current buffer is going to be switched-off, save cursor pos
172                 // Ideally, the whole cursor stack should be saved, but session
173                 // currently can only handle bottom (whole document) level pit and pos.
174                 // That is to say, if a cursor is in a nested inset, it will be
175                 // restore to the left of the top level inset.
176                 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177                         boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
178         }
179
180         // If we're quitting lyx, don't bother updating stuff
181         if (quitting) {
182                 buffer_ = 0;
183                 return;
184         }
185
186         //FIXME Fix for bug 3440 is here.
187         // If we are closing current buffer, switch to the first in
188         // buffer list.
189         if (!b) {
190                 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
191                                     << " No Buffer!" << endl;
192                 // We are closing the buffer, use the first buffer as current
193                 //FIXME 3440
194                 // if (last_buffer_) buffer_ = last_buffer_;
195                 // also check that this is in theBufferList()?
196                 buffer_ = theBufferList().first();
197         } else {
198                 //FIXME 3440
199                 // last_buffer = buffer_;
200                 // Set current buffer
201                 buffer_ = b;
202         }
203
204         // Reset old cursor
205         cursor_ = Cursor(*this);
206         anchor_ref_ = 0;
207         offset_ref_ = 0;
208
209         if (!buffer_)
210                 return;
211
212         LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
213                                         << "Buffer addr: " << buffer_ << endl;
214         cursor_.push(buffer_->inset());
215         cursor_.resetAnchor();
216         buffer_->text().setCurrentFont(cursor_);
217         if (buffer_->getCursor().size() > 0 &&
218                         buffer_->getAnchor().size() > 0)
219         {
220                 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
221                 cursor_.resetAnchor();
222                 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
223                 cursor_.setSelection();
224                 // do not set selection to the new buffer because we
225                 // only paste recent selection.
226
227                 // Make sure that the restored cursor is not broken. This can happen for
228                 // example if this Buffer has been modified by another view.
229                 cursor_.fixIfBroken();
230         }
231         updateMetrics(false);
232         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
233                 graphics::Previews::get().generateBufferPreviews(*buffer_);
234 }
235
236 void BufferView::resize()
237 {
238         if (!buffer_)
239                 return;
240
241         LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
242
243         updateMetrics(false);
244 }
245
246
247 bool BufferView::fitCursor()
248 {
249         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
250                 frontend::FontMetrics const & fm =
251                         theFontMetrics(cursor_.getFont());
252                 int const asc = fm.maxAscent();
253                 int const des = fm.maxDescent();
254                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
255                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
256                         return false;
257         }
258         center();
259         return true;
260 }
261
262
263 bool BufferView::multiParSel()
264 {
265         if (!cursor_.selection())
266                 return false;
267         bool ret = multiparsel_cache_;
268         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
269         // Either this, or previous selection spans paragraphs
270         return ret || multiparsel_cache_;
271 }
272
273
274 bool BufferView::update(Update::flags flags)
275 {
276         // last_inset_ points to the last visited inset. This pointer may become
277         // invalid because of keyboard editing. Since all such operations
278         // causes screen update(), I reset last_inset_ to avoid such a problem.
279         last_inset_ = 0;
280         // This is close to a hot-path.
281         LYXERR(Debug::DEBUG)
282                 << BOOST_CURRENT_FUNCTION
283                 << "[fitcursor = " << (flags & Update::FitCursor)
284                 << ", forceupdate = " << (flags & Update::Force)
285                 << ", singlepar = " << (flags & Update::SinglePar)
286                 << "]  buffer: " << buffer_ << endl;
287
288         // Check needed to survive LyX startup
289         if (!buffer_)
290                 return false;
291
292         LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
293
294         // Update macro store
295         if (!(cursor().inMathed() && cursor().inMacroMode()))
296                 buffer_->buildMacros();
297
298         // Now do the first drawing step if needed. This consists on updating
299         // the CoordCache in updateMetrics().
300         // The second drawing step is done in WorkArea::redraw() if needed.
301
302         // Case when no explicit update is requested.
303         if (!flags) {
304                 // no need to redraw anything.
305                 metrics_info_.update_strategy = NoScreenUpdate;
306                 return false;
307         }
308
309         if (flags == Update::Decoration) {
310                 metrics_info_.update_strategy = DecorationUpdate;
311                 return true;
312         }
313
314         if (flags == Update::FitCursor
315                 || flags == (Update::Decoration | Update::FitCursor)) {
316                 bool const fit_cursor = fitCursor();
317                 // tell the frontend to update the screen if needed.
318                 if (fit_cursor) {
319                         updateMetrics(false);
320                         return true;
321                 }
322                 if (flags & Update::Decoration) {
323                         metrics_info_.update_strategy = DecorationUpdate;
324                         return true;
325                 }
326                 // no screen update is needed.
327                 metrics_info_.update_strategy = NoScreenUpdate;
328                 return false;
329         }
330
331         bool full_metrics = flags & Update::Force;
332         if (flags & Update::MultiParSel)
333                 full_metrics |= multiParSel();
334
335         bool const single_par = !full_metrics;
336         updateMetrics(single_par);
337
338         if (flags & Update::FitCursor && fitCursor())
339                 updateMetrics(false);
340
341         // tell the frontend to update the screen.
342         return true;
343 }
344
345
346 void BufferView::updateScrollbar()
347 {
348         if (!buffer_) {
349                 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
350                                      << " no text in updateScrollbar" << endl;
351                 scrollbarParameters_.reset();
352                 return;
353         }
354
355         Text & t = buffer_->text();
356         TextMetrics & tm = text_metrics_[&t];
357
358         int const parsize = int(t.paragraphs().size() - 1);
359         if (anchor_ref_ >  parsize)  {
360                 anchor_ref_ = parsize;
361                 offset_ref_ = 0;
362         }
363
364         LYXERR(Debug::GUI)
365                 << BOOST_CURRENT_FUNCTION
366                 << " Updating scrollbar: height: " << t.paragraphs().size()
367                 << " curr par: " << cursor_.bottom().pit()
368                 << " default height " << defaultRowHeight() << endl;
369
370         // It would be better to fix the scrollbar to understand
371         // values in [0..1] and divide everything by wh
372
373         // estimated average paragraph height:
374         if (wh_ == 0)
375                 wh_ = height_ / 4;
376
377         int h = tm.parMetrics(anchor_ref_).height();
378
379         // Normalize anchor/offset (MV):
380         while (offset_ref_ > h && anchor_ref_ < parsize) {
381                 anchor_ref_++;
382                 offset_ref_ -= h;
383                 h = tm.parMetrics(anchor_ref_).height();
384         }
385         // Look at paragraph heights on-screen
386         int sumh = 0;
387         int nh = 0;
388         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
389                 if (sumh > height_)
390                         break;
391                 int const h2 = tm.parMetrics(pit).height();
392                 sumh += h2;
393                 nh++;
394         }
395
396         BOOST_ASSERT(nh);
397         int const hav = sumh / nh;
398         // More realistic average paragraph height
399         if (hav > wh_)
400                 wh_ = hav;
401
402         BOOST_ASSERT(h);
403         scrollbarParameters_.height = (parsize + 1) * wh_;
404         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
405         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
406 }
407
408
409 ScrollbarParameters const & BufferView::scrollbarParameters() const
410 {
411         return scrollbarParameters_;
412 }
413
414
415 void BufferView::scrollDocView(int value)
416 {
417         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
418                            << "[ value = " << value << "]" << endl;
419
420         if (!buffer_)
421                 return;
422
423         Text & t = buffer_->text();
424         TextMetrics & tm = text_metrics_[&t];
425
426         float const bar = value / float(wh_ * t.paragraphs().size());
427
428         anchor_ref_ = int(bar * t.paragraphs().size());
429         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
430                 anchor_ref_ = int(t.paragraphs().size()) - 1;
431
432         tm.redoParagraph(anchor_ref_);
433         int const h = tm.parMetrics(anchor_ref_).height();
434         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
435         updateMetrics(false);
436 }
437
438
439 void BufferView::setCursorFromScrollbar()
440 {
441         if (!buffer_)
442                 return;
443
444         Text & t = buffer_->text();
445
446         int const height = 2 * defaultRowHeight();
447         int const first = height;
448         int const last = height_ - height;
449         Cursor & cur = cursor_;
450
451         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
452
453         switch (st) {
454         case bv_funcs::CUR_ABOVE:
455                 // We reset the cursor because bv_funcs::status() does not
456                 // work when the cursor is within mathed.
457                 cur.reset(buffer_->inset());
458                 t.setCursorFromCoordinates(cur, 0, first);
459                 cur.clearSelection();
460                 break;
461         case bv_funcs::CUR_BELOW:
462                 // We reset the cursor because bv_funcs::status() does not
463                 // work when the cursor is within mathed.
464                 cur.reset(buffer_->inset());
465                 t.setCursorFromCoordinates(cur, 0, last);
466                 cur.clearSelection();
467                 break;
468         case bv_funcs::CUR_INSIDE:
469                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
470                 int const newy = min(last, max(y, first));
471                 if (y != newy) {
472                         cur.reset(buffer_->inset());
473                         t.setCursorFromCoordinates(cur, 0, newy);
474                 }
475         }
476 }
477
478
479 Change const BufferView::getCurrentChange() const
480 {
481         if (!cursor_.selection())
482                 return Change(Change::UNCHANGED);
483
484         DocIterator dit = cursor_.selectionBegin();
485         return dit.paragraph().lookupChange(dit.pos());
486 }
487
488
489 void BufferView::saveBookmark(unsigned int idx)
490 {
491         // tenatively save bookmark, id and pos will be used to
492         // acturately locate a bookmark in a 'live' lyx session.
493         // pit and pos will be updated with bottom level pit/pos
494         // when lyx exits.
495         LyX::ref().session().bookmarks().save(
496                 FileName(buffer_->fileName()),
497                 cursor_.bottom().pit(),
498                 cursor_.bottom().pos(),
499                 cursor_.paragraph().id(),
500                 cursor_.pos(),
501                 idx
502         );
503         if (idx)
504                 // emit message signal.
505                 message(_("Save bookmark"));
506 }
507
508
509 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
510         int top_id, pos_type top_pos)
511 {
512         cursor_.clearSelection();
513
514         // if a valid par_id is given, try it first
515         // This is the case for a 'live' bookmark when unique paragraph ID
516         // is used to track bookmarks.
517         if (top_id > 0) {
518                 ParIterator par = buffer_->getParFromID(top_id);
519                 if (par != buffer_->par_iterator_end()) {
520                         DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
521                         // Some slices of the iterator may not be
522                         // reachable (e.g. closed collapsable inset)
523                         // so the dociterator may need to be
524                         // shortened. Otherwise, setCursor may crash
525                         // lyx when the cursor can not be set to these
526                         // insets.
527                         size_t const n = dit.depth();
528                         for (size_t i = 0; i < n; ++i)
529                                 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
530                                         dit.resize(i);
531                                         break;
532                                 }
533                         setCursor(dit);
534                         // Note: return bottom (document) level pit.
535                         return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
536                 }
537         }
538         // if top_id == 0, or searching through top_id failed
539         // This is the case for a 'restored' bookmark when only bottom
540         // (document level) pit was saved. Because of this, bookmark
541         // restoration is inaccurate. If a bookmark was within an inset,
542         // it will be restored to the left of the outmost inset that contains
543         // the bookmark.
544         if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
545                 DocIterator it = doc_iterator_begin(buffer_->inset());
546                 it.pit() = bottom_pit;
547                 it.pos() = min(bottom_pos, it.paragraph().size());
548                 setCursor(it);
549                 return boost::make_tuple(it.pit(), it.pos(),
550                                          it.paragraph().id());
551         }
552         // both methods fail
553         return boost::make_tuple(pit_type(0), pos_type(0), 0);
554 }
555
556
557 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
558 {
559         if (lyxrc.rtl_support) {
560                 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
561                         if (intl_->keymap == Intl::PRIMARY)
562                                 intl_->keyMapSec();
563                 } else {
564                         if (intl_->keymap == Intl::SECONDARY)
565                                 intl_->keyMapPrim();
566                 }
567         }
568         
569         intl_->getTransManager().translateAndInsert(c, t, cur);
570 }
571
572
573 int BufferView::workWidth() const
574 {
575         return width_;
576 }
577
578
579 void BufferView::center()
580 {
581         CursorSlice & bot = cursor_.bottom();
582         TextMetrics & tm = text_metrics_[bot.text()];
583         pit_type const pit = bot.pit();
584         tm.redoParagraph(pit);
585         ParagraphMetrics const & pm = tm.parMetrics(pit);
586         anchor_ref_ = pit;
587         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
588                 + pm.ascent() - height_ / 2;
589 }
590
591
592 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
593 {
594         FuncStatus flag;
595
596         Cursor & cur = cursor_;
597
598         switch (cmd.action) {
599
600         case LFUN_UNDO:
601                 flag.enabled(!buffer_->undostack().empty());
602                 break;
603         case LFUN_REDO:
604                 flag.enabled(!buffer_->redostack().empty());
605                 break;
606         case LFUN_FILE_INSERT:
607         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
608         case LFUN_FILE_INSERT_PLAINTEXT:
609         case LFUN_BOOKMARK_SAVE:
610                 // FIXME: Actually, these LFUNS should be moved to Text
611                 flag.enabled(cur.inTexted());
612                 break;
613         case LFUN_FONT_STATE:
614         case LFUN_LABEL_INSERT:
615         case LFUN_PARAGRAPH_GOTO:
616         // FIXME handle non-trivially
617         case LFUN_OUTLINE_UP:
618         case LFUN_OUTLINE_DOWN:
619         case LFUN_OUTLINE_IN:
620         case LFUN_OUTLINE_OUT:
621         case LFUN_NOTE_NEXT:
622         case LFUN_REFERENCE_NEXT:
623         case LFUN_WORD_FIND:
624         case LFUN_MARK_OFF:
625         case LFUN_MARK_ON:
626         case LFUN_MARK_TOGGLE:
627         case LFUN_SCREEN_RECENTER:
628         case LFUN_BIBTEX_DATABASE_ADD:
629         case LFUN_BIBTEX_DATABASE_DEL:
630         case LFUN_WORDS_COUNT:
631         case LFUN_NEXT_INSET_TOGGLE:
632                 flag.enabled(true);
633                 break;
634
635         case LFUN_WORD_REPLACE:
636                 flag.enabled(!cur.paragraph().isDeleted(cur.pos()));
637                 break;
638
639         case LFUN_LABEL_GOTO: {
640                 flag.enabled(!cmd.argument().empty()
641                     || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
642                 break;
643         }
644
645         case LFUN_CHANGES_TRACK:
646                 flag.enabled(true);
647                 flag.setOnOff(buffer_->params().trackChanges);
648                 break;
649
650         case LFUN_CHANGES_OUTPUT:
651                 flag.enabled(buffer_);
652                 flag.setOnOff(buffer_->params().outputChanges);
653                 break;
654
655         case LFUN_CHANGES_MERGE:
656         case LFUN_CHANGE_NEXT:
657         case LFUN_ALL_CHANGES_ACCEPT:
658         case LFUN_ALL_CHANGES_REJECT:
659                 // TODO: context-sensitive enabling of LFUNs
660                 // In principle, these command should only be enabled if there
661                 // is a change in the document. However, without proper
662                 // optimizations, this will inevitably result in poor performance.
663                 flag.enabled(buffer_);
664                 break;
665
666         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
667                 flag.setOnOff(buffer_->params().compressed);
668                 break;
669         }
670
671         default:
672                 flag.enabled(false);
673         }
674
675         return flag;
676 }
677
678
679 Update::flags BufferView::dispatch(FuncRequest const & cmd)
680 {
681         //lyxerr << BOOST_CURRENT_FUNCTION
682         //       << [ cmd = " << cmd << "]" << endl;
683
684         // Make sure that the cached BufferView is correct.
685         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
686                 << " action[" << cmd.action << ']'
687                 << " arg[" << to_utf8(cmd.argument()) << ']'
688                 << " x[" << cmd.x << ']'
689                 << " y[" << cmd.y << ']'
690                 << " button[" << cmd.button() << ']'
691                 << endl;
692
693         // FIXME: this should not be possible.
694         if (!buffer_)
695                 return Update::None;
696
697         Cursor & cur = cursor_;
698         // Default Update flags.
699         Update::flags updateFlags = Update::Force | Update::FitCursor;
700
701         switch (cmd.action) {
702
703         case LFUN_UNDO:
704                 cur.message(_("Undo"));
705                 cur.clearSelection();
706                 if (!textUndo(*this)) {
707                         cur.message(_("No further undo information"));
708                         updateFlags = Update::None;
709                 }
710                 break;
711
712         case LFUN_REDO:
713                 cur.message(_("Redo"));
714                 cur.clearSelection();
715                 if (!textRedo(*this)) {
716                         cur.message(_("No further redo information"));
717                         updateFlags = Update::None;
718                 }
719                 break;
720
721         case LFUN_FILE_INSERT:
722                 // FIXME UNICODE
723                 menuInsertLyXFile(to_utf8(cmd.argument()));
724                 break;
725
726         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
727                 // FIXME UNICODE
728                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
729                 break;
730
731         case LFUN_FILE_INSERT_PLAINTEXT:
732                 // FIXME UNICODE
733                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
734                 break;
735
736         case LFUN_FONT_STATE:
737                 cur.message(cur.currentState());
738                 break;
739
740         case LFUN_BOOKMARK_SAVE:
741                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
742                 break;
743
744         case LFUN_LABEL_GOTO: {
745                 docstring label = cmd.argument();
746                 if (label.empty()) {
747                         InsetRef * inset =
748                                 getInsetByCode<InsetRef>(cursor_,
749                                                          Inset::REF_CODE);
750                         if (inset) {
751                                 label = inset->getParam("reference");
752                                 // persistent=false: use temp_bookmark
753                                 saveBookmark(0);
754                         }
755                 }
756
757                 if (!label.empty())
758                         gotoLabel(label);
759                 break;
760         }
761
762         case LFUN_PARAGRAPH_GOTO: {
763                 int const id = convert<int>(to_utf8(cmd.argument()));
764                 int i = 0;
765                 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
766                         ParIterator par = b->getParFromID(id);
767                         if (par == b->par_iterator_end()) {
768                                 LYXERR(Debug::INFO)
769                                         << "No matching paragraph found! ["
770                                         << id << "]." << endl;
771                         } else {
772                                 LYXERR(Debug::INFO)
773                                         << "Paragraph " << par->id()
774                                         << " found in buffer `"
775                                         << b->fileName() << "'." << endl;
776
777                                 if (b == buffer_) {
778                                         // Set the cursor
779                                         setCursor(makeDocIterator(par, 0));
780                                 } else {
781                                         // Switch to other buffer view and resend cmd
782                                         theLyXFunc().dispatch(FuncRequest(
783                                                 LFUN_BUFFER_SWITCH, b->fileName()));
784                                         theLyXFunc().dispatch(cmd);
785                                         updateFlags = Update::None;
786                                 }
787                                 break;
788                         }
789                         ++i;
790                 }
791                 break;
792         }
793
794         case LFUN_OUTLINE_UP:
795                 toc::outline(toc::Up, cursor_);
796                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
797                 updateLabels(*buffer_);
798                 break;
799         case LFUN_OUTLINE_DOWN:
800                 toc::outline(toc::Down, cursor_);
801                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
802                 updateLabels(*buffer_);
803                 break;
804         case LFUN_OUTLINE_IN:
805                 toc::outline(toc::In, cursor_);
806                 updateLabels(*buffer_);
807                 break;
808         case LFUN_OUTLINE_OUT:
809                 toc::outline(toc::Out, cursor_);
810                 updateLabels(*buffer_);
811                 break;
812
813         case LFUN_NOTE_NEXT:
814                 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
815                 break;
816
817         case LFUN_REFERENCE_NEXT: {
818                 vector<Inset_code> tmp;
819                 tmp.push_back(Inset::LABEL_CODE);
820                 tmp.push_back(Inset::REF_CODE);
821                 bv_funcs::gotoInset(this, tmp, true);
822                 break;
823         }
824
825         case LFUN_CHANGES_TRACK:
826                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
827                 break;
828
829         case LFUN_CHANGES_OUTPUT:
830                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
831                 if (buffer_->params().outputChanges) {
832                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
833                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
834                                           LaTeXFeatures::isAvailable("xcolor");
835
836                         if (!dvipost && !xcolorsoul) {
837                                 Alert::warning(_("Changes not shown in LaTeX output"),
838                                                _("Changes will not be highlighted in LaTeX output, "
839                                                  "because neither dvipost nor xcolor/soul are installed.\n"
840                                                  "Please install these packages or redefine "
841                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
842                         } else if (!xcolorsoul) {
843                                 Alert::warning(_("Changes not shown in LaTeX output"),
844                                                _("Changes will not be highlighted in LaTeX output "
845                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
846                                                  "Please install both packages or redefine "
847                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
848                         }
849                 }
850                 break;
851
852         case LFUN_CHANGE_NEXT:
853                 findNextChange(this);
854                 break;
855
856         case LFUN_CHANGES_MERGE:
857                 if (findNextChange(this))
858                         showDialog("changes");
859                 break;
860
861         case LFUN_ALL_CHANGES_ACCEPT:
862                 // select complete document
863                 cursor_.reset(buffer_->inset());
864                 cursor_.selHandle(true);
865                 buffer_->text().cursorBottom(cursor_);
866                 // accept everything in a single step to support atomic undo
867                 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
868                 break;
869
870         case LFUN_ALL_CHANGES_REJECT:
871                 // select complete document
872                 cursor_.reset(buffer_->inset());
873                 cursor_.selHandle(true);
874                 buffer_->text().cursorBottom(cursor_);
875                 // reject everything in a single step to support atomic undo
876                 // Note: reject does not work recursively; the user may have to repeat the operation
877                 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
878                 break;
879
880         case LFUN_WORD_FIND:
881                 find(this, cmd);
882                 break;
883
884         case LFUN_WORD_REPLACE:
885                 replace(this, cmd);
886                 break;
887
888         case LFUN_MARK_OFF:
889                 cur.clearSelection();
890                 cur.resetAnchor();
891                 cur.message(from_utf8(N_("Mark off")));
892                 break;
893
894         case LFUN_MARK_ON:
895                 cur.clearSelection();
896                 cur.mark() = true;
897                 cur.resetAnchor();
898                 cur.message(from_utf8(N_("Mark on")));
899                 break;
900
901         case LFUN_MARK_TOGGLE:
902                 cur.clearSelection();
903                 if (cur.mark()) {
904                         cur.mark() = false;
905                         cur.message(from_utf8(N_("Mark removed")));
906                 } else {
907                         cur.mark() = true;
908                         cur.message(from_utf8(N_("Mark set")));
909                 }
910                 cur.resetAnchor();
911                 break;
912
913         case LFUN_SCREEN_RECENTER:
914                 center();
915                 break;
916
917         case LFUN_BIBTEX_DATABASE_ADD: {
918                 Cursor tmpcur = cursor_;
919                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
920                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
921                                                 Inset::BIBTEX_CODE);
922                 if (inset) {
923                         if (inset->addDatabase(to_utf8(cmd.argument())))
924                                 buffer_->updateBibfilesCache();
925                 }
926                 break;
927         }
928
929         case LFUN_BIBTEX_DATABASE_DEL: {
930                 Cursor tmpcur = cursor_;
931                 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
932                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
933                                                 Inset::BIBTEX_CODE);
934                 if (inset) {
935                         if (inset->delDatabase(to_utf8(cmd.argument())))
936                                 buffer_->updateBibfilesCache();
937                 }
938                 break;
939         }
940
941         case LFUN_WORDS_COUNT: {
942                 DocIterator from, to;
943                 if (cur.selection()) {
944                         from = cur.selectionBegin();
945                         to = cur.selectionEnd();
946                 } else {
947                         from = doc_iterator_begin(buffer_->inset());
948                         to = doc_iterator_end(buffer_->inset());
949                 }
950                 int const count = countWords(from, to);
951                 docstring message;
952                 if (count != 1) {
953                         if (cur.selection())
954                                 message = bformat(_("%1$d words in selection."),
955                                           count);
956                                 else
957                                         message = bformat(_("%1$d words in document."),
958                                                           count);
959                 }
960                 else {
961                         if (cur.selection())
962                                 message = _("One word in selection.");
963                         else
964                                 message = _("One word in document.");
965                 }
966
967                 Alert::information(_("Count words"), message);
968         }
969                 break;
970
971         case LFUN_BUFFER_TOGGLE_COMPRESSION:
972                 // turn compression on/off
973                 buffer_->params().compressed = !buffer_->params().compressed;
974                 break;
975
976         case LFUN_NEXT_INSET_TOGGLE: {
977                 // this is the real function we want to invoke
978                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
979                 // if there is an inset at cursor, see whether it
980                 // wants to toggle.
981                 Inset * inset = cur.nextInset();
982                 if (inset && inset->isActive()) {
983                         Cursor tmpcur = cur;
984                         tmpcur.pushLeft(*inset);
985                         inset->dispatch(tmpcur, tmpcmd);
986                         if (tmpcur.result().dispatched()) {
987                                 cur.dispatched();
988                         }
989                 }
990                 // if it did not work, try the underlying inset.
991                 if (!cur.result().dispatched())
992                         cur.dispatch(tmpcmd);
993
994                 if (cur.result().dispatched())
995                         cur.clearSelection();
996
997                 break;
998         }
999
1000         default:
1001                 updateFlags = Update::None;
1002         }
1003
1004         return updateFlags;
1005 }
1006
1007
1008 docstring const BufferView::requestSelection()
1009 {
1010         if (!buffer_)
1011                 return docstring();
1012
1013         Cursor & cur = cursor_;
1014
1015         if (!cur.selection()) {
1016                 xsel_cache_.set = false;
1017                 return docstring();
1018         }
1019
1020         if (!xsel_cache_.set ||
1021             cur.top() != xsel_cache_.cursor ||
1022             cur.anchor_.top() != xsel_cache_.anchor)
1023         {
1024                 xsel_cache_.cursor = cur.top();
1025                 xsel_cache_.anchor = cur.anchor_.top();
1026                 xsel_cache_.set = cur.selection();
1027                 return cur.selectionAsString(false);
1028         }
1029         return docstring();
1030 }
1031
1032
1033 void BufferView::clearSelection()
1034 {
1035         if (buffer_) {
1036                 cursor_.clearSelection();
1037                 // Clear the selection buffer. Otherwise a subsequent
1038                 // middle-mouse-button paste would use the selection buffer,
1039                 // not the more current external selection.
1040                 cap::clearSelection();
1041                 xsel_cache_.set = false;
1042                 // The buffer did not really change, but this causes the
1043                 // redraw we need because we cleared the selection above.
1044                 buffer_->changed();
1045         }
1046 }
1047
1048
1049 void BufferView::workAreaResize(int width, int height)
1050 {
1051         // Update from work area
1052         width_ = width;
1053         height_ = height;
1054
1055         // The complete text metrics will be redone.
1056         text_metrics_.clear();
1057
1058         if (buffer_)
1059                 resize();
1060 }
1061
1062
1063 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1064 {
1065         pit_type pit = text.getPitNearY(*this, y);
1066         BOOST_ASSERT(pit != -1);
1067         Paragraph const & par = text.getPar(pit);
1068
1069         LYXERR(Debug::DEBUG)
1070                 << BOOST_CURRENT_FUNCTION
1071                 << ": x: " << x
1072                 << " y: " << y
1073                 << "  pit: " << pit
1074                 << endl;
1075         InsetList::const_iterator iit = par.insetlist.begin();
1076         InsetList::const_iterator iend = par.insetlist.end();
1077         for (; iit != iend; ++iit) {
1078                 Inset * const inset = iit->inset;
1079                 if (inset->covers(*this, x, y)) {
1080                         if (!inset->descendable())
1081                                 // No need to go further down if the inset is not
1082                                 // descendable.
1083                                 return inset;
1084
1085                         size_t cell_number = inset->nargs();
1086                         // Check all the inner cell.
1087                         for (size_t i = 0; i != cell_number; ++i) {
1088                                 Text const * inner_text = inset->getText(i);
1089                                 if (inner_text) {
1090                                         // Try deeper.
1091                                         Inset const * inset_deeper =
1092                                                 getCoveringInset(*inner_text, x, y);
1093                                         if (inset_deeper)
1094                                                 return inset_deeper;
1095                                 }
1096                         }
1097
1098                         LYXERR(Debug::DEBUG)
1099                                 << BOOST_CURRENT_FUNCTION
1100                                 << ": Hit inset: " << inset << endl;
1101                         return inset;
1102                 }
1103         }
1104         LYXERR(Debug::DEBUG)
1105                 << BOOST_CURRENT_FUNCTION
1106                 << ": No inset hit. " << endl;
1107         return 0;
1108 }
1109
1110
1111 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1112 {
1113         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1114
1115         // This is only called for mouse related events including
1116         // LFUN_FILE_OPEN generated by drag-and-drop.
1117         FuncRequest cmd = cmd0;
1118
1119         // E.g. Qt mouse press when no buffer
1120         if (!buffer_)
1121                 return false;
1122
1123         Cursor cur(*this);
1124         cur.push(buffer_->inset());
1125         cur.selection() = cursor_.selection();
1126
1127         // Either the inset under the cursor or the
1128         // surrounding Text will handle this event.
1129
1130         // make sure we stay within the screen...
1131         cmd.y = min(max(cmd.y, -1), height_);
1132
1133         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1134
1135                 // Get inset under mouse, if there is one.
1136                 Inset const * covering_inset =
1137                         getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1138                 if (covering_inset == last_inset_)
1139                         // Same inset, no need to do anything...
1140                         return false;
1141
1142                 bool need_redraw = false;
1143                 // const_cast because of setMouseHover().
1144                 Inset * inset = const_cast<Inset *>(covering_inset);
1145                 if (last_inset_)
1146                         // Remove the hint on the last hovered inset (if any).
1147                         need_redraw |= last_inset_->setMouseHover(false);
1148                 if (inset)
1149                         // Highlighted the newly hovered inset (if any).
1150                         need_redraw |= inset->setMouseHover(true);
1151                 last_inset_ = inset;
1152
1153                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1154                 // not expose the button for redraw. We adjust here the metrics dimension
1155                 // to enable a full redraw.
1156                 // FIXME: It is possible to redraw only the area around the button!
1157                 if (need_redraw
1158                         && metrics_info_.update_strategy == SingleParUpdate) {
1159                         // FIXME: It should be possible to redraw only the area around
1160                         // the button by doing this:
1161                         //
1162                         //metrics_info_.singlepar = false;
1163                         //metrics_info_.y1 = ymin of button;
1164                         //metrics_info_.y2 = ymax of button;
1165                         //
1166                         // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1167                         // between background updates and text updates. So we use the hammer
1168                         // solution for now. We could also avoid the updateMetrics() below
1169                         // by using the first and last pit of the CoordCache. Have a look
1170                         // at Text::getPitNearY() to see what I mean.
1171                         //
1172                         //metrics_info_.pit1 = first pit of CoordCache;
1173                         //metrics_info_.pit2 = last pit of CoordCache;
1174                         //metrics_info_.singlepar = false;
1175                         //metrics_info_.y1 = 0;
1176                         //metrics_info_.y2 = height_;
1177                         //
1178                         updateMetrics(false);
1179                 }
1180
1181                 // This event (moving without mouse click) is not passed further.
1182                 // This should be changed if it is further utilized.
1183                 return need_redraw;
1184         }
1185
1186         // Build temporary cursor.
1187         Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1188
1189         // Put anchor at the same position.
1190         cur.resetAnchor();
1191
1192         // Try to dispatch to an non-editable inset near this position
1193         // via the temp cursor. If the inset wishes to change the real
1194         // cursor it has to do so explicitly by using
1195         //  cur.bv().cursor() = cur;  (or similar)
1196         if (inset) {
1197                 inset->dispatch(cur, cmd);
1198         }
1199
1200         // Now dispatch to the temporary cursor. If the real cursor should
1201         // be modified, the inset's dispatch has to do so explicitly.
1202         if (!cur.result().dispatched())
1203                 cur.dispatch(cmd);
1204
1205         // Redraw if requested and necessary.
1206         if (cur.result().dispatched() && cur.result().update())
1207                 return update(cur.result().update());
1208
1209         return false;
1210 }
1211
1212
1213 void BufferView::scroll(int /*lines*/)
1214 {
1215 //      if (!buffer_)
1216 //              return;
1217 //
1218 //      Text const * t = &buffer_->text();
1219 //      int const line_height = defaultRowHeight();
1220 //
1221 //      // The new absolute coordinate
1222 //      int new_top_y = top_y() + lines * line_height;
1223 //
1224 //      // Restrict to a valid value
1225 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1226 //      new_top_y = std::max(0, new_top_y);
1227 //
1228 //      scrollDocView(new_top_y);
1229 //
1230 }
1231
1232
1233 void BufferView::setCursorFromRow(int row)
1234 {
1235         int tmpid = -1;
1236         int tmppos = -1;
1237
1238         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1239
1240         if (tmpid == -1)
1241                 buffer_->text().setCursor(cursor_, 0, 0);
1242         else
1243                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1244 }
1245
1246
1247 void BufferView::gotoLabel(docstring const & label)
1248 {
1249         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1250                 vector<docstring> labels;
1251                 it->getLabelList(*buffer_, labels);
1252                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1253                         setCursor(it);
1254                         update();
1255                         return;
1256                 }
1257         }
1258 }
1259
1260
1261 TextMetrics const & BufferView::textMetrics(Text const * t) const
1262 {
1263         return const_cast<BufferView *>(this)->textMetrics(t);
1264 }
1265
1266
1267 TextMetrics & BufferView::textMetrics(Text const * t)
1268 {
1269         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1270         if (tmc_it == text_metrics_.end()) {
1271                 tmc_it = text_metrics_.insert(
1272                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1273         }
1274         return tmc_it->second;
1275 }
1276
1277
1278 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1279                 pit_type pit) const
1280 {
1281         return textMetrics(t).parMetrics(pit);
1282 }
1283
1284
1285 int BufferView::workHeight() const
1286 {
1287         return height_;
1288 }
1289
1290
1291 void BufferView::setCursor(DocIterator const & dit)
1292 {
1293         size_t const n = dit.depth();
1294         for (size_t i = 0; i < n; ++i)
1295                 dit[i].inset().edit(cursor_, true);
1296
1297         cursor_.setCursor(dit);
1298         cursor_.selection() = false;
1299 }
1300
1301
1302 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1303 {
1304         // Would be wrong to delete anything if we have a selection.
1305         if (cur.selection())
1306                 return false;
1307
1308         bool need_anchor_change = false;
1309         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1310                 need_anchor_change);
1311
1312         if (need_anchor_change)
1313                 cur.resetAnchor();
1314
1315         if (!changed)
1316                 return false;
1317
1318         updateLabels(*buffer_);
1319
1320         updateMetrics(false);
1321         buffer_->changed();
1322         return true;
1323 }
1324
1325
1326 bool BufferView::mouseSetCursor(Cursor & cur)
1327 {
1328         BOOST_ASSERT(&cur.bv() == this);
1329
1330         // Has the cursor just left the inset?
1331         bool badcursor = false;
1332         bool leftinset = (&cursor_.inset() != &cur.inset());
1333         if (leftinset)
1334                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1335
1336         // do the dEPM magic if needed
1337         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1338         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1339         // the leftinset bool would not be necessary (badcursor instead).
1340         bool update = leftinset;
1341         if (!badcursor && cursor_.inTexted())
1342                 update |= checkDepm(cur, cursor_);
1343
1344         // if the cursor was in an empty script inset and the new
1345         // position is in the nucleus of the inset, notifyCursorLeaves
1346         // will kill the script inset itself. So we check all the
1347         // elements of the cursor to make sure that they are correct.
1348         // For an example, see bug 2933:
1349         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1350         // The code below could maybe be moved to a DocIterator method.
1351         //lyxerr << "cur before " << cur <<std::endl;
1352         DocIterator dit(cur.inset());
1353         dit.push_back(cur.bottom());
1354         size_t i = 1;
1355         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1356                 dit.push_back(cur[i]);
1357                 ++i;
1358         }
1359         //lyxerr << "5 cur after" << dit <<std::endl;
1360
1361         cursor_.setCursor(dit);
1362         cursor_.boundary(cur.boundary());
1363         cursor_.clearSelection();
1364         finishUndo();
1365         return update;
1366 }
1367
1368
1369 void BufferView::putSelectionAt(DocIterator const & cur,
1370                                 int length, bool backwards)
1371 {
1372         cursor_.clearSelection();
1373
1374         setCursor(cur);
1375
1376         if (length) {
1377                 if (backwards) {
1378                         cursor_.pos() += length;
1379                         cursor_.setSelection(cursor_, -length);
1380                 } else
1381                         cursor_.setSelection(cursor_, length);
1382                 cap::saveSelection(cursor_);
1383         }
1384 }
1385
1386
1387 Cursor & BufferView::cursor()
1388 {
1389         return cursor_;
1390 }
1391
1392
1393 Cursor const & BufferView::cursor() const
1394 {
1395         return cursor_;
1396 }
1397
1398
1399 pit_type BufferView::anchor_ref() const
1400 {
1401         return anchor_ref_;
1402 }
1403
1404
1405 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1406 {
1407         return metrics_info_;
1408 }
1409
1410
1411 // FIXME: We should split-up updateMetrics() for the singlepar case.
1412 void BufferView::updateMetrics(bool singlepar)
1413 {
1414         Text & buftext = buffer_->text();
1415         TextMetrics & tm = textMetrics(&buftext);
1416         pit_type size = int(buftext.paragraphs().size());
1417
1418         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1419                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1420                 offset_ref_ = 0;
1421         }
1422
1423         // If the paragraph metrics has changed, we can not
1424         // use the singlepar optimisation.
1425         if (singlepar
1426                 // In Single Paragraph mode, rebreak only
1427                 // the (main text, not inset!) paragraph containing the cursor.
1428                 // (if this paragraph contains insets etc., rebreaking will
1429                 // recursively descend)
1430                 && tm.redoParagraph(cursor_.bottom().pit()))
1431                 singlepar = false;
1432
1433         pit_type const pit = anchor_ref_;
1434         int pit1 = pit;
1435         int pit2 = pit;
1436         size_t const npit = buftext.paragraphs().size();
1437
1438         // Rebreak anchor paragraph.
1439         if (!singlepar)
1440                 tm.redoParagraph(pit);
1441
1442         // Clear out the position cache in case of full screen redraw.
1443         if (!singlepar)
1444                 coord_cache_.clear();
1445
1446         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1447
1448         // Redo paragraphs above anchor if necessary.
1449         int y1 = y0;
1450         while (y1 > 0 && pit1 > 0) {
1451                 y1 -= tm.parMetrics(pit1).ascent();
1452                 --pit1;
1453                 if (!singlepar)
1454                         tm.redoParagraph(pit1);
1455                 y1 -= tm.parMetrics(pit1).descent();
1456         }
1457
1458
1459         // Take care of ascent of first line
1460         y1 -= tm.parMetrics(pit1).ascent();
1461
1462         // Normalize anchor for next time
1463         anchor_ref_ = pit1;
1464         offset_ref_ = -y1;
1465
1466         // Grey at the beginning is ugly
1467         if (pit1 == 0 && y1 > 0) {
1468                 y0 -= y1;
1469                 y1 = 0;
1470                 anchor_ref_ = 0;
1471         }
1472
1473         // Redo paragraphs below the anchor if necessary.
1474         int y2 = y0;
1475         while (y2 < height_ && pit2 < int(npit) - 1) {
1476                 y2 += tm.parMetrics(pit2).descent();
1477                 ++pit2;
1478                 if (!singlepar)
1479                         tm.redoParagraph(pit2);
1480                 y2 += tm.parMetrics(pit2).ascent();
1481         }
1482
1483         // Take care of descent of last line
1484         y2 += tm.parMetrics(pit2).descent();
1485
1486         // The coordinates of all these paragraphs are correct, cache them
1487         int y = y1;
1488         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1489         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1490                 ParagraphMetrics const & pm = tm.parMetrics(pit);
1491                 y += pm.ascent();
1492                 parPos[pit] = Point(0, y);
1493                 if (singlepar && pit == cursor_.bottom().pit()) {
1494                         // In Single Paragraph mode, collect here the
1495                         // y1 and y2 of the (one) paragraph the cursor is in
1496                         y1 = y - pm.ascent();
1497                         y2 = y + pm.descent();
1498                 }
1499                 y += pm.descent();
1500         }
1501
1502         if (singlepar) {
1503                 // collect cursor paragraph iter bounds
1504                 pit1 = cursor_.bottom().pit();
1505                 pit2 = cursor_.bottom().pit();
1506         }
1507
1508         LYXERR(Debug::DEBUG)
1509                 << BOOST_CURRENT_FUNCTION
1510                 << " y1: " << y1
1511                 << " y2: " << y2
1512                 << " pit1: " << pit1
1513                 << " pit2: " << pit2
1514                 << " npit: " << npit
1515                 << " singlepar: " << singlepar
1516                 << "size: " << size
1517                 << endl;
1518
1519         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1520                 singlepar? SingleParUpdate: FullScreenUpdate, size);
1521
1522         if (lyxerr.debugging(Debug::WORKAREA)) {
1523                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1524                 coord_cache_.dump();
1525         }
1526 }
1527
1528
1529 void BufferView::menuInsertLyXFile(string const & filenm)
1530 {
1531         BOOST_ASSERT(cursor_.inTexted());
1532         string filename = filenm;
1533
1534         if (filename.empty()) {
1535                 // Launch a file browser
1536                 // FIXME UNICODE
1537                 string initpath = lyxrc.document_path;
1538
1539                 if (buffer_) {
1540                         string const trypath = buffer_->filePath();
1541                         // If directory is writeable, use this as default.
1542                         if (isDirWriteable(FileName(trypath)))
1543                                 initpath = trypath;
1544                 }
1545
1546                 // FIXME UNICODE
1547                 FileDialog fileDlg(_("Select LyX document to insert"),
1548                         LFUN_FILE_INSERT,
1549                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1550                         make_pair(_("Examples|#E#e"),
1551                                     from_utf8(addPath(package().system_support().absFilename(),
1552                                     "examples"))));
1553
1554                 FileDialog::Result result =
1555                         fileDlg.open(from_utf8(initpath),
1556                                      FileFilterList(_("LyX Documents (*.lyx)")),
1557                                      docstring());
1558
1559                 if (result.first == FileDialog::Later)
1560                         return;
1561
1562                 // FIXME UNICODE
1563                 filename = to_utf8(result.second);
1564
1565                 // check selected filename
1566                 if (filename.empty()) {
1567                         // emit message signal.
1568                         message(_("Canceled."));
1569                         return;
1570                 }
1571         }
1572
1573         // Get absolute path of file and add ".lyx"
1574         // to the filename if necessary
1575         filename = fileSearch(string(), filename, "lyx").absFilename();
1576
1577         docstring const disp_fn = makeDisplayPath(filename);
1578         // emit message signal.
1579         message(bformat(_("Inserting document %1$s..."), disp_fn));
1580
1581         docstring res;
1582         Buffer buf("", false);
1583         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1584                 ErrorList & el = buffer_->errorList("Parse");
1585                 // Copy the inserted document error list into the current buffer one.
1586                 el = buf.errorList("Parse");
1587                 recordUndo(cursor_);
1588                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1589                                              buf.params().textclass, el);
1590                 res = _("Document %1$s inserted.");
1591         } else
1592                 res = _("Could not insert document %1$s");
1593
1594         // emit message signal.
1595         message(bformat(res, disp_fn));
1596         buffer_->errors("Parse");
1597         resize();
1598 }
1599
1600 } // namespace lyx