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