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