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