2 * \file buffer_funcs.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Alfredo Braunstein
9 * Full author contact details are available in file CREDITS.
15 #include "buffer_funcs.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "DocIterator.h"
21 #include "ErrorList.h"
23 #include "FloatList.h"
24 #include "InsetList.h"
25 #include "InsetIterator.h"
29 #include "LayoutPtr.h"
31 #include "TextClass.h"
32 #include "TextClassList.h"
33 #include "Paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParagraphList.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
40 #include "TocBackend.h"
42 #include "frontends/alert.h"
44 #include "insets/InsetBibitem.h"
45 #include "insets/InsetInclude.h"
47 #include "support/convert.h"
48 #include "support/debug.h"
49 #include "support/filetools.h"
50 #include "support/gettext.h"
51 #include "support/lstrings.h"
52 #include "support/textutils.h"
55 using namespace lyx::support;
59 namespace Alert = frontend::Alert;
62 Buffer * checkAndLoadLyXFile(FileName const & filename)
65 Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
67 if (checkBuffer->isClean())
69 docstring const file = makeDisplayPath(filename.absFilename(), 20);
70 docstring text = bformat(_(
71 "The document %1$s is already loaded and has unsaved changes.\n"
72 "Do you want to abandon your changes and reload the version on disk?"), file);
73 if (Alert::prompt(_("Reload saved document?"),
74 text, 0, 1, _("&Reload"), _("&Keep Changes")))
77 // FIXME: should be LFUN_REVERT
78 theBufferList().release(checkBuffer);
80 return checkAndLoadLyXFile(filename);
83 if (filename.isReadableFile()) {
84 Buffer * b = theBufferList().newBuffer(filename.absFilename());
86 // Buffer creation is not possible.
88 if (!b->loadLyXFile(filename)) {
89 theBufferList().release(b);
95 docstring text = bformat(_("The document %1$s does not yet "
96 "exist.\n\nDo you want to create a new document?"),
97 from_utf8(filename.absFilename()));
98 if (!Alert::prompt(_("Create new document?"),
99 text, 0, 1, _("&Create"), _("Cancel")))
100 return newFile(filename.absFilename(), string(), true);
106 // FIXME newFile() should probably be a member method of Application...
107 Buffer * newFile(string const & filename, string const & templatename,
111 Buffer * b = theBufferList().newBuffer(filename);
113 // Buffer creation is not possible.
117 // use defaults.lyx as a default template if it exists.
118 if (templatename.empty())
119 tname = libFileSearch("templates", "defaults.lyx");
121 tname = makeAbsPath(templatename);
123 if (!tname.empty()) {
124 if (!b->readFile(tname)) {
125 docstring const file = makeDisplayPath(tname.absFilename(), 50);
126 docstring const text = bformat(
127 _("The specified document template\n%1$s\ncould not be read."),
129 Alert::error(_("Could not read template"), text);
130 theBufferList().release(b);
137 b->setFileName(filename);
140 b->setReadonly(false);
141 b->setFullyLoaded(true);
147 Buffer * newUnnamedFile(string const & templatename, FileName const & path)
149 static int newfile_number;
151 string document_path = path.absFilename();
152 string filename = addName(document_path,
153 "newfile" + convert<string>(++newfile_number) + ".lyx");
154 while (theBufferList().exists(filename)
155 || FileName(filename).isReadableFile()) {
157 filename = addName(document_path,
158 "newfile" + convert<string>(newfile_number) + ".lyx");
160 return newFile(filename, templatename, false);
164 int countWords(DocIterator const & from, DocIterator const & to)
168 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
169 // Copied and adapted from isLetter() in ControlSpellChecker
171 && dit.pos() != dit.lastpos()
172 && dit.paragraph().isLetter(dit.pos())
173 && !dit.paragraph().isDeleted(dit.pos())) {
186 int countChars(DocIterator const & from, DocIterator const & to, bool with_blanks)
190 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
192 if (!dit.inTexted()) continue;
193 Paragraph const & par = dit.paragraph();
194 pos_type const pos = dit.pos();
196 if (pos != dit.lastpos() && !par.isDeleted(pos)) {
197 if (par.isInset(pos)) {
198 Inset const * ins = par.getInset(pos);
201 else if (with_blanks && ins->isSpace())
204 char_type const c = par.getChar(pos);
205 if (isPrintableNonspace(c))
207 else if (isSpace(c) && with_blanks)
213 return chars + blanks;
219 depth_type getDepth(DocIterator const & it)
221 depth_type depth = 0;
222 for (size_t i = 0 ; i < it.depth() ; ++i)
223 if (!it[i].inset().inMathed())
224 depth += it[i].paragraph().getDepth() + 1;
225 // remove 1 since the outer inset does not count
229 depth_type getItemDepth(ParIterator const & it)
231 Paragraph const & par = *it;
232 LabelType const labeltype = par.layout()->labeltype;
234 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
237 // this will hold the lowest depth encountered up to now.
238 depth_type min_depth = getDepth(it);
239 ParIterator prev_it = it;
242 --prev_it.top().pit();
244 // start of nested inset: go to outer par
246 if (prev_it.empty()) {
247 // start of document: nothing to do
252 // We search for the first paragraph with same label
253 // that is not more deeply nested.
254 Paragraph & prev_par = *prev_it;
255 depth_type const prev_depth = getDepth(prev_it);
256 if (labeltype == prev_par.layout()->labeltype) {
257 if (prev_depth < min_depth)
258 return prev_par.itemdepth + 1;
259 if (prev_depth == min_depth)
260 return prev_par.itemdepth;
262 min_depth = min(min_depth, prev_depth);
263 // small optimization: if we are at depth 0, we won't
264 // find anything else
271 bool needEnumCounterReset(ParIterator const & it)
273 Paragraph const & par = *it;
274 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
275 depth_type const cur_depth = par.getDepth();
276 ParIterator prev_it = it;
277 while (prev_it.pit()) {
278 --prev_it.top().pit();
279 Paragraph const & prev_par = *prev_it;
280 if (prev_par.getDepth() <= cur_depth)
281 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
283 // start of nested inset: reset
288 // set the label of a paragraph. This includes the counters.
289 void setLabel(Buffer const & buf, ParIterator & it)
291 TextClass const & textclass = buf.params().getTextClass();
292 Paragraph & par = it.paragraph();
293 LayoutPtr const & layout = par.layout();
294 Counters & counters = textclass.counters();
296 if (par.params().startOfAppendix()) {
297 // FIXME: only the counter corresponding to toplevel
298 // sectionning should be reset
300 counters.appendix(true);
302 par.params().appendix(counters.appendix());
304 // Compute the item depth of the paragraph
305 par.itemdepth = getItemDepth(it);
307 if (layout->margintype == MARGIN_MANUAL) {
308 if (par.params().labelWidthString().empty())
309 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
311 par.params().labelWidthString(docstring());
314 switch(layout->labeltype) {
316 if (layout->toclevel <= buf.params().secnumdepth
317 && (layout->latextype != LATEX_ENVIRONMENT
318 || isFirstInSequence(it.pit(), it.plist()))) {
319 counters.step(layout->counter);
320 par.params().labelString(
321 par.expandLabel(layout, buf.params()));
323 par.params().labelString(docstring());
326 case LABEL_ITEMIZE: {
327 // At some point of time we should do something more
328 // clever here, like:
329 // par.params().labelString(
330 // buf.params().user_defined_bullet(par.itemdepth).getText());
331 // for now, use a simple hardcoded label
333 switch (par.itemdepth) {
335 itemlabel = char_type(0x2022);
338 itemlabel = char_type(0x2013);
341 itemlabel = char_type(0x2217);
344 itemlabel = char_type(0x2219); // or 0x00b7
347 par.params().labelString(itemlabel);
351 case LABEL_ENUMERATE: {
352 // FIXME: Yes I know this is a really, really! bad solution
354 docstring enumcounter = from_ascii("enum");
356 switch (par.itemdepth) {
368 // not a valid enumdepth...
372 // Maybe we have to reset the enumeration counter.
373 if (needEnumCounterReset(it))
374 counters.reset(enumcounter);
376 counters.step(enumcounter);
380 switch (par.itemdepth) {
382 format = N_("\\arabic{enumi}.");
385 format = N_("(\\alph{enumii})");
388 format = N_("\\roman{enumiii}.");
391 format = N_("\\Alph{enumiv}.");
394 // not a valid enumdepth...
398 par.params().labelString(counters.counterLabel(
399 par.translateIfPossible(from_ascii(format), buf.params())));
404 case LABEL_SENSITIVE: {
405 string const & type = counters.current_float();
406 docstring full_label;
408 full_label = buf.B_("Senseless!!! ");
410 docstring name = buf.B_(textclass.floats().getType(type).name());
411 if (counters.hasCounter(from_utf8(type))) {
412 counters.step(from_utf8(type));
413 full_label = bformat(from_ascii("%1$s %2$s:"),
415 counters.theCounter(from_utf8(type)));
417 full_label = bformat(from_ascii("%1$s #:"), name);
419 par.params().labelString(full_label);
424 par.params().labelString(docstring());
428 case LABEL_TOP_ENVIRONMENT:
429 case LABEL_CENTERED_TOP_ENVIRONMENT:
432 par.params().labelString(
433 par.translateIfPossible(layout->labelstring(),
441 void updateLabels(Buffer const & buf, ParIterator & parit)
443 BOOST_ASSERT(parit.pit() == 0);
445 // set the position of the text in the buffer to be able
446 // to resolve macros in it. This has nothing to do with
447 // labels, but by putting it here we avoid implementing
448 // a whole bunch of traversal routines just for this call.
449 parit.text()->setMacrocontextPosition(parit);
451 depth_type maxdepth = 0;
452 pit_type const lastpit = parit.lastpit();
453 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
454 // reduce depth if necessary
455 parit->params().depth(min(parit->params().depth(), maxdepth));
456 maxdepth = parit->getMaxDepthAfter();
458 // set the counter for this paragraph
459 setLabel(buf, parit);
462 InsetList::const_iterator iit = parit->insetList().begin();
463 InsetList::const_iterator end = parit->insetList().end();
464 for (; iit != end; ++iit) {
465 parit.pos() = iit->pos;
466 iit->inset->updateLabels(buf, parit);
473 // FIXME: buf should should be const because updateLabels() modifies
474 // the contents of the paragraphs.
475 void updateLabels(Buffer const & buf, bool childonly)
477 Buffer const * const master = buf.masterBuffer();
478 // Use the master text class also for child documents
479 TextClass const & textclass = master->params().getTextClass();
482 // If this is a child document start with the master
483 if (master != &buf) {
484 updateLabels(*master);
488 // start over the counters
489 textclass.counters().reset();
492 Buffer & cbuf = const_cast<Buffer &>(buf);
494 if (buf.text().empty()) {
495 // FIXME: we don't call continue with updateLabels()
496 // here because it crashes on newly created documents.
497 // But the TocBackend needs to be initialised
498 // nonetheless so we update the tocBackend manually.
499 cbuf.tocBackend().update();
504 ParIterator parit = par_iterator_begin(buf.inset());
505 updateLabels(buf, parit);
507 cbuf.tocBackend().update();
509 cbuf.structureChanged();