3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
34 #include "insetiterator.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
41 #include "lyxlayout.h"
43 #include "lyxtextclass.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
62 #include "frontends/Alert.h"
63 #include "frontends/Clipboard.h"
64 #include "frontends/Dialogs.h"
65 #include "frontends/FileDialog.h"
66 #include "frontends/font_metrics.h"
67 #include "frontends/Gui.h"
68 #include "frontends/LyXView.h"
69 #include "frontends/Selection.h"
71 #include "graphics/Previews.h"
73 #include "support/convert.h"
74 #include "support/filefilterlist.h"
75 #include "support/filetools.h"
76 #include "support/package.h"
77 #include "support/types.h"
79 #include <boost/bind.hpp>
80 #include <boost/current_function.hpp>
86 using lyx::frontend::Clipboard;
87 using lyx::frontend::Gui;
92 using lyx::support::addPath;
93 using lyx::support::bformat;
94 using lyx::support::FileFilterList;
95 using lyx::support::fileSearch;
96 using lyx::support::isDirWriteable;
97 using lyx::support::makeDisplayPath;
98 using lyx::support::makeAbsPath;
99 using lyx::support::package;
103 using std::istringstream;
105 using std::make_pair;
108 using std::mem_fun_ref;
112 extern BufferList bufferlist;
117 unsigned int const saved_positions_num = 20;
120 /// Return an inset of this class if it exists at the current cursor position
122 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
125 DocIterator it = cur;
126 if (it.nextInset() &&
127 it.nextInset()->lyxCode() == code) {
128 inset = static_cast<T*>(it.nextInset());
136 BufferView::BufferView(LyXView * owner)
137 : owner_(owner), buffer_(0), wh_(0),
139 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
142 xsel_cache_.set = false;
144 saved_positions.resize(saved_positions_num);
145 // load saved bookmarks
146 lyx::Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
147 for (lyx::Session::BookmarkList::iterator bm = bmList.begin();
148 bm != bmList.end(); ++bm)
149 if (bm->get<0>() < saved_positions_num)
150 saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
151 // and then clear them
154 intl_->initKeyMapper(lyxrc.use_kbmap);
158 BufferView::~BufferView()
163 Buffer * BufferView::buffer() const
169 LyXView * BufferView::owner() const
175 void BufferView::setBuffer(Buffer * b)
177 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
178 << "[ b = " << b << "]" << endl;
181 // Save the actual cursor position and anchor inside the
182 // buffer so that it can be restored in case we rechange
183 // to this buffer later on.
184 buffer_->saveCursor(cursor_.selectionBegin(),
185 cursor_.selectionEnd());
186 // current buffer is going to be switched-off, save cursor pos
187 LyX::ref().session().saveFilePosition(buffer_->fileName(),
188 boost::tie(cursor_.pit(), cursor_.pos()) );
191 // If we're quitting lyx, don't bother updating stuff
197 // If we are closing current buffer, switch to the first in
200 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
201 << " No Buffer!" << endl;
202 // We are closing the buffer, use the first buffer as current
203 buffer_ = bufferlist.first();
205 // Set current buffer
210 cursor_ = LCursor(*this);
215 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
216 << "Buffer addr: " << buffer_ << endl;
217 cursor_.push(buffer_->inset());
218 cursor_.resetAnchor();
219 buffer_->text().init(this);
220 buffer_->text().setCurrentFont(cursor_);
221 if (buffer_->getCursor().size() > 0 &&
222 buffer_->getAnchor().size() > 0)
224 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
225 cursor_.resetAnchor();
226 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
227 cursor_.setSelection();
233 if (buffer_ && lyx::graphics::Previews::status() != LyXRC::PREVIEW_OFF)
234 lyx::graphics::Previews::get().generateBufferPreviews(*buffer_);
238 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
240 // Get absolute path of file and add ".lyx"
241 // to the filename if necessary
242 string s = fileSearch(string(), filename, "lyx");
244 bool const found = !s.empty();
249 // File already open?
250 if (bufferlist.exists(s)) {
251 docstring const file = makeDisplayPath(s, 20);
252 docstring text = bformat(_("The document %1$s is already "
253 "loaded.\n\nDo you want to revert "
254 "to the saved version?"), file);
255 int const ret = Alert::prompt(_("Revert to saved document?"),
256 text, 0, 1, _("&Revert"), _("&Switch to document"));
259 setBuffer(bufferlist.getBuffer(s));
262 // FIXME: should be LFUN_REVERT
263 if (!bufferlist.close(bufferlist.getBuffer(s), false))
265 // Fall through to new load. (Asger)
271 b = bufferlist.newBuffer(s);
272 if (!::loadLyXFile(b, s)) {
273 bufferlist.release(b);
277 docstring text = bformat(_("The document %1$s does not yet "
278 "exist.\n\nDo you want to create "
279 "a new document?"), lyx::from_utf8(s));
280 int const ret = Alert::prompt(_("Create new document?"),
281 text, 0, 1, _("&Create"), _("Cancel"));
284 b = newFile(s, string(), true);
292 // Send the "errors" signal in case of parsing errors
295 // scroll to the position when the file was last closed
296 if (lyxrc.use_lastfilepos) {
299 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
300 // I am not sure how to separate the following part to a function
301 // so I will leave this to Lars.
303 // check pit since the document may be externally changed.
304 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
305 ParIterator it = b->par_iterator_begin();
306 ParIterator const end = b->par_iterator_end();
307 for (; it != end; ++it)
308 if (it.pit() == pit) {
309 // restored pos may be bigger than it->size
310 setCursor(makeDocIterator(it, min(pos, it->size())));
311 update(Update::FitCursor);
318 LyX::ref().session().addLastFile(b->fileName());
324 void BufferView::reload()
326 string const fn = buffer_->fileName();
327 if (bufferlist.close(buffer_, false))
332 void BufferView::resize()
337 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
339 buffer_->text().init(this);
345 bool BufferView::fitCursor()
347 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
348 LyXFont const font = cursor_.getFont();
349 int const asc = font_metrics::maxAscent(font);
350 int const des = font_metrics::maxDescent(font);
351 Point const p = bv_funcs::getPos(cursor_, cursor_.boundary());
352 if (p.y_ - asc >= 0 && p.y_ + des < height_)
360 bool BufferView::multiParSel()
362 if (!cursor_.selection())
364 bool ret = multiparsel_cache_;
365 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
366 // Either this, or previous selection spans paragraphs
367 return ret || multiparsel_cache_;
371 bool BufferView::update(Update::flags flags)
373 // This is close to a hot-path.
374 if (lyxerr.debugging(Debug::DEBUG)) {
376 << BOOST_CURRENT_FUNCTION
377 << "[fitcursor = " << (flags & Update::FitCursor)
378 << ", forceupdate = " << (flags & Update::Force)
379 << ", singlepar = " << (flags & Update::SinglePar)
380 << "] buffer: " << buffer_ << endl;
383 // Check needed to survive LyX startup
387 // Update macro store
388 buffer_->buildMacros();
390 // First drawing step
391 updateMetrics(flags & Update::SinglePar);
393 // The second drawing step is done in WorkArea::redraw() if needed.
394 bool const need_second_step =
395 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
396 && (fitCursor() || multiParSel());
398 return need_second_step;
402 void BufferView::updateScrollbar()
405 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
406 << " no text in updateScrollbar" << endl;
407 scrollbarParameters_.reset();
411 LyXText & t = buffer_->text();
412 int const parsize = int(t.paragraphs().size() - 1);
413 if (anchor_ref_ > parsize) {
414 anchor_ref_ = parsize;
419 << BOOST_CURRENT_FUNCTION
420 << " Updating scrollbar: height: " << t.paragraphs().size()
421 << " curr par: " << cursor_.bottom().pit()
422 << " default height " << defaultRowHeight() << endl;
424 // It would be better to fix the scrollbar to understand
425 // values in [0..1] and divide everything by wh
427 // estimated average paragraph height:
430 int h = t.getPar(anchor_ref_).height();
432 // Normalize anchor/offset (MV):
433 while (offset_ref_ > h && anchor_ref_ < parsize) {
436 h = t.getPar(anchor_ref_).height();
438 // Look at paragraph heights on-screen
441 for (lyx::pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
444 int const h2 = t.getPar(pit).height();
448 int const hav = sumh / nh;
449 // More realistic average paragraph height
453 scrollbarParameters_.height = (parsize + 1) * wh_;
454 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
455 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
459 ScrollbarParameters const & BufferView::scrollbarParameters() const
461 return scrollbarParameters_;
465 void BufferView::scrollDocView(int value)
467 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
468 << "[ value = " << value << "]" << endl;
473 LyXText & t = buffer_->text();
475 float const bar = value / float(wh_ * t.paragraphs().size());
477 anchor_ref_ = int(bar * t.paragraphs().size());
478 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
479 anchor_ref_ = int(t.paragraphs().size()) - 1;
480 t.redoParagraph(anchor_ref_);
481 int const h = t.getPar(anchor_ref_).height();
482 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
486 void BufferView::setCursorFromScrollbar()
488 LyXText & t = buffer_->text();
490 int const height = 2 * defaultRowHeight();
491 int const first = height;
492 int const last = height_ - height;
493 LCursor & cur = cursor_;
495 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
498 case bv_funcs::CUR_ABOVE:
499 t.setCursorFromCoordinates(cur, 0, first);
500 cur.clearSelection();
502 case bv_funcs::CUR_BELOW:
503 t.setCursorFromCoordinates(cur, 0, last);
504 cur.clearSelection();
506 case bv_funcs::CUR_INSIDE:
507 int const y = bv_funcs::getPos(cur, cur.boundary()).y_;
508 int const newy = min(last, max(y, first));
510 cur.reset(buffer_->inset());
511 t.setCursorFromCoordinates(cur, 0, newy);
517 Change const BufferView::getCurrentChange()
519 if (!buffer_->params().tracking_changes || !cursor_.selection())
520 return Change(Change::UNCHANGED);
522 DocIterator dit = cursor_.selectionBegin();
523 return dit.paragraph().lookupChange(dit.pos());
527 void BufferView::savePosition(unsigned int i)
529 if (i >= saved_positions_num)
531 BOOST_ASSERT(cursor_.inTexted());
532 saved_positions[i] = Position(buffer_->fileName(),
533 cursor_.paragraph().id(),
536 // emit message signal.
537 message(bformat(_("Saved bookmark %1$d"), i));
541 void BufferView::restorePosition(unsigned int i)
543 if (i >= saved_positions_num)
546 string const fname = saved_positions[i].filename;
548 cursor_.clearSelection();
550 if (fname != buffer_->fileName()) {
552 if (bufferlist.exists(fname))
553 b = bufferlist.getBuffer(fname);
555 b = bufferlist.newBuffer(fname);
556 // Don't ask, just load it
557 ::loadLyXFile(b, fname);
563 ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
564 if (par == buffer_->par_iterator_end())
567 setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
570 // emit message signal.
571 message(bformat(_("Moved to bookmark %1$d"), i));
575 bool BufferView::isSavedPosition(unsigned int i)
577 return i < saved_positions_num && !saved_positions[i].filename.empty();
580 void BufferView::saveSavedPositions()
582 // save bookmarks. It is better to use the pit interface
583 // but I do not know how to effectively convert between
585 for (unsigned int i=1; i < saved_positions_num; ++i) {
586 if ( isSavedPosition(i) )
587 LyX::ref().session().saveBookmark( boost::tie(
589 saved_positions[i].filename,
590 saved_positions[i].par_id,
591 saved_positions[i].par_pos) );
595 void BufferView::switchKeyMap()
597 if (!lyxrc.rtl_support)
600 if (getLyXText()->real_current_font.isRightToLeft()) {
601 if (intl_->keymap == Intl::PRIMARY)
604 if (intl_->keymap == Intl::SECONDARY)
610 int BufferView::workWidth() const
616 void BufferView::center()
618 CursorSlice & bot = cursor_.bottom();
619 lyx::pit_type const pit = bot.pit();
620 bot.text()->redoParagraph(pit);
621 Paragraph const & par = bot.text()->paragraphs()[pit];
623 offset_ref_ = bv_funcs::coordOffset(cursor_, cursor_.boundary()).y_
624 + par.ascent() - height_ / 2;
628 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
632 switch (cmd.action) {
635 flag.enabled(!buffer_->undostack().empty());
638 flag.enabled(!buffer_->redostack().empty());
640 case LFUN_FILE_INSERT:
641 case LFUN_FILE_INSERT_ASCII_PARA:
642 case LFUN_FILE_INSERT_ASCII:
643 case LFUN_BOOKMARK_SAVE:
644 // FIXME: Actually, these LFUNS should be moved to LyXText
645 flag.enabled(cursor_.inTexted());
647 case LFUN_FONT_STATE:
648 case LFUN_LABEL_INSERT:
649 case LFUN_PARAGRAPH_GOTO:
650 // FIXME handle non-trivially
651 case LFUN_OUTLINE_UP:
652 case LFUN_OUTLINE_DOWN:
653 case LFUN_OUTLINE_IN:
654 case LFUN_OUTLINE_OUT:
656 case LFUN_REFERENCE_NEXT:
658 case LFUN_WORD_REPLACE:
661 case LFUN_MARK_TOGGLE:
662 case LFUN_SCREEN_RECENTER:
663 case LFUN_BIBTEX_DATABASE_ADD:
664 case LFUN_BIBTEX_DATABASE_DEL:
665 case LFUN_WORDS_COUNT:
666 case LFUN_NEXT_INSET_TOGGLE:
670 case LFUN_LABEL_GOTO: {
671 flag.enabled(!cmd.argument().empty()
672 || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
676 case LFUN_BOOKMARK_GOTO:
677 flag.enabled(isSavedPosition(convert<unsigned int>(lyx::to_utf8(cmd.argument()))));
679 case LFUN_CHANGES_TRACK:
681 flag.setOnOff(buffer_->params().tracking_changes);
684 case LFUN_CHANGES_OUTPUT: {
685 OutputParams runparams;
686 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
687 flag.enabled(buffer_ && buffer_->params().tracking_changes
688 && features.isAvailable("dvipost"));
689 flag.setOnOff(buffer_->params().output_changes);
693 case LFUN_CHANGES_MERGE:
694 case LFUN_CHANGE_ACCEPT: // what about these two
695 case LFUN_CHANGE_REJECT: // what about these two
696 case LFUN_ALL_CHANGES_ACCEPT:
697 case LFUN_ALL_CHANGES_REJECT:
698 flag.enabled(buffer_ && buffer_->params().tracking_changes);
701 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
702 flag.setOnOff(buffer_->params().compressed);
714 bool BufferView::dispatch(FuncRequest const & cmd)
716 //lyxerr << BOOST_CURRENT_FUNCTION
717 // << [ cmd = " << cmd << "]" << endl;
719 // Make sure that the cached BufferView is correct.
720 lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
721 << " action[" << cmd.action << ']'
722 << " arg[" << lyx::to_utf8(cmd.argument()) << ']'
723 << " x[" << cmd.x << ']'
724 << " y[" << cmd.y << ']'
725 << " button[" << cmd.button() << ']'
728 LCursor & cur = cursor_;
730 switch (cmd.action) {
734 cur.message(_("Undo"));
735 cur.clearSelection();
736 if (!textUndo(*this))
737 cur.message(_("No further undo information"));
745 cur.message(_("Redo"));
746 cur.clearSelection();
747 if (!textRedo(*this))
748 cur.message(_("No further redo information"));
754 case LFUN_FILE_INSERT:
755 // FIXME: We don't know the encoding of filenames
756 menuInsertLyXFile(lyx::to_utf8(cmd.argument()));
759 case LFUN_FILE_INSERT_ASCII_PARA:
760 // FIXME: We don't know the encoding of filenames
761 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), true);
764 case LFUN_FILE_INSERT_ASCII:
765 // FIXME: We don't know the encoding of filenames
766 insertAsciiFile(this, lyx::to_utf8(cmd.argument()), false);
769 case LFUN_FONT_STATE:
770 cur.message(lyx::from_utf8(cur.currentState()));
773 case LFUN_BOOKMARK_SAVE:
774 savePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
777 case LFUN_BOOKMARK_GOTO:
778 restorePosition(convert<unsigned int>(lyx::to_utf8(cmd.argument())));
781 case LFUN_LABEL_GOTO: {
782 string label = lyx::to_utf8(cmd.argument());
785 getInsetByCode<InsetRef>(cursor_,
786 InsetBase::REF_CODE);
788 label = inset->getContents();
798 case LFUN_PARAGRAPH_GOTO: {
799 int const id = convert<int>(lyx::to_utf8(cmd.argument()));
800 ParIterator par = buffer_->getParFromID(id);
801 if (par == buffer_->par_iterator_end()) {
802 lyxerr[Debug::INFO] << "No matching paragraph found! ["
803 << id << ']' << endl;
806 lyxerr[Debug::INFO] << "Paragraph " << par->id()
807 << " found." << endl;
811 setCursor(makeDocIterator(par, 0));
818 case LFUN_OUTLINE_UP:
819 lyx::toc::outline(lyx::toc::Up, cursor_);
820 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
821 updateLabels(*buffer_);
823 case LFUN_OUTLINE_DOWN:
824 lyx::toc::outline(lyx::toc::Down, cursor_);
825 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
826 updateLabels(*buffer_);
828 case LFUN_OUTLINE_IN:
829 lyx::toc::outline(lyx::toc::In, cursor_);
830 updateLabels(*buffer_);
832 case LFUN_OUTLINE_OUT:
833 lyx::toc::outline(lyx::toc::Out, cursor_);
834 updateLabels(*buffer_);
838 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
841 case LFUN_REFERENCE_NEXT: {
842 vector<InsetBase_code> tmp;
843 tmp.push_back(InsetBase::LABEL_CODE);
844 tmp.push_back(InsetBase::REF_CODE);
845 bv_funcs::gotoInset(this, tmp, true);
849 case LFUN_CHANGES_TRACK:
853 case LFUN_CHANGES_OUTPUT: {
854 bool const state = buffer_->params().output_changes;
855 buffer_->params().output_changes = !state;
859 case LFUN_CHANGES_MERGE:
860 if (lyx::find::findNextChange(this))
861 owner_->getDialogs().show("changes");
864 case LFUN_ALL_CHANGES_ACCEPT: {
865 cursor_.reset(buffer_->inset());
867 #warning FIXME changes
869 while (lyx::find::findNextChange(this))
870 getLyXText()->acceptChange(cursor_);
875 case LFUN_ALL_CHANGES_REJECT: {
876 cursor_.reset(buffer_->inset());
878 #warning FIXME changes
880 while (lyx::find::findNextChange(this))
881 getLyXText()->rejectChange(cursor_);
886 lyx::find::find(this, cmd);
889 case LFUN_WORD_REPLACE:
890 lyx::find::replace(this, cmd);
894 cur.clearSelection();
896 cur.message(lyx::from_utf8(N_("Mark off")));
900 cur.clearSelection();
903 cur.message(lyx::from_utf8(N_("Mark on")));
906 case LFUN_MARK_TOGGLE:
907 cur.clearSelection();
910 cur.message(lyx::from_utf8(N_("Mark removed")));
913 cur.message(lyx::from_utf8(N_("Mark set")));
918 case LFUN_SCREEN_RECENTER:
922 case LFUN_BIBTEX_DATABASE_ADD: {
923 LCursor tmpcur = cursor_;
924 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
925 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
926 InsetBase::BIBTEX_CODE);
928 if (inset->addDatabase(lyx::to_utf8(cmd.argument())))
929 buffer_->updateBibfilesCache();
934 case LFUN_BIBTEX_DATABASE_DEL: {
935 LCursor tmpcur = cursor_;
936 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
937 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
938 InsetBase::BIBTEX_CODE);
940 if (inset->delDatabase(lyx::to_utf8(cmd.argument())))
941 buffer_->updateBibfilesCache();
946 case LFUN_WORDS_COUNT: {
947 DocIterator from, to;
948 if (cur.selection()) {
949 from = cur.selectionBegin();
950 to = cur.selectionEnd();
952 from = doc_iterator_begin(buffer_->inset());
953 to = doc_iterator_end(buffer_->inset());
955 int const count = countWords(from, to);
959 message = bformat(_("%1$d words in selection."),
962 message = bformat(_("%1$d words in document."),
967 message = _("One word in selection.");
969 message = _("One word in document.");
972 Alert::information(_("Count words"), message);
976 case LFUN_BUFFER_TOGGLE_COMPRESSION:
977 // turn compression on/off
978 buffer_->params().compressed = !buffer_->params().compressed;
981 case LFUN_NEXT_INSET_TOGGLE: {
982 // this is the real function we want to invoke
983 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
984 // if there is an inset at cursor, see whether it
986 InsetBase * inset = cur.nextInset();
987 if (inset && inset->isActive()) {
988 LCursor tmpcur = cur;
989 tmpcur.pushLeft(*inset);
990 inset->dispatch(tmpcur, tmpcmd);
991 if (tmpcur.result().dispatched()) {
995 // if it did not work, try the underlying inset.
996 if (!cur.result().dispatched())
997 cur.dispatch(tmpcmd);
999 if (cur.result().dispatched())
1000 cur.clearSelection();
1013 docstring const BufferView::requestSelection()
1018 LCursor & cur = cursor_;
1020 if (!cur.selection()) {
1021 xsel_cache_.set = false;
1025 if (!xsel_cache_.set ||
1026 cur.top() != xsel_cache_.cursor ||
1027 cur.anchor_.top() != xsel_cache_.anchor)
1029 xsel_cache_.cursor = cur.top();
1030 xsel_cache_.anchor = cur.anchor_.top();
1031 xsel_cache_.set = cur.selection();
1032 return cur.selectionAsString(false);
1038 void BufferView::clearSelection()
1041 cursor_.clearSelection();
1042 xsel_cache_.set = false;
1047 void BufferView::workAreaResize(int width, int height)
1049 bool const widthChange = width != width_;
1050 bool const heightChange = height != height_;
1052 // Update from work area
1056 if (buffer_ && widthChange) {
1057 // The WorkArea content needs a resize
1061 if (widthChange || heightChange)
1066 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1068 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1070 // This is only called for mouse related events including
1071 // LFUN_FILE_OPEN generated by drag-and-drop.
1072 FuncRequest cmd = cmd0;
1078 cur.push(buffer_->inset());
1079 cur.selection() = cursor_.selection();
1081 // Doesn't go through lyxfunc, so we need to update
1082 // the layout choice etc. ourselves
1084 // E.g. Qt mouse press when no buffer
1088 // Either the inset under the cursor or the
1089 // surrounding LyXText will handle this event.
1091 // Build temporary cursor.
1092 cmd.y = min(max(cmd.y, -1), height_);
1093 InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1094 //lyxerr << BOOST_CURRENT_FUNCTION
1095 // << " * hit inset at tip: " << inset << endl;
1096 //lyxerr << BOOST_CURRENT_FUNCTION
1097 // << " * created temp cursor:" << cur << endl;
1099 // Put anchor at the same position.
1102 // Try to dispatch to an non-editable inset near this position
1103 // via the temp cursor. If the inset wishes to change the real
1104 // cursor it has to do so explicitly by using
1105 // cur.bv().cursor() = cur; (or similar)
1107 inset->dispatch(cur, cmd);
1109 // Now dispatch to the temporary cursor. If the real cursor should
1110 // be modified, the inset's dispatch has to do so explicitly.
1111 if (!cur.result().dispatched())
1114 if (cur.result().dispatched()) {
1115 // Redraw if requested or necessary.
1116 if (cur.result().update())
1117 update(Update::FitCursor | Update::Force);
1119 update(Update::FitCursor | Update::MultiParSel);
1126 void BufferView::scroll(int lines)
1131 // LyXText const * t = &buffer_->text();
1132 // int const line_height = defaultRowHeight();
1134 // // The new absolute coordinate
1135 // int new_top_y = top_y() + lines * line_height;
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);
1141 // scrollDocView(new_top_y);
1143 // // Update the scrollbar.
1144 // workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1148 void BufferView::setCursorFromRow(int row)
1153 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1156 buffer_->text().setCursor(cursor_, 0, 0);
1158 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1162 void BufferView::gotoLabel(string const & label)
1164 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1165 vector<string> labels;
1166 it->getLabelList(*buffer_, labels);
1167 if (find(labels.begin(),labels.end(),label) != labels.end()) {
1176 LyXText * BufferView::getLyXText()
1178 LyXText * text = cursor_.innerText();
1184 LyXText const * BufferView::getLyXText() const
1186 LyXText const * text = cursor_.innerText();
1192 int BufferView::workHeight() const
1198 void BufferView::setCursor(DocIterator const & dit)
1200 size_t const n = dit.depth();
1201 for (size_t i = 0; i < n; ++i)
1202 dit[i].inset().edit(cursor_, true);
1204 cursor_.setCursor(dit);
1205 cursor_.selection() = false;
1209 void BufferView::mouseSetCursor(LCursor & cur)
1211 BOOST_ASSERT(&cur.bv() == this);
1213 // Has the cursor just left the inset?
1214 bool badcursor = false;
1215 if (&cursor_.inset() != &cur.inset())
1216 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1218 // do the dEPM magic if needed
1219 // FIXME: move this to InsetText::notifyCursorLeaves?
1220 if (!badcursor && cursor_.inTexted())
1221 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1224 cursor_.clearSelection();
1225 cursor_.setTargetX();
1231 void BufferView::putSelectionAt(DocIterator const & cur,
1232 int length, bool backwards)
1234 cursor_.clearSelection();
1240 cursor_.pos() += length;
1241 cursor_.setSelection(cursor_, -length);
1243 cursor_.setSelection(cursor_, length);
1248 LCursor & BufferView::cursor()
1254 LCursor const & BufferView::cursor() const
1260 lyx::pit_type BufferView::anchor_ref() const
1266 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1268 return metrics_info_;
1272 void BufferView::updateMetrics(bool singlepar)
1274 // Remove old position cache
1276 LyXText & buftext = buffer_->text();
1277 lyx::pit_type size = int(buftext.paragraphs().size());
1279 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1280 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1284 lyx::pit_type const pit = anchor_ref_;
1287 size_t const npit = buftext.paragraphs().size();
1289 // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1290 // the (main text, not inset!) paragraph containing the cursor.
1291 // (if this paragraph contains insets etc., rebreaking will
1292 // recursively descend)
1293 if (!singlepar || pit == cursor_.bottom().pit())
1294 buftext.redoParagraph(pit);
1295 int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1297 // Redo paragraphs above anchor if necessary; again, in Single Par
1298 // mode, only if we encounter the (main text) one having the cursor.
1300 while (y1 > 0 && pit1 > 0) {
1301 y1 -= buftext.getPar(pit1).ascent();
1303 if (!singlepar || pit1 == cursor_.bottom().pit())
1304 buftext.redoParagraph(pit1);
1305 y1 -= buftext.getPar(pit1).descent();
1309 // Take care of ascent of first line
1310 y1 -= buftext.getPar(pit1).ascent();
1312 // Normalize anchor for next time
1316 // Grey at the beginning is ugly
1317 if (pit1 == 0 && y1 > 0) {
1323 // Redo paragraphs below the anchor if necessary. Single par mode:
1324 // only the one containing the cursor if encountered.
1326 while (y2 < height_ && pit2 < int(npit) - 1) {
1327 y2 += buftext.getPar(pit2).descent();
1329 if (!singlepar || pit2 == cursor_.bottom().pit())
1330 buftext.redoParagraph(pit2);
1331 y2 += buftext.getPar(pit2).ascent();
1334 // Take care of descent of last line
1335 y2 += buftext.getPar(pit2).descent();
1337 // The coordinates of all these paragraphs are correct, cache them
1339 CoordCache::InnerParPosCache & parPos = theCoords.parPos()[&buftext];
1340 for (lyx::pit_type pit = pit1; pit <= pit2; ++pit) {
1341 Paragraph const & par = buftext.getPar(pit);
1343 parPos[pit] = Point(0, y);
1344 if (singlepar && pit == cursor_.bottom().pit()) {
1345 // In Single Paragraph mode, collect here the
1346 // y1 and y2 of the (one) paragraph the cursor is in
1347 y1 = y - par.ascent();
1348 y2 = y + par.descent();
1354 // collect cursor paragraph iter bounds
1355 pit1 = cursor_.bottom().pit();
1356 pit2 = cursor_.bottom().pit();
1359 lyxerr[Debug::DEBUG]
1360 << BOOST_CURRENT_FUNCTION
1363 << " pit1: " << pit1
1364 << " pit2: " << pit2
1365 << " npit: " << npit
1366 << " singlepar: " << singlepar
1370 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1374 void BufferView::menuInsertLyXFile(string const & filenm)
1376 BOOST_ASSERT(cursor_.inTexted());
1377 string filename = filenm;
1379 if (filename.empty()) {
1380 // Launch a file browser
1381 string initpath = lyxrc.document_path;
1384 string const trypath = buffer_->filePath();
1385 // If directory is writeable, use this as default.
1386 if (isDirWriteable(trypath))
1390 FileDialog fileDlg(lyx::to_utf8(_("Select LyX document to insert")),
1392 make_pair(string(lyx::to_utf8(_("Documents|#o#O"))),
1393 string(lyxrc.document_path)),
1394 make_pair(string(lyx::to_utf8(_("Examples|#E#e"))),
1395 string(addPath(package().system_support(), "examples"))));
1397 FileDialog::Result result =
1398 fileDlg.open(initpath,
1399 FileFilterList(lyx::to_utf8(_("LyX Documents (*.lyx)"))),
1402 if (result.first == FileDialog::Later)
1405 filename = result.second;
1407 // check selected filename
1408 if (filename.empty()) {
1409 // emit message signal.
1410 message(_("Canceled."));
1415 // Get absolute path of file and add ".lyx"
1416 // to the filename if necessary
1417 filename = fileSearch(string(), filename, "lyx");
1419 docstring const disp_fn = makeDisplayPath(filename);
1420 // emit message signal.
1421 message(bformat(_("Inserting document %1$s..."), disp_fn));
1424 Buffer buf("", false);
1425 if (::loadLyXFile(&buf, makeAbsPath(filename))) {
1426 ErrorList & el = buffer_->errorList("Parse");
1427 // Copy the inserted document error list into the current buffer one.
1428 el = buf.errorList("Parse");
1429 lyx::cap::pasteParagraphList(cursor_, buf.paragraphs(),
1430 buf.params().textclass, el);
1431 res = _("Document %1$s inserted.");
1433 res = _("Could not insert document %1$s");
1435 // emit message signal.
1436 message(bformat(res, disp_fn));
1437 buffer_->errors("Parse");
1442 void BufferView::trackChanges()
1444 bool const tracking = buffer_->params().tracking_changes;
1447 for_each(buffer_->par_iterator_begin(),
1448 buffer_->par_iterator_end(),
1449 bind(&Paragraph::trackChanges, _1, Change::UNCHANGED));
1450 buffer_->params().tracking_changes = true;
1452 // We cannot allow undos beyond the freeze point
1453 buffer_->undostack().clear();
1455 cursor_.setCursor(doc_iterator_begin(buffer_->inset()));
1456 if (lyx::find::findNextChange(this)) {
1457 owner_->getDialogs().show("changes");
1461 for_each(buffer_->par_iterator_begin(),
1462 buffer_->par_iterator_end(),
1463 mem_fun_ref(&Paragraph::untrackChanges));
1465 buffer_->params().tracking_changes = false;
1468 buffer_->redostack().clear();