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