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 "BaseClassList.h"
16 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
20 #include "DocIterator.h"
22 #include "ErrorList.h"
24 #include "FloatList.h"
25 #include "InsetList.h"
26 #include "InsetIterator.h"
30 #include "LayoutPtr.h"
32 #include "TextClass.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.exists()) {
84 if (!filename.isReadableFile()) {
85 docstring text = bformat(_("The file %1$s exists but is not "
86 "readable by the current user."),
87 from_utf8(filename.absFilename()));
88 Alert::error(_("File not readable!"), text);
91 Buffer * b = theBufferList().newBuffer(filename.absFilename());
93 // Buffer creation is not possible.
95 if (!b->loadLyXFile(filename)) {
96 theBufferList().release(b);
102 docstring text = bformat(_("The document %1$s does not yet "
103 "exist.\n\nDo you want to create a new document?"),
104 from_utf8(filename.absFilename()));
105 if (!Alert::prompt(_("Create new document?"),
106 text, 0, 1, _("&Create"), _("Cancel")))
107 return newFile(filename.absFilename(), string(), true);
113 // FIXME newFile() should probably be a member method of Application...
114 Buffer * newFile(string const & filename, string const & templatename,
118 Buffer * b = theBufferList().newBuffer(filename);
120 // Buffer creation is not possible.
124 // use defaults.lyx as a default template if it exists.
125 if (templatename.empty())
126 tname = libFileSearch("templates", "defaults.lyx");
128 tname = makeAbsPath(templatename);
130 if (!tname.empty()) {
131 if (!b->readFile(tname)) {
132 docstring const file = makeDisplayPath(tname.absFilename(), 50);
133 docstring const text = bformat(
134 _("The specified document template\n%1$s\ncould not be read."),
136 Alert::error(_("Could not read template"), text);
137 theBufferList().release(b);
144 b->setFileName(filename);
147 b->setReadonly(false);
148 b->setFullyLoaded(true);
154 Buffer * newUnnamedFile(string const & templatename, FileName const & path)
156 static int newfile_number;
158 string document_path = path.absFilename();
159 string filename = addName(document_path,
160 "newfile" + convert<string>(++newfile_number) + ".lyx");
161 while (theBufferList().exists(filename)
162 || FileName(filename).isReadableFile()) {
164 filename = addName(document_path,
165 "newfile" + convert<string>(newfile_number) + ".lyx");
167 return newFile(filename, templatename, false);
171 int countWords(DocIterator const & from, DocIterator const & to)
175 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
176 // Copied and adapted from isLetter() in ControlSpellChecker
178 && dit.pos() != dit.lastpos()
179 && dit.paragraph().isLetter(dit.pos())
180 && !dit.paragraph().isDeleted(dit.pos())) {
193 int countChars(DocIterator const & from, DocIterator const & to, bool with_blanks)
197 for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
199 if (!dit.inTexted()) continue;
200 Paragraph const & par = dit.paragraph();
201 pos_type const pos = dit.pos();
203 if (pos != dit.lastpos() && !par.isDeleted(pos)) {
204 if (Inset const * ins = par.getInset(pos)) {
207 else if (with_blanks && ins->isSpace())
210 char_type const c = par.getChar(pos);
211 if (isPrintableNonspace(c))
213 else if (isSpace(c) && with_blanks)
219 return chars + blanks;
225 depth_type getDepth(DocIterator const & it)
227 depth_type depth = 0;
228 for (size_t i = 0 ; i < it.depth() ; ++i)
229 if (!it[i].inset().inMathed())
230 depth += it[i].paragraph().getDepth() + 1;
231 // remove 1 since the outer inset does not count
235 depth_type getItemDepth(ParIterator const & it)
237 Paragraph const & par = *it;
238 LabelType const labeltype = par.layout()->labeltype;
240 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
243 // this will hold the lowest depth encountered up to now.
244 depth_type min_depth = getDepth(it);
245 ParIterator prev_it = it;
248 --prev_it.top().pit();
250 // start of nested inset: go to outer par
252 if (prev_it.empty()) {
253 // start of document: nothing to do
258 // We search for the first paragraph with same label
259 // that is not more deeply nested.
260 Paragraph & prev_par = *prev_it;
261 depth_type const prev_depth = getDepth(prev_it);
262 if (labeltype == prev_par.layout()->labeltype) {
263 if (prev_depth < min_depth)
264 return prev_par.itemdepth + 1;
265 if (prev_depth == min_depth)
266 return prev_par.itemdepth;
268 min_depth = min(min_depth, prev_depth);
269 // small optimization: if we are at depth 0, we won't
270 // find anything else
277 bool needEnumCounterReset(ParIterator const & it)
279 Paragraph const & par = *it;
280 BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
281 depth_type const cur_depth = par.getDepth();
282 ParIterator prev_it = it;
283 while (prev_it.pit()) {
284 --prev_it.top().pit();
285 Paragraph const & prev_par = *prev_it;
286 if (prev_par.getDepth() <= cur_depth)
287 return prev_par.layout()->labeltype != LABEL_ENUMERATE;
289 // start of nested inset: reset
294 // set the label of a paragraph. This includes the counters.
295 void setLabel(Buffer const & buf, ParIterator & it)
297 TextClass const & textclass = buf.params().textClass();
298 Paragraph & par = it.paragraph();
299 LayoutPtr const & layout = par.layout();
300 Counters & counters = textclass.counters();
302 if (par.params().startOfAppendix()) {
303 // FIXME: only the counter corresponding to toplevel
304 // sectionning should be reset
306 counters.appendix(true);
308 par.params().appendix(counters.appendix());
310 // Compute the item depth of the paragraph
311 par.itemdepth = getItemDepth(it);
313 if (layout->margintype == MARGIN_MANUAL) {
314 if (par.params().labelWidthString().empty())
315 par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
317 par.params().labelWidthString(docstring());
320 switch(layout->labeltype) {
322 if (layout->toclevel <= buf.params().secnumdepth
323 && (layout->latextype != LATEX_ENVIRONMENT
324 || isFirstInSequence(it.pit(), it.plist()))) {
325 counters.step(layout->counter);
326 par.params().labelString(
327 par.expandLabel(layout, buf.params()));
329 par.params().labelString(docstring());
332 case LABEL_ITEMIZE: {
333 // At some point of time we should do something more
334 // clever here, like:
335 // par.params().labelString(
336 // buf.params().user_defined_bullet(par.itemdepth).getText());
337 // for now, use a simple hardcoded label
339 switch (par.itemdepth) {
341 itemlabel = char_type(0x2022);
344 itemlabel = char_type(0x2013);
347 itemlabel = char_type(0x2217);
350 itemlabel = char_type(0x2219); // or 0x00b7
353 par.params().labelString(itemlabel);
357 case LABEL_ENUMERATE: {
358 // FIXME: Yes I know this is a really, really! bad solution
360 docstring enumcounter = from_ascii("enum");
362 switch (par.itemdepth) {
374 // not a valid enumdepth...
378 // Maybe we have to reset the enumeration counter.
379 if (needEnumCounterReset(it))
380 counters.reset(enumcounter);
382 counters.step(enumcounter);
386 switch (par.itemdepth) {
388 format = N_("\\arabic{enumi}.");
391 format = N_("(\\alph{enumii})");
394 format = N_("\\roman{enumiii}.");
397 format = N_("\\Alph{enumiv}.");
400 // not a valid enumdepth...
404 par.params().labelString(counters.counterLabel(
405 par.translateIfPossible(from_ascii(format), buf.params())));
410 case LABEL_SENSITIVE: {
411 string const & type = counters.current_float();
412 docstring full_label;
414 full_label = buf.B_("Senseless!!! ");
416 docstring name = buf.B_(textclass.floats().getType(type).name());
417 if (counters.hasCounter(from_utf8(type))) {
418 counters.step(from_utf8(type));
419 full_label = bformat(from_ascii("%1$s %2$s:"),
421 counters.theCounter(from_utf8(type)));
423 full_label = bformat(from_ascii("%1$s #:"), name);
425 par.params().labelString(full_label);
430 par.params().labelString(docstring());
434 case LABEL_TOP_ENVIRONMENT:
435 case LABEL_CENTERED_TOP_ENVIRONMENT:
438 par.params().labelString(
439 par.translateIfPossible(layout->labelstring(),
447 void updateLabels(Buffer const & buf, ParIterator & parit)
449 BOOST_ASSERT(parit.pit() == 0);
451 // set the position of the text in the buffer to be able
452 // to resolve macros in it. This has nothing to do with
453 // labels, but by putting it here we avoid implementing
454 // a whole bunch of traversal routines just for this call.
455 parit.text()->setMacrocontextPosition(parit);
457 depth_type maxdepth = 0;
458 pit_type const lastpit = parit.lastpit();
459 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
460 // reduce depth if necessary
461 parit->params().depth(min(parit->params().depth(), maxdepth));
462 maxdepth = parit->getMaxDepthAfter();
464 // set the counter for this paragraph
465 setLabel(buf, parit);
468 InsetList::const_iterator iit = parit->insetList().begin();
469 InsetList::const_iterator end = parit->insetList().end();
470 for (; iit != end; ++iit) {
471 parit.pos() = iit->pos;
472 iit->inset->updateLabels(buf, parit);
479 // FIXME: buf should should be const because updateLabels() modifies
480 // the contents of the paragraphs.
481 void updateLabels(Buffer const & buf, bool childonly)
483 Buffer const * const master = buf.masterBuffer();
484 // Use the master text class also for child documents
485 TextClass const & textclass = master->params().textClass();
488 // If this is a child document start with the master
489 if (master != &buf) {
490 updateLabels(*master);
494 // start over the counters
495 textclass.counters().reset();
498 Buffer & cbuf = const_cast<Buffer &>(buf);
500 if (buf.text().empty()) {
501 // FIXME: we don't call continue with updateLabels()
502 // here because it crashes on newly created documents.
503 // But the TocBackend needs to be initialised
504 // nonetheless so we update the tocBackend manually.
505 cbuf.tocBackend().update();
510 ParIterator parit = par_iterator_begin(buf.inset());
511 updateLabels(buf, parit);
513 cbuf.tocBackend().update();
515 cbuf.structureChanged();