]> git.lyx.org Git - lyx.git/blob - src/buffer.C
1fd247b510f31415cb9cf7c32bf63b23bd35b727
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
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  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14 #include "bufferlist.h"
15 #include "LyXAction.h"
16 #include "lyxrc.h"
17 #include "lyxlex.h"
18 #include "tex-strings.h"
19 #include "layout.h"
20 #include "bufferview_funcs.h"
21 #include "lyxfont.h"
22 #include "version.h"
23 #include "LaTeX.h"
24 #include "Chktex.h"
25 #include "debug.h"
26 #include "LaTeXFeatures.h"
27 #include "lyxtext.h"
28 #include "gettext.h"
29 #include "language.h"
30 #include "exporter.h"
31 #include "errorlist.h"
32 #include "Lsstream.h"
33 #include "format.h"
34 #include "BufferView.h"
35 #include "ParagraphParameters.h"
36 #include "iterators.h"
37 #include "lyxtextclasslist.h"
38 #include "sgml.h"
39 #include "paragraph_funcs.h"
40 #include "messages.h"
41 #include "author.h"
42
43 #include "frontends/LyXView.h"
44
45 #include "mathed/formulamacro.h"
46 #include "mathed/formula.h"
47
48 #include "insets/inseterror.h"
49 #include "insets/insetbibitem.h"
50 #include "insets/insetbibtex.h"
51 #include "insets/insetinclude.h"
52 #include "insets/insettext.h"
53
54 #include "frontends/Dialogs.h"
55 #include "frontends/Alert.h"
56
57 #include "graphics/Previews.h"
58
59 #include "support/textutils.h"
60 #include "support/filetools.h"
61 #include "support/path.h"
62 #include "support/os.h"
63 #include "support/tostr.h"
64 #include "support/lyxlib.h"
65 #include "support/FileInfo.h"
66 #include "support/lyxmanip.h"
67 #include "support/lyxtime.h"
68
69 #include <boost/bind.hpp>
70 #include <boost/tuple/tuple.hpp>
71
72 #include <fstream>
73 #include <iomanip>
74 #include <map>
75 #include <stack>
76 #include <list>
77 #include <algorithm>
78
79 #include <cstdlib>
80 #include <cmath>
81 #include <unistd.h>
82 #include <sys/types.h>
83 #include <utime.h>
84
85 #ifdef HAVE_LOCALE
86 #include <locale>
87 #endif
88
89 #ifndef CXX_GLOBAL_CSTD
90 using std::pow;
91 #endif
92
93 using std::ostream;
94 using std::ofstream;
95 using std::ifstream;
96 using std::fstream;
97 using std::ios;
98 using std::setw;
99 using std::endl;
100 using std::pair;
101 using std::make_pair;
102 using std::vector;
103 using std::map;
104 using std::stack;
105 using std::list;
106 using std::for_each;
107
108 using lyx::pos_type;
109 using lyx::textclass_type;
110
111 // all these externs should eventually be removed.
112 extern BufferList bufferlist;
113
114 namespace {
115
116 const int LYX_FORMAT = 224;
117
118 } // namespace anon
119
120 Buffer::Buffer(string const & file, bool ronly)
121         : niceFile(true), lyx_clean(true), bak_clean(true),
122           unnamed(false), read_only(ronly),
123           filename_(file), users(0)
124 {
125         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
126         filepath_ = OnlyPath(file);
127         lyxvc.buffer(this);
128         if (read_only || lyxrc.use_tempdir) {
129                 tmppath = CreateBufferTmpDir();
130         } else {
131                 tmppath.erase();
132         }
133
134         // set initial author
135         authors().record(Author(lyxrc.user_name, lyxrc.user_email));
136 }
137
138
139 Buffer::~Buffer()
140 {
141         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
142         // here the buffer should take care that it is
143         // saved properly, before it goes into the void.
144
145         // make sure that views using this buffer
146         // forgets it.
147         if (users)
148                 users->buffer(0);
149
150         if (!tmppath.empty() && destroyDir(tmppath) != 0) {
151                 Alert::warning(_("Could not remove temporary directory"),
152                         bformat(_("Could not remove the temporary directory %1$s"), tmppath));
153         }
154
155         paragraphs.clear();
156
157         // Remove any previewed LaTeX snippets assocoated with this buffer.
158         grfx::Previews::get().removeLoader(this);
159 }
160
161
162 string const Buffer::getLatexName(bool no_path) const
163 {
164         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
165         return no_path ? OnlyFilename(name) : name;
166 }
167
168
169 pair<Buffer::LogType, string> const Buffer::getLogName() const
170 {
171         string const filename = getLatexName(false);
172
173         if (filename.empty())
174                 return make_pair(Buffer::latexlog, string());
175
176         string path = OnlyPath(filename);
177
178         if (lyxrc.use_tempdir || !IsDirWriteable(path))
179                 path = tmppath;
180
181         string const fname = AddName(path,
182                                      OnlyFilename(ChangeExtension(filename,
183                                                                   ".log")));
184         string const bname =
185                 AddName(path, OnlyFilename(
186                         ChangeExtension(filename,
187                                         formats.extension("literate") + ".out")));
188
189         // If no Latex log or Build log is newer, show Build log
190
191         FileInfo const f_fi(fname);
192         FileInfo const b_fi(bname);
193
194         if (b_fi.exist() &&
195             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
196                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
197                 return make_pair(Buffer::buildlog, bname);
198         }
199         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
200         return make_pair(Buffer::latexlog, fname);
201 }
202
203
204 void Buffer::setReadonly(bool flag)
205 {
206         if (read_only != flag) {
207                 read_only = flag;
208                 updateTitles();
209                 users->owner()->getDialogs().updateBufferDependent(false);
210         }
211 }
212
213
214 AuthorList & Buffer::authors()
215 {
216         return params.authorlist;
217 }
218
219
220 /// Update window titles of all users
221 // Should work on a list
222 void Buffer::updateTitles() const
223 {
224         if (users)
225                 users->owner()->updateWindowTitle();
226 }
227
228
229 /// Reset autosave timer of all users
230 // Should work on a list
231 void Buffer::resetAutosaveTimers() const
232 {
233         if (users)
234                 users->owner()->resetAutosaveTimer();
235 }
236
237
238 void Buffer::setFileName(string const & newfile)
239 {
240         filename_ = MakeAbsPath(newfile);
241         filepath_ = OnlyPath(filename_);
242         setReadonly(IsFileWriteable(filename_) == 0);
243         updateTitles();
244 }
245
246
247 // We'll remove this later. (Lgb)
248 namespace {
249
250 void unknownClass(string const & unknown)
251 {
252         Alert::warning(_("Unknown document class"),
253                 bformat(_("Using the default document class, because the "
254                         " class %1$s is unknown."), unknown));
255 }
256
257 } // anon
258
259 int Buffer::readHeader(LyXLex & lex)
260 {
261         int unknown_tokens = 0;
262
263         while (lex.isOK()) {
264                 lex.nextToken();
265                 string const token = lex.getString();
266
267                 if (token.empty())
268                         continue;
269
270                 if (token == "\\end_header")
271                         break;
272
273                 lyxerr[Debug::PARSER] << "Handling header token: `"
274                                       << token << '\'' << endl;
275
276                 string unknown = params.readToken(lex, token);
277                 if (!unknown.empty()) {
278                         if (unknown[0] != '\\') {
279                                 unknownClass(unknown);
280                         } else {
281                                 ++unknown_tokens;
282                         }
283                 }
284         }
285         return unknown_tokens;
286 }
287
288
289 // candidate for move to BufferView
290 // (at least some parts in the beginning of the func)
291 //
292 // Uwe C. Schroeder
293 // changed to be public and have one parameter
294 // if par = 0 normal behavior
295 // else insert behavior
296 // Returns false if "\the_end" is not read (Asger)
297 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
298 {
299         int unknown_tokens = 0;
300
301         Paragraph::depth_type depth = 0;
302         bool the_end_read = false;
303
304         if (paragraphs.empty()) {
305                 unknown_tokens += readHeader(lex);
306
307                 if (!params.getLyXTextClass().load()) {
308                         string theclass = params.getLyXTextClass().name();
309                         Alert::error(_("Can't load document class"), bformat(
310                                         "Using the default document class, because the "
311                                         " class %1$s could not be loaded.", theclass));
312                         params.textclass = 0;
313                 }
314         } else {
315                 // We are inserting into an existing document
316                 users->text->breakParagraph(paragraphs);
317
318                 // We don't want to adopt the parameters from the
319                 // document we insert, so read them into a temporary buffer
320                 // and then discard it
321
322                 Buffer tmpbuf("", false);
323                 tmpbuf.readHeader(lex);
324         }
325
326         while (lex.isOK()) {
327                 lex.nextToken();
328                 string const token = lex.getString();
329
330                 if (token.empty())
331                         continue;
332
333                 lyxerr[Debug::PARSER] << "Handling token: `"
334                                       << token << '\'' << endl;
335
336                 if (token == "\\the_end") {
337                         the_end_read = true;
338                         continue;
339                 }
340
341                 unknown_tokens += readParagraph(lex, token, paragraphs, pit, depth);
342         }
343
344
345         if (unknown_tokens > 0) {
346                 string s;
347                 if (unknown_tokens == 1) {
348                         s = bformat(_("Encountered one unknown token when reading "
349                                 "the document %1$s."), fileName());
350                 } else {
351                         s = bformat(_("Encountered %1$s unknown tokens when reading "
352                                 "the document %2$s."), tostr(unknown_tokens), fileName());
353                 }
354                 Alert::warning(_("Document format failure"), s);
355         }
356
357         return the_end_read;
358 }
359
360
361 int Buffer::readParagraph(LyXLex & lex, string const & token,
362                       ParagraphList & pars, ParagraphList::iterator & pit,
363                       Paragraph::depth_type & depth)
364 {
365         static Change current_change;
366         int unknown = 0;
367
368         if (token == "\\layout") {
369                 lex.pushToken(token);
370
371                 Paragraph par;
372                 par.params().depth(depth);
373                 if (params.tracking_changes)
374                         par.trackChanges();
375                 LyXFont f(LyXFont::ALL_INHERIT, params.language);
376                 par.setFont(0, f);
377
378                 // FIXME: goddamn InsetTabular makes us pass a Buffer
379                 // not BufferParams
380                 unknown += ::readParagraph(*this, par, lex);
381
382                 // insert after
383                 if (pit != pars.end())
384                         ++pit;
385                 pit = pars.insert(pit, par);
386         } else if (token == "\\begin_deeper") {
387                 ++depth;
388         } else if (token == "\\end_deeper") {
389                 if (!depth) {
390                         lex.printError("\\end_deeper: " "depth is already null");
391                 } else {
392                         --depth;
393                 }
394         } else {
395                 ++unknown;
396         }
397         return unknown;
398 }
399
400
401 // needed to insert the selection
402 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
403                                  LyXFont const & fn,string const & str)
404 {
405         LyXLayout_ptr const & layout = par->layout();
406
407         LyXFont font = fn;
408
409         par->checkInsertChar(font);
410         // insert the string, don't insert doublespace
411         bool space_inserted = true;
412         bool autobreakrows = !par->inInset() ||
413                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
414         for(string::const_iterator cit = str.begin();
415             cit != str.end(); ++cit) {
416                 if (*cit == '\n') {
417                         if (autobreakrows && (!par->empty() || par->allowEmpty())) {
418                                 breakParagraph(params, paragraphs, par, pos,
419                                                layout->isEnvironment());
420                                 ++par;
421                                 pos = 0;
422                                 space_inserted = true;
423                         } else {
424                                 continue;
425                         }
426                         // do not insert consecutive spaces if !free_spacing
427                 } else if ((*cit == ' ' || *cit == '\t') &&
428                            space_inserted && !par->isFreeSpacing()) {
429                         continue;
430                 } else if (*cit == '\t') {
431                         if (!par->isFreeSpacing()) {
432                                 // tabs are like spaces here
433                                 par->insertChar(pos, ' ', font);
434                                 ++pos;
435                                 space_inserted = true;
436                         } else {
437                                 const pos_type nb = 8 - pos % 8;
438                                 for (pos_type a = 0; a < nb ; ++a) {
439                                         par->insertChar(pos, ' ', font);
440                                         ++pos;
441                                 }
442                                 space_inserted = true;
443                         }
444                 } else if (!IsPrintable(*cit)) {
445                         // Ignore unprintables
446                         continue;
447                 } else {
448                         // just insert the character
449                         par->insertChar(pos, *cit, font);
450                         ++pos;
451                         space_inserted = (*cit == ' ');
452                 }
453
454         }
455 }
456
457
458 bool Buffer::readFile(LyXLex & lex, string const & filename)
459 {
460         bool ret = readFile(lex, filename, paragraphs.begin());
461
462         // After we have read a file, we must ensure that the buffer
463         // language is set and used in the gui.
464         // If you know of a better place to put this, please tell me. (Lgb)
465         updateDocLang(params.language);
466
467         return ret;
468 }
469
470
471 // FIXME: all the below Alerts should give the filename..
472 bool Buffer::readFile(LyXLex & lex, string const & filename,
473                       ParagraphList::iterator pit)
474 {
475         if (!lex.isOK()) {
476                 Alert::error(_("Document could not be read"),
477                         _("The specified document could not be read."));
478                 return false;
479         }
480
481         lex.next();
482         string const token(lex.getString());
483
484         if (!lex.isOK()) {
485                 Alert::error(_("Document could not be read"),
486                         _("The specified document could not be read."));
487                 return false;
488         }
489
490         // the first token _must_ be...
491         if (token != "\\lyxformat") {
492                 Alert::error(_("Document format failure"),
493                         _("The specified document is not a LyX document."));
494                 return false;
495         }
496
497         lex.eatLine();
498         string tmp_format = lex.getString();
499         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
500         // if present remove ".," from string.
501         string::size_type dot = tmp_format.find_first_of(".,");
502         //lyxerr << "           dot found at " << dot << endl;
503         if (dot != string::npos)
504                         tmp_format.erase(dot, 1);
505         file_format = strToInt(tmp_format);
506         //lyxerr << "format: " << file_format << endl;
507         if (file_format == LYX_FORMAT) {
508                 // current format
509         } else if (file_format > LYX_FORMAT) {
510                 Alert::warning(_("Document format failure"),
511                         _("This document was created with a newer version of "
512                         "LyX. This is likely to cause problems."));
513         } else if (file_format < LYX_FORMAT) {
514                 // old formats
515                 if (file_format < 200) {
516                         Alert::error(_("Document format failure"),
517                                 _("This LyX document is too old to be read "
518                                 "by this version of LyX. Try LyX 0.10."));
519                         return false;
520                 } else if (!filename.empty()) {
521                         string command =
522                                 LibFileSearch("lyx2lyx", "lyx2lyx");
523                         if (command.empty()) {
524                                 Alert::error(_("Conversion script not found"),
525                                         _("The document is from an earlier version "
526                                           "of LyX, but the conversion script lyx2lyx "
527                                           "could not be found."));
528                                 return false;
529                         }
530                         command += " -t"
531                                 +tostr(LYX_FORMAT) + ' '
532                                 + QuoteName(filename);
533                         lyxerr[Debug::INFO] << "Running '"
534                                             << command << '\''
535                                             << endl;
536                         cmd_ret const ret = RunCommand(command);
537                         if (ret.first) {
538                                 Alert::error(_("Conversion script failed"),
539                                         _("The document is from an earlier version "
540                                           "of LyX, but the lyx2lyx script failed "
541                                           "to convert it."));
542                                 return false;
543                         }
544                         istringstream is(STRCONV(ret.second));
545                         LyXLex tmplex(0, 0);
546                         tmplex.setStream(is);
547                         return readFile(tmplex, string(), pit);
548                 } else {
549                         // This code is reached if lyx2lyx failed (for
550                         // some reason) to change the file format of
551                         // the file.
552                         lyx::Assert(false);
553                         return false;
554                 }
555         }
556         bool the_end = readBody(lex, pit);
557         params.setPaperStuff();
558
559         if (!the_end) {
560                 Alert::error(_("Document format failure"),
561                         _("The document ended unexpectedly, which means "
562                           "that it is probably corrupted."));
563         }
564         return true;
565 }
566
567
568 // Should probably be moved to somewhere else: BufferView? LyXView?
569 bool Buffer::save() const
570 {
571         // We don't need autosaves in the immediate future. (Asger)
572         resetAutosaveTimers();
573
574         // make a backup
575         string s;
576         if (lyxrc.make_backup) {
577                 s = fileName() + '~';
578                 if (!lyxrc.backupdir_path.empty())
579                         s = AddName(lyxrc.backupdir_path,
580                                     subst(os::slashify_path(s),'/','!'));
581
582                 // Rename is the wrong way of making a backup,
583                 // this is the correct way.
584                 /* truss cp fil fil2:
585                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
586                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
587                    open("LyXVC.lyx", O_RDONLY)                     = 3
588                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
589                    fstat(4, 0xEFFFF508)                            = 0
590                    fstat(3, 0xEFFFF508)                            = 0
591                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
592                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
593                    read(3, 0xEFFFD4A0, 8192)                       = 0
594                    close(4)                                        = 0
595                    close(3)                                        = 0
596                    chmod("LyXVC3.lyx", 0100644)                    = 0
597                    lseek(0, 0, SEEK_CUR)                           = 46440
598                    _exit(0)
599                 */
600
601                 // Should probably have some more error checking here.
602                 // Doing it this way, also makes the inodes stay the same.
603                 // This is still not a very good solution, in particular we
604                 // might loose the owner of the backup.
605                 FileInfo finfo(fileName());
606                 if (finfo.exist()) {
607                         mode_t fmode = finfo.getMode();
608                         struct utimbuf times = {
609                                 finfo.getAccessTime(),
610                                 finfo.getModificationTime() };
611
612                         ifstream ifs(fileName().c_str());
613                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
614                         if (ifs && ofs) {
615                                 ofs << ifs.rdbuf();
616                                 ifs.close();
617                                 ofs.close();
618                                 ::chmod(s.c_str(), fmode);
619
620                                 if (::utime(s.c_str(), &times)) {
621                                         lyxerr << "utime error." << endl;
622                                 }
623                         } else {
624                                 lyxerr << "LyX was not able to make "
625                                         "backup copy. Beware." << endl;
626                         }
627                 }
628         }
629
630         if (writeFile(fileName())) {
631                 markClean();
632                 removeAutosaveFile(fileName());
633         } else {
634                 // Saving failed, so backup is not backup
635                 if (lyxrc.make_backup) {
636                         lyx::rename(s, fileName());
637                 }
638                 return false;
639         }
640         return true;
641 }
642
643
644 bool Buffer::writeFile(string const & fname) const
645 {
646         if (read_only && (fname == fileName())) {
647                 return false;
648         }
649
650         FileInfo finfo(fname);
651         if (finfo.exist() && !finfo.writable()) {
652                 return false;
653         }
654
655         ofstream ofs(fname.c_str());
656         if (!ofs) {
657                 return false;
658         }
659
660 #ifdef HAVE_LOCALE
661         // Use the standard "C" locale for file output.
662         ofs.imbue(std::locale::classic());
663 #endif
664
665         // The top of the file should not be written by params.
666
667         // write out a comment in the top of the file
668         ofs << '#' << lyx_docversion
669             << " created this file. For more info see http://www.lyx.org/\n"
670             << "\\lyxformat " << LYX_FORMAT << "\n";
671
672         // now write out the buffer paramters.
673         params.writeFile(ofs);
674
675         ofs << "\\end_header\n";
676
677         Paragraph::depth_type depth = 0;
678
679         // this will write out all the paragraphs
680         // using recursive descent.
681         ParagraphList::const_iterator pit = paragraphs.begin();
682         ParagraphList::const_iterator pend = paragraphs.end();
683         for (; pit != pend; ++pit)
684                 pit->write(this, ofs, params, depth);
685
686         // Write marker that shows file is complete
687         ofs << "\n\\the_end" << endl;
688
689         ofs.close();
690
691         // how to check if close went ok?
692         // Following is an attempt... (BE 20001011)
693
694         // good() returns false if any error occured, including some
695         //        formatting error.
696         // bad()  returns true if something bad happened in the buffer,
697         //        which should include file system full errors.
698
699         bool status = true;
700         if (!ofs.good()) {
701                 status = false;
702 #if 0
703                 if (ofs.bad()) {
704                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
705                 } else {
706                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
707                                << endl;
708                 }
709 #endif
710         }
711
712         return status;
713 }
714
715
716 namespace {
717
718 pair<int, string> const addDepth(int depth, int ldepth)
719 {
720         int d = depth * 2;
721         if (ldepth > depth)
722                 d += (ldepth - depth) * 2;
723         return make_pair(d, string(d, ' '));
724 }
725
726 }
727
728
729 string const Buffer::asciiParagraph(Paragraph const & par,
730                                     unsigned int linelen,
731                                     bool noparbreak) const
732 {
733         ostringstream buffer;
734         Paragraph::depth_type depth = 0;
735         int ltype = 0;
736         Paragraph::depth_type ltype_depth = 0;
737         bool ref_printed = false;
738 //      if (!par->previous()) {
739 #if 0
740         // begins or ends a deeper area ?
741         if (depth != par->params().depth()) {
742                 if (par->params().depth() > depth) {
743                         while (par->params().depth() > depth) {
744                                 ++depth;
745                         }
746                 } else {
747                         while (par->params().depth() < depth) {
748                                 --depth;
749                         }
750                 }
751         }
752 #else
753         depth = par.params().depth();
754 #endif
755
756         // First write the layout
757         string const & tmp = par.layout()->name();
758         if (compare_no_case(tmp, "itemize") == 0) {
759                 ltype = 1;
760                 ltype_depth = depth + 1;
761         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
762                 ltype = 2;
763                 ltype_depth = depth + 1;
764         } else if (contains(ascii_lowercase(tmp), "ection")) {
765                 ltype = 3;
766                 ltype_depth = depth + 1;
767         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
768                 ltype = 4;
769                 ltype_depth = depth + 1;
770         } else if (compare_ascii_no_case(tmp, "description") == 0) {
771                 ltype = 5;
772                 ltype_depth = depth + 1;
773         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
774                 ltype = 6;
775                 ltype_depth = 0;
776         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
777                 ltype = 7;
778                 ltype_depth = 0;
779         } else {
780                 ltype = 0;
781                 ltype_depth = 0;
782         }
783
784         /* maybe some vertical spaces */
785
786         /* the labelwidthstring used in lists */
787
788         /* some lines? */
789
790         /* some pagebreaks? */
791
792         /* noindent ? */
793
794         /* what about the alignment */
795
796         // linelen <= 0 is special and means we don't have paragraph breaks
797
798         string::size_type currlinelen = 0;
799
800         if (!noparbreak) {
801                 if (linelen > 0)
802                         buffer << "\n\n";
803
804                 buffer << string(depth * 2, ' ');
805                 currlinelen += depth * 2;
806
807                 //--
808                 // we should probably change to the paragraph language in the
809                 // gettext here (if possible) so that strings are outputted in
810                 // the correct language! (20012712 Jug)
811                 //--
812                 switch (ltype) {
813                 case 0: // Standard
814                 case 4: // (Sub)Paragraph
815                 case 5: // Description
816                         break;
817                 case 6: // Abstract
818                         if (linelen > 0) {
819                                 buffer << _("Abstract") << "\n\n";
820                                 currlinelen = 0;
821                         } else {
822                                 string const abst = _("Abstract: ");
823                                 buffer << abst;
824                                 currlinelen += abst.length();
825                         }
826                         break;
827                 case 7: // Bibliography
828                         if (!ref_printed) {
829                                 if (linelen > 0) {
830                                         buffer << _("References") << "\n\n";
831                                         currlinelen = 0;
832                                 } else {
833                                         string const refs = _("References: ");
834                                         buffer << refs;
835                                         currlinelen += refs.length();
836                                 }
837
838                                 ref_printed = true;
839                         }
840                         break;
841                 default:
842                 {
843                         string const parlab = par.params().labelString();
844                         buffer << parlab << ' ';
845                         currlinelen += parlab.length() + 1;
846                 }
847                 break;
848
849                 }
850         }
851
852         if (!currlinelen) {
853                 pair<int, string> p = addDepth(depth, ltype_depth);
854                 buffer << p.second;
855                 currlinelen += p.first;
856         }
857
858         // this is to change the linebreak to do it by word a bit more
859         // intelligent hopefully! (only in the case where we have a
860         // max linelength!) (Jug)
861
862         string word;
863
864         for (pos_type i = 0; i < par.size(); ++i) {
865                 char c = par.getUChar(params, i);
866                 switch (c) {
867                 case Paragraph::META_INSET:
868                 {
869                         Inset const * inset = par.getInset(i);
870                         if (inset) {
871                                 if (linelen > 0) {
872                                         buffer << word;
873                                         currlinelen += word.length();
874                                         word.erase();
875                                 }
876                                 if (inset->ascii(this, buffer, linelen)) {
877                                         // to be sure it breaks paragraph
878                                         currlinelen += linelen;
879                                 }
880                         }
881                 }
882                 break;
883
884                 default:
885                         if (c == ' ') {
886                                 if (linelen > 0 &&
887                                     currlinelen + word.length() > linelen - 10) {
888                                         buffer << "\n";
889                                         pair<int, string> p = addDepth(depth, ltype_depth);
890                                         buffer << p.second;
891                                         currlinelen = p.first;
892                                 }
893
894                                 buffer << word << ' ';
895                                 currlinelen += word.length() + 1;
896                                 word.erase();
897
898                         } else {
899                                 if (c != '\0') {
900                                         word += c;
901                                 } else {
902                                         lyxerr[Debug::INFO] <<
903                                                 "writeAsciiFile: NULL char in structure." << endl;
904                                 }
905                                 if ((linelen > 0) &&
906                                         (currlinelen + word.length()) > linelen)
907                                 {
908                                         buffer << "\n";
909
910                                         pair<int, string> p =
911                                                 addDepth(depth, ltype_depth);
912                                         buffer << p.second;
913                                         currlinelen = p.first;
914                                 }
915                         }
916                         break;
917                 }
918         }
919         buffer << word;
920         return STRCONV(buffer.str());
921 }
922
923
924 void Buffer::writeFileAscii(string const & fname, int linelen)
925 {
926         ofstream ofs(fname.c_str());
927         if (!ofs) {
928                 string const file = MakeDisplayPath(fname, 50);
929                 string text = bformat(_("Could not save the document\n%1$s."), file);
930                 Alert::error(_("Could not save document"), text);
931                 return;
932         }
933         writeFileAscii(ofs, linelen);
934 }
935
936
937 void Buffer::writeFileAscii(ostream & os, int linelen)
938 {
939         ParagraphList::iterator beg = paragraphs.begin();
940         ParagraphList::iterator end = paragraphs.end();
941         ParagraphList::iterator it = beg;
942         for (; it != end; ++it) {
943                 os << asciiParagraph(*it, linelen, it == beg);
944         }
945         os << "\n";
946 }
947
948
949
950 void Buffer::makeLaTeXFile(string const & fname,
951                            string const & original_path,
952                            LatexRunParams const & runparams,
953                            bool only_body, bool only_preamble)
954 {
955         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
956
957         ofstream ofs(fname.c_str());
958         if (!ofs) {
959                 string const file = MakeDisplayPath(fname, 50);
960                 string text = bformat(_("Could not open the specified document\n%1$s."),
961                         file);
962                 Alert::error(_("Could not open file"), text);
963                 return;
964         }
965
966         makeLaTeXFile(ofs, original_path,
967                       runparams, only_body, only_preamble);
968
969         ofs.close();
970         if (ofs.fail()) {
971                 lyxerr << "File was not closed properly." << endl;
972         }
973 }
974
975
976 void Buffer::makeLaTeXFile(ostream & os,
977                            string const & original_path,
978                            LatexRunParams const & runparams_in,
979                            bool only_body, bool only_preamble)
980 {
981         LatexRunParams runparams = runparams_in;
982         niceFile = runparams.nice; // this will be used by Insetincludes.
983
984         // validate the buffer.
985         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
986         LaTeXFeatures features(params);
987         validate(features);
988         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
989
990         texrow.reset();
991         // The starting paragraph of the coming rows is the
992         // first paragraph of the document. (Asger)
993         texrow.start(paragraphs.begin()->id(), 0);
994
995         if (!only_body && runparams.nice) {
996                 os << "%% " << lyx_docversion << " created this file.  "
997                         "For more info, see http://www.lyx.org/.\n"
998                         "%% Do not edit unless you really know what "
999                         "you are doing.\n";
1000                 texrow.newline();
1001                 texrow.newline();
1002         }
1003         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1004         // There are a few differences between nice LaTeX and usual files:
1005         // usual is \batchmode and has a
1006         // special input@path to allow the including of figures
1007         // with either \input or \includegraphics (what figinsets do).
1008         // input@path is set when the actual parameter
1009         // original_path is set. This is done for usual tex-file, but not
1010         // for nice-latex-file. (Matthias 250696)
1011         if (!only_body) {
1012                 if (!runparams.nice) {
1013                         // code for usual, NOT nice-latex-file
1014                         os << "\\batchmode\n"; // changed
1015                         // from \nonstopmode
1016                         texrow.newline();
1017                 }
1018                 if (!original_path.empty()) {
1019                         string inputpath = os::external_path(original_path);
1020                         subst(inputpath, "~", "\\string~");
1021                         os << "\\makeatletter\n"
1022                             << "\\def\\input@path{{"
1023                             << inputpath << "/}}\n"
1024                             << "\\makeatother\n";
1025                         texrow.newline();
1026                         texrow.newline();
1027                         texrow.newline();
1028                 }
1029
1030                 // Write the preamble
1031                 runparams.use_babel = params.writeLaTeX(os, features, texrow);
1032
1033                 if (only_preamble)
1034                         return;
1035
1036                 // make the body.
1037                 os << "\\begin{document}\n";
1038                 texrow.newline();
1039         } // only_body
1040         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1041
1042         if (!lyxrc.language_auto_begin) {
1043                 os << subst(lyxrc.language_command_begin, "$$lang",
1044                              params.language->babel())
1045                     << endl;
1046                 texrow.newline();
1047         }
1048
1049         latexParagraphs(this, paragraphs, os, texrow, runparams);
1050
1051         // add this just in case after all the paragraphs
1052         os << endl;
1053         texrow.newline();
1054
1055         if (!lyxrc.language_auto_end) {
1056                 os << subst(lyxrc.language_command_end, "$$lang",
1057                              params.language->babel())
1058                     << endl;
1059                 texrow.newline();
1060         }
1061
1062         if (!only_body) {
1063                 os << "\\end{document}\n";
1064                 texrow.newline();
1065
1066                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1067         } else {
1068                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1069                                      << endl;
1070         }
1071
1072         // Just to be sure. (Asger)
1073         texrow.newline();
1074
1075         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1076         lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1077                             << '.' << endl;
1078
1079         // we want this to be true outside previews (for insetexternal)
1080         niceFile = true;
1081 }
1082
1083
1084 bool Buffer::isLatex() const
1085 {
1086         return params.getLyXTextClass().outputType() == LATEX;
1087 }
1088
1089
1090 bool Buffer::isLinuxDoc() const
1091 {
1092         return params.getLyXTextClass().outputType() == LINUXDOC;
1093 }
1094
1095
1096 bool Buffer::isLiterate() const
1097 {
1098         return params.getLyXTextClass().outputType() == LITERATE;
1099 }
1100
1101
1102 bool Buffer::isDocBook() const
1103 {
1104         return params.getLyXTextClass().outputType() == DOCBOOK;
1105 }
1106
1107
1108 bool Buffer::isSGML() const
1109 {
1110         LyXTextClass const & tclass = params.getLyXTextClass();
1111
1112         return tclass.outputType() == LINUXDOC ||
1113                tclass.outputType() == DOCBOOK;
1114 }
1115
1116
1117 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1118 {
1119         ofstream ofs(fname.c_str());
1120
1121         if (!ofs) {
1122                 string const file = MakeDisplayPath(fname, 50);
1123                 string text = bformat(_("Could not save the specified document\n%1$s.\n"),
1124                         file);
1125                 Alert::error(_("Could not save document"), text);
1126                 return;
1127         }
1128
1129         niceFile = nice; // this will be used by included files.
1130
1131         LaTeXFeatures features(params);
1132
1133         validate(features);
1134
1135         texrow.reset();
1136
1137         LyXTextClass const & tclass = params.getLyXTextClass();
1138
1139         string top_element = tclass.latexname();
1140
1141         if (!body_only) {
1142                 ofs << "<!doctype linuxdoc system";
1143
1144                 string preamble = params.preamble;
1145                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1146                          : fname;
1147                 preamble += features.getIncludedFiles(name);
1148                 preamble += features.getLyXSGMLEntities();
1149
1150                 if (!preamble.empty()) {
1151                         ofs << " [ " << preamble << " ]";
1152                 }
1153                 ofs << ">\n\n";
1154
1155                 if (params.options.empty())
1156                         sgml::openTag(ofs, 0, false, top_element);
1157                 else {
1158                         string top = top_element;
1159                         top += ' ';
1160                         top += params.options;
1161                         sgml::openTag(ofs, 0, false, top);
1162                 }
1163         }
1164
1165         ofs << "<!-- "  << lyx_docversion
1166             << " created this file. For more info see http://www.lyx.org/"
1167             << " -->\n";
1168
1169         Paragraph::depth_type depth = 0; // paragraph depth
1170         string item_name;
1171         vector<string> environment_stack(5);
1172
1173         users->resetErrorList();
1174
1175         ParagraphList::iterator pit = paragraphs.begin();
1176         ParagraphList::iterator pend = paragraphs.end();
1177         for (; pit != pend; ++pit) {
1178                 LyXLayout_ptr const & style = pit->layout();
1179                 // treat <toc> as a special case for compatibility with old code
1180                 if (pit->isInset(0)) {
1181                         Inset * inset = pit->getInset(0);
1182                         Inset::Code lyx_code = inset->lyxCode();
1183                         if (lyx_code == Inset::TOC_CODE) {
1184                                 string const temp = "toc";
1185                                 sgml::openTag(ofs, depth, false, temp);
1186                                 continue;
1187                         }
1188                 }
1189
1190                 // environment tag closing
1191                 for (; depth > pit->params().depth(); --depth) {
1192                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1193                         environment_stack[depth].erase();
1194                 }
1195
1196                 // write opening SGML tags
1197                 switch (style->latextype) {
1198                 case LATEX_PARAGRAPH:
1199                         if (depth == pit->params().depth()
1200                            && !environment_stack[depth].empty()) {
1201                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1202                                 environment_stack[depth].erase();
1203                                 if (depth)
1204                                         --depth;
1205                                 else
1206                                         ofs << "</p>";
1207                         }
1208                         sgml::openTag(ofs, depth, false, style->latexname());
1209                         break;
1210
1211                 case LATEX_COMMAND:
1212                         if (depth != 0)
1213                                 sgmlError(pit, 0,
1214                                           _("Error: Wrong depth for LatexType Command.\n"));
1215
1216                         if (!environment_stack[depth].empty()) {
1217                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1218                                 ofs << "</p>";
1219                         }
1220
1221                         environment_stack[depth].erase();
1222                         sgml::openTag(ofs, depth, false, style->latexname());
1223                         break;
1224
1225                 case LATEX_ENVIRONMENT:
1226                 case LATEX_ITEM_ENVIRONMENT:
1227                 case LATEX_BIB_ENVIRONMENT:
1228                 {
1229                         string const & latexname = style->latexname();
1230
1231                         if (depth == pit->params().depth()
1232                             && environment_stack[depth] != latexname) {
1233                                 sgml::closeTag(ofs, depth, false,
1234                                              environment_stack[depth]);
1235                                 environment_stack[depth].erase();
1236                         }
1237                         if (depth < pit->params().depth()) {
1238                                depth = pit->params().depth();
1239                                environment_stack[depth].erase();
1240                         }
1241                         if (environment_stack[depth] != latexname) {
1242                                 if (depth == 0) {
1243                                         sgml::openTag(ofs, depth, false, "p");
1244                                 }
1245                                 sgml::openTag(ofs, depth, false, latexname);
1246
1247                                 if (environment_stack.size() == depth + 1)
1248                                         environment_stack.push_back("!-- --");
1249                                 environment_stack[depth] = latexname;
1250                         }
1251
1252                         if (style->latexparam() == "CDATA")
1253                                 ofs << "<![CDATA[";
1254
1255                         if (style->latextype == LATEX_ENVIRONMENT) break;
1256
1257                         if (style->labeltype == LABEL_MANUAL)
1258                                 item_name = "tag";
1259                         else
1260                                 item_name = "item";
1261
1262                         sgml::openTag(ofs, depth + 1, false, item_name);
1263                 }
1264                 break;
1265
1266                 default:
1267                         sgml::openTag(ofs, depth, false, style->latexname());
1268                         break;
1269                 }
1270
1271                 simpleLinuxDocOnePar(ofs, pit, depth);
1272
1273                 ofs << "\n";
1274                 // write closing SGML tags
1275                 switch (style->latextype) {
1276                 case LATEX_COMMAND:
1277                         break;
1278                 case LATEX_ENVIRONMENT:
1279                 case LATEX_ITEM_ENVIRONMENT:
1280                 case LATEX_BIB_ENVIRONMENT:
1281                         if (style->latexparam() == "CDATA")
1282                                 ofs << "]]>";
1283                         break;
1284                 default:
1285                         sgml::closeTag(ofs, depth, false, style->latexname());
1286                         break;
1287                 }
1288         }
1289
1290         // Close open tags
1291         for (int i = depth; i >= 0; --i)
1292                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1293
1294         if (!body_only) {
1295                 ofs << "\n\n";
1296                 sgml::closeTag(ofs, 0, false, top_element);
1297         }
1298
1299         ofs.close();
1300         // How to check for successful close
1301
1302         // we want this to be true outside previews (for insetexternal)
1303         niceFile = true;
1304
1305         users->showErrorList(_("LinuxDoc"));
1306 }
1307
1308
1309 // checks, if newcol chars should be put into this line
1310 // writes newline, if necessary.
1311 namespace {
1312
1313 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1314                           string::size_type newcol)
1315 {
1316         colcount += newcol;
1317         if (colcount > lyxrc.ascii_linelen) {
1318                 os << "\n";
1319                 colcount = newcol; // assume write after this call
1320         }
1321 }
1322
1323 enum PAR_TAG {
1324         NONE=0,
1325         TT = 1,
1326         SF = 2,
1327         BF = 4,
1328         IT = 8,
1329         SL = 16,
1330         EM = 32
1331 };
1332
1333
1334 string tag_name(PAR_TAG const & pt) {
1335         switch (pt) {
1336         case NONE: return "!-- --";
1337         case TT: return "tt";
1338         case SF: return "sf";
1339         case BF: return "bf";
1340         case IT: return "it";
1341         case SL: return "sl";
1342         case EM: return "em";
1343         }
1344         return "";
1345 }
1346
1347
1348 inline
1349 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1350 {
1351         p1 = static_cast<PAR_TAG>(p1 | p2);
1352 }
1353
1354
1355 inline
1356 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1357 {
1358         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1359 }
1360
1361 } // anon
1362
1363
1364 // Handle internal paragraph parsing -- layout already processed.
1365 void Buffer::simpleLinuxDocOnePar(ostream & os,
1366         ParagraphList::iterator par,
1367         Paragraph::depth_type /*depth*/) const
1368 {
1369         LyXLayout_ptr const & style = par->layout();
1370
1371         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1372
1373         // gets paragraph main font
1374         LyXFont font_old;
1375         bool desc_on;
1376         if (style->labeltype == LABEL_MANUAL) {
1377                 font_old = style->labelfont;
1378                 desc_on = true;
1379         } else {
1380                 font_old = style->font;
1381                 desc_on = false;
1382         }
1383
1384         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1385         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1386         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1387         bool is_em = false;
1388
1389         stack<PAR_TAG> tag_state;
1390         // parsing main loop
1391         for (pos_type i = 0; i < par->size(); ++i) {
1392
1393                 PAR_TAG tag_close = NONE;
1394                 list < PAR_TAG > tag_open;
1395
1396                 LyXFont const font = par->getFont(params, i, outerFont(par, paragraphs));
1397
1398                 if (font_old.family() != font.family()) {
1399                         switch (family_type) {
1400                         case LyXFont::SANS_FAMILY:
1401                                 tag_close |= SF;
1402                                 break;
1403                         case LyXFont::TYPEWRITER_FAMILY:
1404                                 tag_close |= TT;
1405                                 break;
1406                         default:
1407                                 break;
1408                         }
1409
1410                         family_type = font.family();
1411
1412                         switch (family_type) {
1413                         case LyXFont::SANS_FAMILY:
1414                                 tag_open.push_back(SF);
1415                                 break;
1416                         case LyXFont::TYPEWRITER_FAMILY:
1417                                 tag_open.push_back(TT);
1418                                 break;
1419                         default:
1420                                 break;
1421                         }
1422                 }
1423
1424                 if (font_old.series() != font.series()) {
1425                         switch (series_type) {
1426                         case LyXFont::BOLD_SERIES:
1427                                 tag_close |= BF;
1428                                 break;
1429                         default:
1430                                 break;
1431                         }
1432
1433                         series_type = font.series();
1434
1435                         switch (series_type) {
1436                         case LyXFont::BOLD_SERIES:
1437                                 tag_open.push_back(BF);
1438                                 break;
1439                         default:
1440                                 break;
1441                         }
1442
1443                 }
1444
1445                 if (font_old.shape() != font.shape()) {
1446                         switch (shape_type) {
1447                         case LyXFont::ITALIC_SHAPE:
1448                                 tag_close |= IT;
1449                                 break;
1450                         case LyXFont::SLANTED_SHAPE:
1451                                 tag_close |= SL;
1452                                 break;
1453                         default:
1454                                 break;
1455                         }
1456
1457                         shape_type = font.shape();
1458
1459                         switch (shape_type) {
1460                         case LyXFont::ITALIC_SHAPE:
1461                                 tag_open.push_back(IT);
1462                                 break;
1463                         case LyXFont::SLANTED_SHAPE:
1464                                 tag_open.push_back(SL);
1465                                 break;
1466                         default:
1467                                 break;
1468                         }
1469                 }
1470                 // handle <em> tag
1471                 if (font_old.emph() != font.emph()) {
1472                         if (font.emph() == LyXFont::ON) {
1473                                 tag_open.push_back(EM);
1474                                 is_em = true;
1475                         }
1476                         else if (is_em) {
1477                                 tag_close |= EM;
1478                                 is_em = false;
1479                         }
1480                 }
1481
1482                 list < PAR_TAG > temp;
1483                 while (!tag_state.empty() && tag_close) {
1484                         PAR_TAG k =  tag_state.top();
1485                         tag_state.pop();
1486                         os << "</" << tag_name(k) << '>';
1487                         if (tag_close & k)
1488                                 reset(tag_close,k);
1489                         else
1490                                 temp.push_back(k);
1491                 }
1492
1493                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1494                     j != temp.end(); ++j) {
1495                         tag_state.push(*j);
1496                         os << '<' << tag_name(*j) << '>';
1497                 }
1498
1499                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1500                     j != tag_open.end(); ++j) {
1501                         tag_state.push(*j);
1502                         os << '<' << tag_name(*j) << '>';
1503                 }
1504
1505                 char c = par->getChar(i);
1506
1507                 if (c == Paragraph::META_INSET) {
1508                         Inset * inset = par->getInset(i);
1509                         inset->linuxdoc(this, os);
1510                         font_old = font;
1511                         continue;
1512                 }
1513
1514                 if (style->latexparam() == "CDATA") {
1515                         // "TeX"-Mode on == > SGML-Mode on.
1516                         if (c != '\0')
1517                                 os << c;
1518                         ++char_line_count;
1519                 } else {
1520                         bool ws;
1521                         string str;
1522                         boost::tie(ws, str) = sgml::escapeChar(c);
1523                         if (ws && !par->isFreeSpacing()) {
1524                                 // in freespacing mode, spaces are
1525                                 // non-breaking characters
1526                                 if (desc_on) {// if char is ' ' then...
1527
1528                                         ++char_line_count;
1529                                         sgmlLineBreak(os, char_line_count, 6);
1530                                         os << "</tag>";
1531                                         desc_on = false;
1532                                 } else  {
1533                                         sgmlLineBreak(os, char_line_count, 1);
1534                                         os << c;
1535                                 }
1536                         } else {
1537                                 os << str;
1538                                 char_line_count += str.length();
1539                         }
1540                 }
1541                 font_old = font;
1542         }
1543
1544         while (!tag_state.empty()) {
1545                 os << "</" << tag_name(tag_state.top()) << '>';
1546                 tag_state.pop();
1547         }
1548
1549         // resets description flag correctly
1550         if (desc_on) {
1551                 // <tag> not closed...
1552                 sgmlLineBreak(os, char_line_count, 6);
1553                 os << "</tag>";
1554         }
1555 }
1556
1557
1558 // Print an error message.
1559 void Buffer::sgmlError(ParagraphList::iterator pit, int pos,
1560                        string const & message) const
1561 {
1562         users->addError(ErrorItem(message, string(), pit->id(), pos, pos));
1563 }
1564
1565
1566 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1567 {
1568         ofstream ofs(fname.c_str());
1569         if (!ofs) {
1570                 string const file = MakeDisplayPath(fname, 50);
1571                 string text = bformat(_("Could not save the specified document\n%1$s.\n"),
1572                         file);
1573                 Alert::error(_("Could not save document"), text);
1574                 return;
1575         }
1576
1577         niceFile = nice; // this will be used by Insetincludes.
1578
1579         LaTeXFeatures features(params);
1580         validate(features);
1581
1582         texrow.reset();
1583
1584         LyXTextClass const & tclass = params.getLyXTextClass();
1585         string top_element = tclass.latexname();
1586
1587         if (!only_body) {
1588                 ofs << "<!DOCTYPE " << top_element
1589                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1590
1591                 string preamble = params.preamble;
1592                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1593                          : fname;
1594                 preamble += features.getIncludedFiles(name);
1595                 preamble += features.getLyXSGMLEntities();
1596
1597                 if (!preamble.empty()) {
1598                         ofs << "\n [ " << preamble << " ]";
1599                 }
1600                 ofs << ">\n\n";
1601         }
1602
1603         string top = top_element;
1604         top += " lang=\"";
1605         top += params.language->code();
1606         top += '"';
1607
1608         if (!params.options.empty()) {
1609                 top += ' ';
1610                 top += params.options;
1611         }
1612         sgml::openTag(ofs, 0, false, top);
1613
1614         ofs << "<!-- DocBook file was created by " << lyx_docversion
1615             << "\n  See http://www.lyx.org/ for more information -->\n";
1616
1617         vector<string> environment_stack(10);
1618         vector<string> environment_inner(10);
1619         vector<string> command_stack(10);
1620
1621         bool command_flag = false;
1622         Paragraph::depth_type command_depth = 0;
1623         Paragraph::depth_type command_base = 0;
1624         Paragraph::depth_type cmd_depth = 0;
1625         Paragraph::depth_type depth = 0; // paragraph depth
1626
1627         string item_name;
1628         string command_name;
1629
1630         users->resetErrorList();
1631
1632         ParagraphList::iterator par = paragraphs.begin();
1633         ParagraphList::iterator pend = paragraphs.end();
1634
1635         for (; par != pend; ++par) {
1636                 string sgmlparam;
1637                 string c_depth;
1638                 string c_params;
1639                 int desc_on = 0; // description mode
1640
1641                 LyXLayout_ptr const & style = par->layout();
1642
1643                 // environment tag closing
1644                 for (; depth > par->params().depth(); --depth) {
1645                         if (environment_inner[depth] != "!-- --" && !environment_inner[depth].empty()) {
1646                                 item_name = "listitem";
1647                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1648                                 if (environment_inner[depth] == "varlistentry")
1649                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
1650                         }
1651                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1652                         environment_stack[depth].erase();
1653                         environment_inner[depth].erase();
1654                 }
1655
1656                 if (depth == par->params().depth()
1657                    && environment_stack[depth] != style->latexname()
1658                    && !environment_stack[depth].empty()) {
1659                         if (environment_inner[depth] != "!-- --") {
1660                                 item_name= "listitem";
1661                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
1662                                 if (environment_inner[depth] == "varlistentry")
1663                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1664                         }
1665
1666                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1667
1668                         environment_stack[depth].erase();
1669                         environment_inner[depth].erase();
1670                 }
1671
1672                 // Write opening SGML tags.
1673                 switch (style->latextype) {
1674                 case LATEX_PARAGRAPH:
1675                         sgml::openTag(ofs, depth + command_depth,
1676                                     false, style->latexname());
1677                         break;
1678
1679                 case LATEX_COMMAND:
1680                         if (depth != 0)
1681                                 sgmlError(par, 0,
1682                                           _("Error: Wrong depth for LatexType Command.\n"));
1683
1684                         command_name = style->latexname();
1685
1686                         sgmlparam = style->latexparam();
1687                         c_params = split(sgmlparam, c_depth,'|');
1688
1689                         cmd_depth = lyx::atoi(c_depth);
1690
1691                         if (command_flag) {
1692                                 if (cmd_depth < command_base) {
1693                                         for (Paragraph::depth_type j = command_depth;
1694                                              j >= command_base; --j) {
1695                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1696                                                 ofs << endl;
1697                                         }
1698                                         command_depth = command_base = cmd_depth;
1699                                 } else if (cmd_depth <= command_depth) {
1700                                         for (int j = command_depth;
1701                                              j >= int(cmd_depth); --j) {
1702                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1703                                                 ofs << endl;
1704                                         }
1705                                         command_depth = cmd_depth;
1706                                 } else
1707                                         command_depth = cmd_depth;
1708                         } else {
1709                                 command_depth = command_base = cmd_depth;
1710                                 command_flag = true;
1711                         }
1712                         if (command_stack.size() == command_depth + 1)
1713                                 command_stack.push_back(string());
1714                         command_stack[command_depth] = command_name;
1715
1716                         // treat label as a special case for
1717                         // more WYSIWYM handling.
1718                         // This is a hack while paragraphs can't have
1719                         // attributes, like id in this case.
1720                         if (par->isInset(0)) {
1721                                 Inset * inset = par->getInset(0);
1722                                 Inset::Code lyx_code = inset->lyxCode();
1723                                 if (lyx_code == Inset::LABEL_CODE) {
1724                                         command_name += " id=\"";
1725                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
1726                                         command_name += '"';
1727                                         desc_on = 3;
1728                                 }
1729                         }
1730
1731                         sgml::openTag(ofs, depth + command_depth, false, command_name);
1732
1733                         item_name = c_params.empty() ? "title" : c_params;
1734                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
1735                         break;
1736
1737                 case LATEX_ENVIRONMENT:
1738                 case LATEX_ITEM_ENVIRONMENT:
1739                         if (depth < par->params().depth()) {
1740                                 depth = par->params().depth();
1741                                 environment_stack[depth].erase();
1742                         }
1743
1744                         if (environment_stack[depth] != style->latexname()) {
1745                                 if (environment_stack.size() == depth + 1) {
1746                                         environment_stack.push_back("!-- --");
1747                                         environment_inner.push_back("!-- --");
1748                                 }
1749                                 environment_stack[depth] = style->latexname();
1750                                 environment_inner[depth] = "!-- --";
1751                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
1752                         } else {
1753                                 if (environment_inner[depth] != "!-- --") {
1754                                         item_name= "listitem";
1755                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
1756                                         if (environment_inner[depth] == "varlistentry")
1757                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1758                                 }
1759                         }
1760
1761                         if (style->latextype == LATEX_ENVIRONMENT) {
1762                                 if (!style->latexparam().empty()) {
1763                                         if (style->latexparam() == "CDATA")
1764                                                 ofs << "<![CDATA[";
1765                                         else
1766                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
1767                                 }
1768                                 break;
1769                         }
1770
1771                         desc_on = (style->labeltype == LABEL_MANUAL);
1772
1773                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1774                         sgml::openTag(ofs, depth + 1 + command_depth,
1775                                     false, environment_inner[depth]);
1776
1777                         item_name = desc_on ? "term" : "para";
1778                         sgml::openTag(ofs, depth + 1 + command_depth,
1779                                     false, item_name);
1780                         break;
1781                 default:
1782                         sgml::openTag(ofs, depth + command_depth,
1783                                     false, style->latexname());
1784                         break;
1785                 }
1786
1787                 simpleDocBookOnePar(ofs, par, desc_on,
1788                                     depth + 1 + command_depth);
1789
1790                 string end_tag;
1791                 // write closing SGML tags
1792                 switch (style->latextype) {
1793                 case LATEX_COMMAND:
1794                         end_tag = c_params.empty() ? "title" : c_params;
1795                         sgml::closeTag(ofs, depth + command_depth,
1796                                      false, end_tag);
1797                         break;
1798                 case LATEX_ENVIRONMENT:
1799                         if (!style->latexparam().empty()) {
1800                                 if (style->latexparam() == "CDATA")
1801                                         ofs << "]]>";
1802                                 else
1803                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
1804                         }
1805                         break;
1806                 case LATEX_ITEM_ENVIRONMENT:
1807                         if (desc_on == 1) break;
1808                         end_tag = "para";
1809                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
1810                         break;
1811                 case LATEX_PARAGRAPH:
1812                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1813                         break;
1814                 default:
1815                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1816                         break;
1817                 }
1818         }
1819
1820         // Close open tags
1821         for (int d = depth; d >= 0; --d) {
1822                 if (!environment_stack[depth].empty()) {
1823                         if (environment_inner[depth] != "!-- --") {
1824                                 item_name = "listitem";
1825                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1826                                if (environment_inner[depth] == "varlistentry")
1827                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1828                         }
1829
1830                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1831                 }
1832         }
1833
1834         for (int j = command_depth; j >= 0 ; --j)
1835                 if (!command_stack[j].empty()) {
1836                         sgml::closeTag(ofs, j, false, command_stack[j]);
1837                         ofs << endl;
1838                 }
1839
1840         ofs << "\n\n";
1841         sgml::closeTag(ofs, 0, false, top_element);
1842
1843         ofs.close();
1844         // How to check for successful close
1845
1846         // we want this to be true outside previews (for insetexternal)
1847         niceFile = true;
1848         users->showErrorList(_("DocBook"));
1849 }
1850
1851
1852 void Buffer::simpleDocBookOnePar(ostream & os,
1853                                  ParagraphList::iterator par, int & desc_on,
1854                                  Paragraph::depth_type depth) const
1855 {
1856         bool emph_flag = false;
1857
1858         LyXLayout_ptr const & style = par->layout();
1859
1860         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
1861
1862         int char_line_count = depth;
1863         //if (!style.free_spacing)
1864         //      os << string(depth,' ');
1865
1866         // parsing main loop
1867         for (pos_type i = 0; i < par->size(); ++i) {
1868                 LyXFont font = par->getFont(params, i, outerFont(par, paragraphs));
1869
1870                 // handle <emphasis> tag
1871                 if (font_old.emph() != font.emph()) {
1872                         if (font.emph() == LyXFont::ON) {
1873                                 if (style->latexparam() == "CDATA")
1874                                         os << "]]>";
1875                                 os << "<emphasis>";
1876                                 if (style->latexparam() == "CDATA")
1877                                         os << "<![CDATA[";
1878                                 emph_flag = true;
1879                         } else if (i) {
1880                                 if (style->latexparam() == "CDATA")
1881                                         os << "]]>";
1882                                 os << "</emphasis>";
1883                                 if (style->latexparam() == "CDATA")
1884                                         os << "<![CDATA[";
1885                                 emph_flag = false;
1886                         }
1887                 }
1888
1889
1890                 if (par->isInset(i)) {
1891                         Inset * inset = par->getInset(i);
1892                         // don't print the inset in position 0 if desc_on == 3 (label)
1893                         if (i || desc_on != 3) {
1894                                 if (style->latexparam() == "CDATA")
1895                                         os << "]]>";
1896                                 inset->docbook(this, os, false);
1897                                 if (style->latexparam() == "CDATA")
1898                                         os << "<![CDATA[";
1899                         }
1900                 } else {
1901                         char c = par->getChar(i);
1902                         bool ws;
1903                         string str;
1904                         boost::tie(ws, str) = sgml::escapeChar(c);
1905
1906                         if (style->pass_thru) {
1907                                 os << c;
1908                         } else if (par->isFreeSpacing() || c != ' ') {
1909                                         os << str;
1910                         } else if (desc_on == 1) {
1911                                 ++char_line_count;
1912                                 os << "\n</term><listitem><para>";
1913                                 desc_on = 2;
1914                         } else {
1915                                 os << ' ';
1916                         }
1917                 }
1918                 font_old = font;
1919         }
1920
1921         if (emph_flag) {
1922                 if (style->latexparam() == "CDATA")
1923                         os << "]]>";
1924                 os << "</emphasis>";
1925                 if (style->latexparam() == "CDATA")
1926                         os << "<![CDATA[";
1927         }
1928
1929         // resets description flag correctly
1930         if (desc_on == 1) {
1931                 // <term> not closed...
1932                 os << "</term>\n<listitem><para>&nbsp;</para>";
1933         }
1934         if (style->free_spacing)
1935                 os << '\n';
1936 }
1937
1938
1939 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1940 // Other flags: -wall -v0 -x
1941 int Buffer::runChktex()
1942 {
1943         if (!users->text) return 0;
1944
1945         users->owner()->busy(true);
1946
1947         // get LaTeX-Filename
1948         string const name = getLatexName();
1949         string path = filePath();
1950
1951         string const org_path = path;
1952         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1953                 path = tmppath;
1954         }
1955
1956         Path p(path); // path to LaTeX file
1957         users->owner()->message(_("Running chktex..."));
1958
1959         // Generate the LaTeX file if neccessary
1960         LatexRunParams runparams;
1961         runparams.flavor = LatexRunParams::LATEX;
1962         runparams.nice = false;
1963         makeLaTeXFile(name, org_path, runparams);
1964
1965         TeXErrors terr;
1966         Chktex chktex(lyxrc.chktex_command, name, filePath());
1967         int res = chktex.run(terr); // run chktex
1968
1969         if (res == -1) {
1970                 Alert::error(_("chktex failure"),
1971                         _("Could not run chktex successfully."));
1972         } else if (res > 0) {
1973                 // Insert all errors as errors boxes
1974                 ErrorList el (*this, terr);
1975                 users->setErrorList(el);
1976                 users->showErrorList(_("ChkTeX"));
1977         }
1978
1979         users->owner()->busy(false);
1980
1981         return res;
1982 }
1983
1984
1985 void Buffer::validate(LaTeXFeatures & features) const
1986 {
1987         LyXTextClass const & tclass = params.getLyXTextClass();
1988
1989         if (params.tracking_changes) {
1990                 features.require("dvipost");
1991                 features.require("color");
1992         }
1993
1994         // AMS Style is at document level
1995         if (params.use_amsmath == BufferParams::AMS_ON
1996             || tclass.provides(LyXTextClass::amsmath))
1997                 features.require("amsmath");
1998
1999         for_each(paragraphs.begin(), paragraphs.end(),
2000                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2001
2002         // the bullet shapes are buffer level not paragraph level
2003         // so they are tested here
2004         for (int i = 0; i < 4; ++i) {
2005                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2006                         int const font = params.user_defined_bullets[i].getFont();
2007                         if (font == 0) {
2008                                 int const c = params
2009                                         .user_defined_bullets[i]
2010                                         .getCharacter();
2011                                 if (c == 16
2012                                    || c == 17
2013                                    || c == 25
2014                                    || c == 26
2015                                    || c == 31) {
2016                                         features.require("latexsym");
2017                                 }
2018                         } else if (font == 1) {
2019                                 features.require("amssymb");
2020                         } else if ((font >= 2 && font <= 5)) {
2021                                 features.require("pifont");
2022                         }
2023                 }
2024         }
2025
2026         if (lyxerr.debugging(Debug::LATEX)) {
2027                 features.showStruct();
2028         }
2029 }
2030
2031
2032 vector<string> const Buffer::getLabelList() const
2033 {
2034         /// if this is a child document and the parent is already loaded
2035         /// Use the parent's list instead  [ale990407]
2036         if (!params.parentname.empty()
2037             && bufferlist.exists(params.parentname)) {
2038                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2039                 if (tmp)
2040                         return tmp->getLabelList();
2041         }
2042
2043         vector<string> label_list;
2044         for (inset_iterator it = inset_const_iterator_begin();
2045              it != inset_const_iterator_end(); ++it) {
2046                 vector<string> const l = it->getLabelList();
2047                 label_list.insert(label_list.end(), l.begin(), l.end());
2048         }
2049         return label_list;
2050 }
2051
2052
2053 // This is also a buffer property (ale)
2054 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2055 {
2056         /// if this is a child document and the parent is already loaded
2057         /// use the parent's list instead  [ale990412]
2058         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2059                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2060                 if (tmp) {
2061                         tmp->fillWithBibKeys(keys);
2062                         return;
2063                 }
2064         }
2065
2066         for (inset_iterator it = inset_const_iterator_begin();
2067                 it != inset_const_iterator_end(); ++it) {
2068                 if (it->lyxCode() == Inset::BIBTEX_CODE)
2069                         static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2070                 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2071                         static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2072                 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2073                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2074                         string const key = bib.getContents();
2075                         string const opt = bib.getOptions();
2076                         string const ref; // = pit->asString(this, false);
2077                         string const info = opt + "TheBibliographyRef" + ref;
2078                         keys.push_back(pair<string, string>(key, info));
2079                 }
2080         }
2081 }
2082
2083
2084 bool Buffer::isDepClean(string const & name) const
2085 {
2086         DepClean::const_iterator it = dep_clean_.find(name);
2087         if (it == dep_clean_.end())
2088                 return true;
2089         return it->second;
2090 }
2091
2092
2093 void Buffer::markDepClean(string const & name)
2094 {
2095         dep_clean_[name] = true;
2096 }
2097
2098
2099 bool Buffer::dispatch(string const & command, bool * result)
2100 {
2101         // Split command string into command and argument
2102         string cmd;
2103         string line = ltrim(command);
2104         string const arg = trim(split(line, cmd, ' '));
2105
2106         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2107 }
2108
2109
2110 bool Buffer::dispatch(int action, string const & argument, bool * result)
2111 {
2112         bool dispatched = true;
2113
2114         switch (action) {
2115                 case LFUN_EXPORT: {
2116                         bool const tmp = Exporter::Export(this, argument, false);
2117                         if (result)
2118                                 *result = tmp;
2119                         break;
2120                 }
2121
2122                 default:
2123                         dispatched = false;
2124         }
2125         return dispatched;
2126 }
2127
2128
2129 void Buffer::resizeInsets(BufferView * bv)
2130 {
2131         /// then remove all LyXText in text-insets
2132         for_each(paragraphs.begin(), paragraphs.end(),
2133                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2134 }
2135
2136
2137 void Buffer::redraw()
2138 {
2139 #warning repaint needed here, or do you mean update() ?
2140         users->repaint();
2141         users->fitCursor();
2142 }
2143
2144
2145 void Buffer::changeLanguage(Language const * from, Language const * to)
2146 {
2147         lyxerr << "Changing Language!" << endl;
2148
2149         // Take care of l10n/i18n
2150         updateDocLang(to);
2151
2152         ParIterator end = par_iterator_end();
2153         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2154                 (*it)->changeLanguage(params, from, to);
2155 }
2156
2157
2158 void Buffer::updateDocLang(Language const * nlang)
2159 {
2160         messages_.reset(new Messages(nlang->code()));
2161 }
2162
2163
2164 bool Buffer::isMultiLingual()
2165 {
2166         ParIterator end = par_iterator_end();
2167         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2168                 if ((*it)->isMultiLingual(params))
2169                         return true;
2170
2171         return false;
2172 }
2173
2174
2175 void Buffer::inset_iterator::setParagraph()
2176 {
2177         while (pit != pend) {
2178                 it = pit->insetlist.begin();
2179                 if (it != pit->insetlist.end())
2180                         return;
2181                 ++pit;
2182         }
2183 }
2184
2185
2186 Inset * Buffer::getInsetFromID(int id_arg) const
2187 {
2188         for (inset_iterator it = inset_const_iterator_begin();
2189                  it != inset_const_iterator_end(); ++it)
2190         {
2191                 if (it->id() == id_arg)
2192                         return &(*it);
2193                 Inset * in = it->getInsetFromID(id_arg);
2194                 if (in)
2195                         return in;
2196         }
2197         return 0;
2198 }
2199
2200
2201 ParIterator Buffer::getParFromID(int id) const
2202 {
2203 #warning FIXME: const correctness! (Andre)
2204         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
2205         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
2206
2207 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
2208         if (id < 0) {
2209                 // John says this is called with id == -1 from undo
2210                 lyxerr << "getParFromID(), id: " << id << endl;
2211                 return end;
2212         }
2213
2214         for (; it != end; ++it)
2215                 if ((*it)->id() == id)
2216                         return it;
2217
2218         return end;
2219 }
2220
2221
2222 bool Buffer::hasParWithID(int id) const
2223 {
2224         ParIterator it(const_cast<Buffer*>(this)->par_iterator_begin());
2225         ParIterator end(const_cast<Buffer*>(this)->par_iterator_end());
2226
2227         if (id < 0) {
2228                 // John says this is called with id == -1 from undo
2229                 lyxerr << "hasParWithID(), id: " << id << endl;
2230                 return 0;
2231         }
2232
2233         for (; it != end; ++it)
2234                 if ((*it)->id() == id)
2235                         return true;
2236
2237         return false;
2238 }
2239
2240
2241 ParIterator Buffer::par_iterator_begin()
2242 {
2243         return ParIterator(paragraphs.begin(), paragraphs);
2244 }
2245
2246
2247 ParIterator Buffer::par_iterator_end()
2248 {
2249         return ParIterator(paragraphs.end(), paragraphs);
2250 }
2251
2252 ParConstIterator Buffer::par_iterator_begin() const
2253 {
2254         return ParConstIterator(const_cast<ParagraphList&>(paragraphs).begin(), paragraphs);
2255 }
2256
2257
2258 ParConstIterator Buffer::par_iterator_end() const
2259 {
2260         return ParConstIterator(const_cast<ParagraphList&>(paragraphs).end(), paragraphs);
2261 }
2262
2263
2264
2265 void Buffer::addUser(BufferView * u)
2266 {
2267         users = u;
2268 }
2269
2270
2271 void Buffer::delUser(BufferView *)
2272 {
2273         users = 0;
2274 }
2275
2276
2277 Language const * Buffer::getLanguage() const
2278 {
2279         return params.language;
2280 }
2281
2282
2283 string const Buffer::B_(string const & l10n) const
2284 {
2285         if (messages_.get()) {
2286                 return messages_->get(l10n);
2287         }
2288
2289         return _(l10n);
2290 }
2291
2292
2293 bool Buffer::isClean() const
2294 {
2295         return lyx_clean;
2296 }
2297
2298
2299 bool Buffer::isBakClean() const
2300 {
2301         return bak_clean;
2302 }
2303
2304
2305 void Buffer::markClean() const
2306 {
2307         if (!lyx_clean) {
2308                 lyx_clean = true;
2309                 updateTitles();
2310         }
2311         // if the .lyx file has been saved, we don't need an
2312         // autosave
2313         bak_clean = true;
2314 }
2315
2316
2317 void Buffer::markBakClean()
2318 {
2319         bak_clean = true;
2320 }
2321
2322
2323 void Buffer::setUnnamed(bool flag)
2324 {
2325         unnamed = flag;
2326 }
2327
2328
2329 bool Buffer::isUnnamed()
2330 {
2331         return unnamed;
2332 }
2333
2334
2335 void Buffer::markDirty()
2336 {
2337         if (lyx_clean) {
2338                 lyx_clean = false;
2339                 updateTitles();
2340         }
2341         bak_clean = false;
2342
2343         DepClean::iterator it = dep_clean_.begin();
2344         DepClean::const_iterator const end = dep_clean_.end();
2345
2346         for (; it != end; ++it) {
2347                 it->second = false;
2348         }
2349 }
2350
2351
2352 string const & Buffer::fileName() const
2353 {
2354         return filename_;
2355 }
2356
2357
2358 string const & Buffer::filePath() const
2359 {
2360         return filepath_;
2361 }
2362
2363
2364 bool Buffer::isReadonly() const
2365 {
2366         return read_only;
2367 }
2368
2369
2370 BufferView * Buffer::getUser() const
2371 {
2372         return users;
2373 }
2374
2375
2376 void Buffer::setParentName(string const & name)
2377 {
2378         params.parentname = name;
2379 }
2380
2381
2382 Buffer::inset_iterator::inset_iterator()
2383         : pit(), pend()
2384 {}
2385
2386
2387 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2388         : pit(p), pend(e)
2389 {
2390         setParagraph();
2391 }
2392
2393
2394 Buffer::inset_iterator Buffer::inset_iterator_begin()
2395 {
2396         return inset_iterator(paragraphs.begin(), paragraphs.end());
2397 }
2398
2399
2400 Buffer::inset_iterator Buffer::inset_iterator_end()
2401 {
2402         return inset_iterator(paragraphs.end(), paragraphs.end());
2403 }
2404
2405
2406 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
2407 {
2408         return inset_iterator(const_cast<ParagraphList&>(paragraphs).begin(),
2409                               const_cast<ParagraphList&>(paragraphs).end());
2410 }
2411
2412
2413 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
2414 {
2415         return inset_iterator(const_cast<ParagraphList&>(paragraphs).end(),
2416                               const_cast<ParagraphList&>(paragraphs).end());
2417 }
2418
2419
2420 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2421 {
2422         if (pit != pend) {
2423                 ++it;
2424                 if (it == pit->insetlist.end()) {
2425                         ++pit;
2426                         setParagraph();
2427                 }
2428         }
2429         return *this;
2430 }
2431
2432
2433 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2434 {
2435         inset_iterator tmp = *this;
2436         ++*this;
2437         return tmp;
2438 }
2439
2440
2441 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2442 {
2443         return *it->inset;
2444 }
2445
2446
2447 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2448 {
2449         return it->inset;
2450 }
2451
2452
2453 ParagraphList::iterator Buffer::inset_iterator::getPar() const
2454 {
2455         return pit;
2456 }
2457
2458
2459 lyx::pos_type Buffer::inset_iterator::getPos() const
2460 {
2461         return it->pos;
2462 }
2463
2464
2465 bool operator==(Buffer::inset_iterator const & iter1,
2466                 Buffer::inset_iterator const & iter2)
2467 {
2468         return iter1.pit == iter2.pit
2469                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2470 }
2471
2472
2473 bool operator!=(Buffer::inset_iterator const & iter1,
2474                 Buffer::inset_iterator const & iter2)
2475 {
2476         return !(iter1 == iter2);
2477 }