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