]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
0232078b7ef66d0e6f765f9ebc745293528e768f
[lyx.git] / src / insets / InsetText.cpp
1 /**
2  * \file InsetText.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetText.h"
14
15 #include "insets/InsetOptArg.h"
16
17 #include "buffer_funcs.h"
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "CompletionList.h"
22 #include "CoordCache.h"
23 #include "Cursor.h"
24 #include "CutAndPaste.h"
25 #include "DispatchResult.h"
26 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "InsetList.h"
30 #include "Intl.h"
31 #include "Lexer.h"
32 #include "lyxfind.h"
33 #include "LyXRC.h"
34 #include "MetricsInfo.h"
35 #include "output_docbook.h"
36 #include "output_latex.h"
37 #include "OutputParams.h"
38 #include "output_plaintext.h"
39 #include "paragraph_funcs.h"
40 #include "Paragraph.h"
41 #include "ParagraphParameters.h"
42 #include "ParIterator.h"
43 #include "Row.h"
44 #include "sgml.h"
45 #include "TexRow.h"
46 #include "TextClass.h"
47 #include "Text.h"
48 #include "TextMetrics.h"
49 #include "TocBackend.h"
50
51 #include "frontends/alert.h"
52 #include "frontends/Painter.h"
53
54 #include "support/debug.h"
55 #include "support/gettext.h"
56 #include "support/lstrings.h"
57
58 #include <boost/bind.hpp>
59 #include "support/lassert.h"
60
61 using namespace std;
62 using namespace lyx::support;
63
64 using boost::bind;
65 using boost::ref;
66
67 namespace lyx {
68
69 using graphics::PreviewLoader;
70
71
72 /////////////////////////////////////////////////////////////////////
73
74 InsetText::InsetText(Buffer const & buf, UsePlain type)
75         : drawFrame_(false), frame_color_(Color_insetframe)
76 {
77         setBuffer(const_cast<Buffer &>(buf));
78         initParagraphs(type);
79 }
80
81
82 InsetText::InsetText(InsetText const & in)
83         : Inset(in), text_()
84 {
85         text_.autoBreakRows_ = in.text_.autoBreakRows_;
86         drawFrame_ = in.drawFrame_;
87         frame_color_ = in.frame_color_;
88         text_.paragraphs() = in.text_.paragraphs();
89         setParagraphOwner();
90 }
91
92
93 void InsetText::setBuffer(Buffer & buf)
94 {
95         ParagraphList::iterator end = paragraphs().end();
96         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
97                 it->setBuffer(buf);
98         Inset::setBuffer(buf);
99 }
100
101
102 void InsetText::initParagraphs(UsePlain type)
103 {
104         LASSERT(paragraphs().empty(), /**/);
105         paragraphs().push_back(Paragraph());
106         Paragraph & ourpar = paragraphs().back();
107         ourpar.setInsetOwner(this);
108         DocumentClass const & dc = buffer_->params().documentClass();
109         if (type == DefaultLayout)
110                 ourpar.setDefaultLayout(dc);
111         else
112                 ourpar.setPlainLayout(dc);
113 }
114
115
116 void InsetText::setParagraphOwner()
117 {
118         for_each(paragraphs().begin(), paragraphs().end(),
119                  bind(&Paragraph::setInsetOwner, _1, this));
120 }
121
122
123 void InsetText::clear()
124 {
125         ParagraphList & pars = paragraphs();
126         LASSERT(!pars.empty(), /**/);
127
128         // This is a gross hack...
129         Layout const & old_layout = pars.begin()->layout();
130
131         pars.clear();
132         pars.push_back(Paragraph());
133         pars.begin()->setInsetOwner(this);
134         pars.begin()->setLayout(old_layout);
135 }
136
137
138 Dimension const InsetText::dimension(BufferView const & bv) const
139 {
140         TextMetrics const & tm = bv.textMetrics(&text_);
141         Dimension dim = tm.dimension();
142         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
143         dim.des += TEXT_TO_INSET_OFFSET;
144         dim.asc += TEXT_TO_INSET_OFFSET;
145         return dim;
146 }
147
148
149 void InsetText::write(ostream & os) const
150 {
151         os << "Text\n";
152         text_.write(buffer(), os);
153 }
154
155
156 void InsetText::read(Lexer & lex)
157 {
158         clear();
159
160         // delete the initial paragraph
161         Paragraph oldpar = *paragraphs().begin();
162         paragraphs().clear();
163         ErrorList errorList;
164         lex.setContext("InsetText::read");
165         bool res = text_.read(buffer(), lex, errorList, this);
166
167         if (!res)
168                 lex.printError("Missing \\end_inset at this point. ");
169
170         // sanity check
171         // ensure we have at least one paragraph.
172         if (paragraphs().empty())
173                 paragraphs().push_back(oldpar);
174 }
175
176
177 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
178 {
179         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
180
181         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
182
183         // Hand font through to contained lyxtext:
184         tm.font_.fontInfo() = mi.base.font;
185         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
186         if (hasFixedWidth())
187                 tm.metrics(mi, dim, mi.base.textwidth);
188         else
189                 tm.metrics(mi, dim);
190         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
191         dim.asc += TEXT_TO_INSET_OFFSET;
192         dim.des += TEXT_TO_INSET_OFFSET;
193         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
194 }
195
196
197 void InsetText::draw(PainterInfo & pi, int x, int y) const
198 {
199         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
200
201         if (drawFrame_ || pi.full_repaint) {
202                 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
203                 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
204                 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
205                 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
206                 if (pi.full_repaint)
207                         pi.pain.fillRectangle(xframe, yframe, w, h,
208                                 pi.backgroundColor(this));
209
210                 if (drawFrame_)
211                         pi.pain.rectangle(xframe, yframe, w, h, frameColor());
212         }
213         ColorCode const old_color = pi.background_color;
214         pi.background_color = pi.backgroundColor(this, false);
215
216         tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
217
218         pi.background_color = old_color;
219 }
220
221
222 docstring InsetText::editMessage() const
223 {
224         return _("Opened Text Inset");
225 }
226
227
228 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
229 {
230         pit_type const pit = front ? 0 : paragraphs().size() - 1;
231         pos_type pos = front ? 0 : paragraphs().back().size();
232
233         // if visual information is not to be ignored, move to extreme right/left
234         if (entry_from != ENTRY_DIRECTION_IGNORE) {
235                 Cursor temp_cur = cur;
236                 temp_cur.pit() = pit;
237                 temp_cur.pos() = pos;
238                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
239                 pos = temp_cur.pos();
240         }
241
242         text_.setCursor(cur.top(), pit, pos);
243         cur.clearSelection();
244         cur.finishUndo();
245 }
246
247
248 Inset * InsetText::editXY(Cursor & cur, int x, int y)
249 {
250         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
251 }
252
253
254 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
255 {
256         LYXERR(Debug::ACTION, "InsetText::doDispatch()"
257                 << " [ cmd.action = " << cmd.action << ']');
258         text_.dispatch(cur, cmd);
259 }
260
261
262 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
263         FuncStatus & status) const
264 {
265         switch (cmd.action) {
266         case LFUN_LAYOUT:
267                 status.setEnabled(!forcePlainLayout());
268                 return true;
269
270         case LFUN_LAYOUT_PARAGRAPH:
271         case LFUN_PARAGRAPH_PARAMS:
272         case LFUN_PARAGRAPH_PARAMS_APPLY:
273         case LFUN_PARAGRAPH_SPACING:
274         case LFUN_PARAGRAPH_UPDATE:
275                 status.setEnabled(allowParagraphCustomization());
276                 return true;
277         default:
278                 // Dispatch only to text_ if the cursor is inside
279                 // the text_. It is not for context menus (bug 5797).
280                 if (cur.text() == &text_)
281                         return text_.getStatus(cur, cmd, status);
282                 return false;
283         }
284 }
285
286
287 void InsetText::setChange(Change const & change)
288 {
289         ParagraphList::iterator pit = paragraphs().begin();
290         ParagraphList::iterator end = paragraphs().end();
291         for (; pit != end; ++pit) {
292                 pit->setChange(change);
293         }
294 }
295
296
297 void InsetText::acceptChanges(BufferParams const & bparams)
298 {
299         text_.acceptChanges(bparams);
300 }
301
302
303 void InsetText::rejectChanges(BufferParams const & bparams)
304 {
305         text_.rejectChanges(bparams);
306 }
307
308
309 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
310 {
311         TexRow texrow;
312         latexParagraphs(buffer(), text_, os, texrow, runparams);
313         return texrow.rows();
314 }
315
316
317 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
318 {
319         ParagraphList::const_iterator beg = paragraphs().begin();
320         ParagraphList::const_iterator end = paragraphs().end();
321         ParagraphList::const_iterator it = beg;
322         bool ref_printed = false;
323         int len = 0;
324         for (; it != end; ++it) {
325                 if (it != beg) {
326                         os << '\n';
327                         if (runparams.linelen > 0)
328                                 os << '\n';
329                 }
330                 odocstringstream oss;
331                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
332                 docstring const str = oss.str();
333                 os << str;
334                 // FIXME: len is not computed fully correctly; in principle,
335                 // we have to count the characters after the last '\n'
336                 len = str.size();
337         }
338
339         return len;
340 }
341
342
343 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
344 {
345         docbookParagraphs(paragraphs(), buffer(), os, runparams);
346         return 0;
347 }
348
349
350 void InsetText::validate(LaTeXFeatures & features) const
351 {
352         for_each(paragraphs().begin(), paragraphs().end(),
353                  bind(&Paragraph::validate, _1, ref(features)));
354 }
355
356
357 void InsetText::cursorPos(BufferView const & bv,
358                 CursorSlice const & sl, bool boundary, int & x, int & y) const
359 {
360         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
361         y = bv.textMetrics(&text_).cursorY(sl, boundary);
362 }
363
364
365 bool InsetText::showInsetDialog(BufferView *) const
366 {
367         return false;
368 }
369
370
371 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
372 {
373         clear();
374         Paragraph & first = paragraphs().front();
375         for (unsigned int i = 0; i < data.length(); ++i)
376                 first.insertChar(i, data[i], font, trackChanges);
377 }
378
379
380 void InsetText::setAutoBreakRows(bool flag)
381 {
382         if (flag == text_.autoBreakRows_)
383                 return;
384
385         text_.autoBreakRows_ = flag;
386         if (flag)
387                 return;
388
389         // remove previously existing newlines
390         ParagraphList::iterator it = paragraphs().begin();
391         ParagraphList::iterator end = paragraphs().end();
392         for (; it != end; ++it)
393                 for (int i = 0; i < it->size(); ++i)
394                         if (it->isNewline(i))
395                                 // do not track the change, because the user
396                                 // is not allowed to revert/reject it
397                                 it->eraseChar(i, false);
398 }
399
400
401 void InsetText::setDrawFrame(bool flag)
402 {
403         drawFrame_ = flag;
404 }
405
406
407 ColorCode InsetText::frameColor() const
408 {
409         return frame_color_;
410 }
411
412
413 void InsetText::setFrameColor(ColorCode col)
414 {
415         frame_color_ = col;
416 }
417
418
419 void InsetText::appendParagraphs(ParagraphList & plist)
420 {
421         // There is little we can do here to keep track of changes.
422         // As of 2006/10/20, appendParagraphs is used exclusively by
423         // LyXTabular::setMultiColumn. In this context, the paragraph break
424         // is lost irreversibly and the appended text doesn't really change
425
426         ParagraphList & pl = paragraphs();
427
428         ParagraphList::iterator pit = plist.begin();
429         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
430         ++pit;
431         mergeParagraph(buffer().params(), pl,
432                        distance(pl.begin(), ins) - 1);
433
434         for_each(pit, plist.end(),
435                  bind(&ParagraphList::push_back, ref(pl), _1));
436 }
437
438
439 void InsetText::addPreview(PreviewLoader & loader) const
440 {
441         ParagraphList::const_iterator pit = paragraphs().begin();
442         ParagraphList::const_iterator pend = paragraphs().end();
443
444         for (; pit != pend; ++pit) {
445                 InsetList::const_iterator it  = pit->insetList().begin();
446                 InsetList::const_iterator end = pit->insetList().end();
447                 for (; it != end; ++it)
448                         it->inset->addPreview(loader);
449         }
450 }
451
452
453 ParagraphList const & InsetText::paragraphs() const
454 {
455         return text_.paragraphs();
456 }
457
458
459 ParagraphList & InsetText::paragraphs()
460 {
461         return text_.paragraphs();
462 }
463
464
465 void InsetText::updateLabels(ParIterator const & it)
466 {
467         ParIterator it2 = it;
468         it2.forwardPos();
469         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
470         if (producesOutput()) {
471                 buffer().updateLabels(it2);
472         } else {
473                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
474                 Counters const savecnt = tclass.counters();
475                 buffer().updateLabels(it2);
476                 tclass.counters() = savecnt;
477         }
478 }
479
480
481 void InsetText::addToToc(DocIterator const & cdit)
482 {
483         DocIterator dit = cdit;
484         dit.push_back(CursorSlice(*this));
485         Toc & toc = buffer().tocBackend().toc("tableofcontents");
486
487         BufferParams const & bufparams = buffer_->params();
488         const int min_toclevel = bufparams.documentClass().min_toclevel();
489
490         // For each paragraph, traverse its insets and let them add
491         // their toc items
492         ParagraphList & pars = paragraphs();
493         pit_type pend = paragraphs().size();
494         for (pit_type pit = 0; pit != pend; ++pit) {
495                 Paragraph const & par = pars[pit];
496                 dit.pit() = pit;
497                 // the string that goes to the toc (could be the optarg)
498                 docstring tocstring;
499                 InsetList::const_iterator it  = par.insetList().begin();
500                 InsetList::const_iterator end = par.insetList().end();
501                 for (; it != end; ++it) {
502                         Inset & inset = *it->inset;
503                         dit.pos() = it->pos;
504                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
505                         inset.addToToc(dit);
506                         switch (inset.lyxCode()) {
507                         case OPTARG_CODE: {
508                                 if (!tocstring.empty())
509                                         break;
510                                 dit.pos() = 0;
511                                 Paragraph const & insetpar =
512                                         *static_cast<InsetOptArg&>(inset).paragraphs().begin();
513                                 if (!par.labelString().empty())
514                                         tocstring = par.labelString() + ' ';
515                                 tocstring += insetpar.asString(AS_STR_INSETS);
516                                 break;
517                         }
518                         default:
519                                 break;
520                         }
521                 }
522                 /// now the toc entry for the paragraph
523                 int const toclevel = par.layout().toclevel;
524                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
525                         dit.pos() = 0;
526                         // insert this into the table of contents
527                         if (tocstring.empty())
528                                 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
529                         toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
530                 }
531                 
532                 // And now the list of changes.
533                 par.addChangesToToc(dit, buffer());
534         }
535 }
536
537
538 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
539 {
540         if (buffer().isClean())
541                 return Inset::notifyCursorLeaves(old, cur);
542         
543         // find text inset in old cursor
544         Cursor insetCur = old;
545         int scriptSlice = insetCur.find(this);
546         LASSERT(scriptSlice != -1, /**/);
547         insetCur.cutOff(scriptSlice);
548         LASSERT(&insetCur.inset() == this, /**/);
549         
550         // update the old paragraph's words
551         insetCur.paragraph().updateWords(insetCur.top());
552         
553         return Inset::notifyCursorLeaves(old, cur);
554 }
555
556
557 bool InsetText::completionSupported(Cursor const & cur) const
558 {
559         //LASSERT(&cur.bv().cursor().inset() != this, return false);
560         return text_.completionSupported(cur);
561 }
562
563
564 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
565 {
566         return completionSupported(cur);
567 }
568
569
570 bool InsetText::automaticInlineCompletion() const
571 {
572         return lyxrc.completion_inline_text;
573 }
574
575
576 bool InsetText::automaticPopupCompletion() const
577 {
578         return lyxrc.completion_popup_text;
579 }
580
581
582 bool InsetText::showCompletionCursor() const
583 {
584         return lyxrc.completion_cursor_text;
585 }
586
587
588 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
589 {
590         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
591 }
592
593
594 docstring InsetText::completionPrefix(Cursor const & cur) const
595 {
596         if (!completionSupported(cur))
597                 return docstring();
598         return text_.completionPrefix(cur);
599 }
600
601
602 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
603         bool finished)
604 {
605         if (!completionSupported(cur))
606                 return false;
607
608         return text_.insertCompletion(cur, s, finished);
609 }
610
611
612 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
613         Dimension & dim) const
614 {
615         TextMetrics const & tm = cur.bv().textMetrics(&text_);
616         tm.completionPosAndDim(cur, x, y, dim);
617 }
618
619
620 docstring InsetText::contextMenu(BufferView const &, int, int) const
621 {
622         return from_ascii("context-edit");
623 }
624
625
626 } // namespace lyx