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