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