]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.cpp
1d90fa47775b1633c7202e567678afaa86abe9e5
[lyx.git] / src / buffer_funcs.cpp
1 /**
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.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16 #include "Buffer.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "DocIterator.h"
20 #include "Counters.h"
21 #include "ErrorList.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "InsetList.h"
25 #include "InsetIterator.h"
26 #include "Language.h"
27 #include "LaTeX.h"
28 #include "Layout.h"
29 #include "LayoutPtr.h"
30 #include "LyX.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"
38 #include "TexRow.h"
39 #include "Text.h"
40 #include "TocBackend.h"
41
42 #include "frontends/alert.h"
43
44 #include "insets/InsetBibitem.h"
45 #include "insets/InsetInclude.h"
46
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"
53
54 using namespace std;
55 using namespace lyx::support;
56
57 namespace lyx {
58
59 namespace Alert = frontend::Alert;
60
61
62 Buffer * checkAndLoadLyXFile(FileName const & filename)
63 {
64         // File already open?
65         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
66         if (checkBuffer) {
67                 if (checkBuffer->isClean())
68                         return checkBuffer;
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")))
75                         return checkBuffer;
76
77                 // FIXME: should be LFUN_REVERT
78                 theBufferList().release(checkBuffer);
79                 // Load it again.
80                 return checkAndLoadLyXFile(filename);
81         }
82
83         if (filename.isReadableFile()) {
84                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
85                 if (!b)
86                         // Buffer creation is not possible.
87                         return 0;
88                 if (!b->loadLyXFile(filename)) {
89                         theBufferList().release(b);
90                         return 0;
91                 }
92                 return b;
93         }
94
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);
101
102         return 0;
103 }
104
105
106 // FIXME newFile() should probably be a member method of Application...
107 Buffer * newFile(string const & filename, string const & templatename,
108                  bool const isNamed)
109 {
110         // get a free buffer
111         Buffer * b = theBufferList().newBuffer(filename);
112         if (!b)
113                 // Buffer creation is not possible.
114                 return 0;
115
116         FileName tname;
117         // use defaults.lyx as a default template if it exists.
118         if (templatename.empty())
119                 tname = libFileSearch("templates", "defaults.lyx");
120         else
121                 tname = makeAbsPath(templatename);
122
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."),
128                                 file);
129                         Alert::error(_("Could not read template"), text);
130                         theBufferList().release(b);
131                         return 0;
132                 }
133         }
134
135         if (!isNamed) {
136                 b->setUnnamed();
137                 b->setFileName(filename);
138         }
139
140         b->setReadonly(false);
141         b->setFullyLoaded(true);
142
143         return b;
144 }
145
146
147 Buffer * newUnnamedFile(string const & templatename, FileName const & path)
148 {
149         static int newfile_number;
150
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()) {
156                 ++newfile_number;
157                 filename = addName(document_path,
158                         "newfile" +     convert<string>(newfile_number) + ".lyx");
159         }
160         return newFile(filename, templatename, false);
161 }
162
163
164 int countWords(DocIterator const & from, DocIterator const & to)
165 {
166         int count = 0;
167         bool inword = false;
168         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
169                 // Copied and adapted from isLetter() in ControlSpellChecker
170                 if (dit.inTexted()
171                     && dit.pos() != dit.lastpos()
172                     && dit.paragraph().isLetter(dit.pos())
173                     && !dit.paragraph().isDeleted(dit.pos())) {
174                         if (!inword) {
175                                 ++count;
176                                 inword = true;
177                         }
178                 } else if (inword)
179                         inword = false;
180         }
181
182         return count;
183 }
184
185
186 int countChars(DocIterator const & from, DocIterator const & to, bool with_blanks)
187 {
188         int chars = 0;
189         int blanks = 0;
190         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
191                 Paragraph const & par = dit.paragraph();
192                 pos_type const pos = dit.pos();
193
194                 if (dit.inTexted() && pos != dit.lastpos() && !par.isDeleted(pos)) {
195                         if (par.isInset(pos)) {
196                                 Inset const * ins = par.getInset(pos);
197                                 if (ins->isLetter())
198                                         ++chars;
199                                 else if (with_blanks && ins->isSpace())
200                                         ++blanks;
201                         } else {
202                                 char_type const c = par.getChar(pos);
203                                 if (isPrintableNonspace(c))
204                                         ++chars;
205                                 else if (isSpace(c) && with_blanks)
206                                         ++blanks;
207                         }
208                 }
209         }
210
211         return chars + blanks;
212 }
213
214
215 namespace {
216
217 depth_type getDepth(DocIterator const & it)
218 {
219         depth_type depth = 0;
220         for (size_t i = 0 ; i < it.depth() ; ++i)
221                 if (!it[i].inset().inMathed())
222                         depth += it[i].paragraph().getDepth() + 1;
223         // remove 1 since the outer inset does not count
224         return depth - 1;
225 }
226
227 depth_type getItemDepth(ParIterator const & it)
228 {
229         Paragraph const & par = *it;
230         LabelType const labeltype = par.layout()->labeltype;
231
232         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
233                 return 0;
234
235         // this will hold the lowest depth encountered up to now.
236         depth_type min_depth = getDepth(it);
237         ParIterator prev_it = it;
238         while (true) {
239                 if (prev_it.pit())
240                         --prev_it.top().pit();
241                 else {
242                         // start of nested inset: go to outer par
243                         prev_it.pop_back();
244                         if (prev_it.empty()) {
245                                 // start of document: nothing to do
246                                 return 0;
247                         }
248                 }
249
250                 // We search for the first paragraph with same label
251                 // that is not more deeply nested.
252                 Paragraph & prev_par = *prev_it;
253                 depth_type const prev_depth = getDepth(prev_it);
254                 if (labeltype == prev_par.layout()->labeltype) {
255                         if (prev_depth < min_depth)
256                                 return prev_par.itemdepth + 1;
257                         if (prev_depth == min_depth)
258                                 return prev_par.itemdepth;
259                 }
260                 min_depth = min(min_depth, prev_depth);
261                 // small optimization: if we are at depth 0, we won't
262                 // find anything else
263                 if (prev_depth == 0)
264                         return 0;
265         }
266 }
267
268
269 bool needEnumCounterReset(ParIterator const & it)
270 {
271         Paragraph const & par = *it;
272         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
273         depth_type const cur_depth = par.getDepth();
274         ParIterator prev_it = it;
275         while (prev_it.pit()) {
276                 --prev_it.top().pit();
277                 Paragraph const & prev_par = *prev_it;
278                 if (prev_par.getDepth() <= cur_depth)
279                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
280         }
281         // start of nested inset: reset
282         return true;
283 }
284
285
286 // set the label of a paragraph. This includes the counters.
287 void setLabel(Buffer const & buf, ParIterator & it)
288 {
289         TextClass const & textclass = buf.params().getTextClass();
290         Paragraph & par = it.paragraph();
291         LayoutPtr const & layout = par.layout();
292         Counters & counters = textclass.counters();
293
294         if (par.params().startOfAppendix()) {
295                 // FIXME: only the counter corresponding to toplevel
296                 // sectionning should be reset
297                 counters.reset();
298                 counters.appendix(true);
299         }
300         par.params().appendix(counters.appendix());
301
302         // Compute the item depth of the paragraph
303         par.itemdepth = getItemDepth(it);
304
305         if (layout->margintype == MARGIN_MANUAL) {
306                 if (par.params().labelWidthString().empty())
307                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
308         } else {
309                 par.params().labelWidthString(docstring());
310         }
311
312         switch(layout->labeltype) {
313         case LABEL_COUNTER:
314                 if (layout->toclevel <= buf.params().secnumdepth
315                     && (layout->latextype != LATEX_ENVIRONMENT
316                         || isFirstInSequence(it.pit(), it.plist()))) {
317                         counters.step(layout->counter);
318                         par.params().labelString(
319                                 par.expandLabel(layout, buf.params()));
320                 } else
321                         par.params().labelString(docstring());
322                 break;
323
324         case LABEL_ITEMIZE: {
325                 // At some point of time we should do something more
326                 // clever here, like:
327                 //   par.params().labelString(
328                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
329                 // for now, use a simple hardcoded label
330                 docstring itemlabel;
331                 switch (par.itemdepth) {
332                 case 0:
333                         itemlabel = char_type(0x2022);
334                         break;
335                 case 1:
336                         itemlabel = char_type(0x2013);
337                         break;
338                 case 2:
339                         itemlabel = char_type(0x2217);
340                         break;
341                 case 3:
342                         itemlabel = char_type(0x2219); // or 0x00b7
343                         break;
344                 }
345                 par.params().labelString(itemlabel);
346                 break;
347         }
348
349         case LABEL_ENUMERATE: {
350                 // FIXME: Yes I know this is a really, really! bad solution
351                 // (Lgb)
352                 docstring enumcounter = from_ascii("enum");
353
354                 switch (par.itemdepth) {
355                 case 2:
356                         enumcounter += 'i';
357                 case 1:
358                         enumcounter += 'i';
359                 case 0:
360                         enumcounter += 'i';
361                         break;
362                 case 3:
363                         enumcounter += "iv";
364                         break;
365                 default:
366                         // not a valid enumdepth...
367                         break;
368                 }
369
370                 // Maybe we have to reset the enumeration counter.
371                 if (needEnumCounterReset(it))
372                         counters.reset(enumcounter);
373
374                 counters.step(enumcounter);
375
376                 string format;
377
378                 switch (par.itemdepth) {
379                 case 0:
380                         format = N_("\\arabic{enumi}.");
381                         break;
382                 case 1:
383                         format = N_("(\\alph{enumii})");
384                         break;
385                 case 2:
386                         format = N_("\\roman{enumiii}.");
387                         break;
388                 case 3:
389                         format = N_("\\Alph{enumiv}.");
390                         break;
391                 default:
392                         // not a valid enumdepth...
393                         break;
394                 }
395
396                 par.params().labelString(counters.counterLabel(
397                         par.translateIfPossible(from_ascii(format), buf.params())));
398
399                 break;
400         }
401
402         case LABEL_SENSITIVE: {
403                 string const & type = counters.current_float();
404                 docstring full_label;
405                 if (type.empty())
406                         full_label = buf.B_("Senseless!!! ");
407                 else {
408                         docstring name = buf.B_(textclass.floats().getType(type).name());
409                         if (counters.hasCounter(from_utf8(type))) {
410                                 counters.step(from_utf8(type));
411                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
412                                                      name, 
413                                                      counters.theCounter(from_utf8(type)));
414                         } else
415                                 full_label = bformat(from_ascii("%1$s #:"), name);      
416                 }
417                 par.params().labelString(full_label);   
418                 break;
419         }
420
421         case LABEL_NO_LABEL:
422                 par.params().labelString(docstring());
423                 break;
424
425         case LABEL_MANUAL:
426         case LABEL_TOP_ENVIRONMENT:
427         case LABEL_CENTERED_TOP_ENVIRONMENT:
428         case LABEL_STATIC:      
429         case LABEL_BIBLIO:
430                 par.params().labelString(
431                         par.translateIfPossible(layout->labelstring(), 
432                                                 buf.params()));
433                 break;
434         }
435 }
436
437 } // anon namespace
438
439 void updateLabels(Buffer const & buf, ParIterator & parit)
440 {
441         BOOST_ASSERT(parit.pit() == 0);
442
443         // set the position of the text in the buffer to be able
444         // to resolve macros in it. This has nothing to do with
445         // labels, but by putting it here we avoid implementing
446         // a whole bunch of traversal routines just for this call.
447         parit.text()->setMacrocontextPosition(parit);
448
449         depth_type maxdepth = 0;
450         pit_type const lastpit = parit.lastpit();
451         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
452                 // reduce depth if necessary
453                 parit->params().depth(min(parit->params().depth(), maxdepth));
454                 maxdepth = parit->getMaxDepthAfter();
455
456                 // set the counter for this paragraph
457                 setLabel(buf, parit);
458
459                 // Now the insets
460                 InsetList::const_iterator iit = parit->insetList().begin();
461                 InsetList::const_iterator end = parit->insetList().end();
462                 for (; iit != end; ++iit) {
463                         parit.pos() = iit->pos;
464                         iit->inset->updateLabels(buf, parit);
465                 }
466         }
467         
468 }
469
470
471 // FIXME: buf should should be const because updateLabels() modifies
472 // the contents of the paragraphs.
473 void updateLabels(Buffer const & buf, bool childonly)
474 {
475         Buffer const * const master = buf.masterBuffer();
476         // Use the master text class also for child documents
477         TextClass const & textclass = master->params().getTextClass();
478
479         if (!childonly) {
480                 // If this is a child document start with the master
481                 if (master != &buf) {
482                         updateLabels(*master);
483                         return;
484                 }
485
486                 // start over the counters
487                 textclass.counters().reset();
488         }
489
490         Buffer & cbuf = const_cast<Buffer &>(buf);
491
492         if (buf.text().empty()) {
493                 // FIXME: we don't call continue with updateLabels()
494                 // here because it crashes on newly created documents.
495                 // But the TocBackend needs to be initialised
496                 // nonetheless so we update the tocBackend manually.
497                 cbuf.tocBackend().update();
498                 return;
499         }
500
501         // do the real work
502         ParIterator parit = par_iterator_begin(buf.inset());
503         updateLabels(buf, parit);
504
505         cbuf.tocBackend().update();
506         if (!childonly)
507                 cbuf.structureChanged();
508 }
509
510
511 } // namespace lyx