]> git.lyx.org Git - lyx.git/blob - src/buffer.C
567c168afba868e4e850bb23c018eadbc11de217
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14
15 #include "author.h"
16 #include "buffer_funcs.h"
17 #include "bufferlist.h"
18 #include "bufferparams.h"
19 #include "counters.h"
20 #include "Bullet.h"
21 #include "Chktex.h"
22 #include "debug.h"
23 #include "errorlist.h"
24 #include "exporter.h"
25 #include "format.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "iterators.h"
29 #include "language.h"
30 #include "LaTeX.h"
31 #include "LaTeXFeatures.h"
32 #include "LyXAction.h"
33 #include "lyxlex.h"
34 #include "lyxtext.h"
35 #include "lyxrc.h"
36 #include "lyxvc.h"
37 #include "lyx_main.h"
38 #include "messages.h"
39 #include "output.h"
40 #include "output_docbook.h"
41 #include "output_latex.h"
42 #include "output_linuxdoc.h"
43 #include "paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "PosIterator.h"
47 #include "sgml.h"
48 #include "texrow.h"
49 #include "undo.h"
50 #include "version.h"
51
52 #include "insets/insetbibitem.h"
53 #include "insets/insetbibtex.h"
54 #include "insets/insetinclude.h"
55 #include "insets/insettext.h"
56
57 #include "frontends/Alert.h"
58
59 #include "graphics/Previews.h"
60
61 #include "support/FileInfo.h"
62 #include "support/filetools.h"
63 #include "support/gzstream.h"
64 #include "support/lyxlib.h"
65 #include "support/os.h"
66 #include "support/path.h"
67 #include "support/textutils.h"
68 #include "support/tostr.h"
69
70 #include <boost/bind.hpp>
71
72 #include "support/std_sstream.h"
73
74 #include <iomanip>
75 #include <stack>
76
77 #include <utime.h>
78
79 #ifdef HAVE_LOCALE
80 #endif
81
82 using lyx::pos_type;
83
84 using lyx::support::AddName;
85 using lyx::support::atoi;
86 using lyx::support::bformat;
87 using lyx::support::ChangeExtension;
88 using lyx::support::cmd_ret;
89 using lyx::support::createBufferTmpDir;
90 using lyx::support::destroyDir;
91 using lyx::support::FileInfo;
92 using lyx::support::FileInfo;
93 using lyx::support::getExtFromContents;
94 using lyx::support::IsDirWriteable;
95 using lyx::support::IsFileWriteable;
96 using lyx::support::LibFileSearch;
97 using lyx::support::ltrim;
98 using lyx::support::MakeAbsPath;
99 using lyx::support::MakeDisplayPath;
100 using lyx::support::MakeLatexName;
101 using lyx::support::OnlyFilename;
102 using lyx::support::OnlyPath;
103 using lyx::support::Path;
104 using lyx::support::QuoteName;
105 using lyx::support::removeAutosaveFile;
106 using lyx::support::rename;
107 using lyx::support::RunCommand;
108 using lyx::support::split;
109 using lyx::support::strToInt;
110 using lyx::support::subst;
111 using lyx::support::tempName;
112 using lyx::support::trim;
113
114 namespace os = lyx::support::os;
115
116 using std::endl;
117 using std::for_each;
118 using std::make_pair;
119
120 using std::ifstream;
121 using std::ios;
122 using std::ostream;
123 using std::ostringstream;
124 using std::ofstream;
125 using std::pair;
126 using std::stack;
127 using std::vector;
128 using std::string;
129
130
131 // all these externs should eventually be removed.
132 extern BufferList bufferlist;
133
134 namespace {
135
136 const int LYX_FORMAT = 229;
137
138 } // namespace anon
139
140
141 typedef std::map<string, bool> DepClean;
142
143 struct Buffer::Impl
144 {
145         Impl(Buffer & parent, string const & file, bool readonly);
146
147         limited_stack<Undo> undostack;
148         limited_stack<Undo> redostack;
149         BufferParams params;
150         LyXVC lyxvc;
151         string temppath;
152         TexRow texrow;
153
154         /// need to regenerate .tex?
155         DepClean dep_clean;
156
157         /// is save needed?
158         mutable bool lyx_clean;
159
160         /// is autosave needed?
161         mutable bool bak_clean;
162
163         /// is this a unnamed file (New...)?
164         bool unnamed;
165
166         /// buffer is r/o
167         bool read_only;
168
169         /// name of the file the buffer is associated with.
170         string filename;
171
172         /// The path to the document file.
173         string filepath;
174
175         boost::scoped_ptr<Messages> messages;
176
177         /** Set to true only when the file is fully loaded.
178          *  Used to prevent the premature generation of previews
179          *  and by the citation inset.
180          */
181         bool file_fully_loaded;
182
183         /// our text
184         LyXText text;
185 };
186
187
188 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
189         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
190           filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
191                 text(0, 0)
192 {
193         lyxvc.buffer(&parent);
194         temppath = createBufferTmpDir();
195         // FIXME: And now do something if temppath == string(), because we
196         // assume from now on that temppath points to a valid temp dir.
197         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
198 }
199
200
201 Buffer::Buffer(string const & file, bool ronly)
202         : pimpl_(new Impl(*this, file, ronly))
203 {
204         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
205 }
206
207
208 Buffer::~Buffer()
209 {
210         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
211         // here the buffer should take care that it is
212         // saved properly, before it goes into the void.
213
214         closing();
215
216         if (!temppath().empty() && destroyDir(temppath()) != 0) {
217                 Alert::warning(_("Could not remove temporary directory"),
218                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
219         }
220
221         // Remove any previewed LaTeX snippets associated with this buffer.
222         lyx::graphics::Previews::get().removeLoader(*this);
223 }
224
225
226 LyXText & Buffer::text() const
227 {
228         return const_cast<LyXText &>(pimpl_->text);
229 }
230
231
232 limited_stack<Undo> & Buffer::undostack()
233 {
234         return pimpl_->undostack;
235 }
236
237
238 limited_stack<Undo> const & Buffer::undostack() const
239 {
240         return pimpl_->undostack;
241 }
242
243
244 limited_stack<Undo> & Buffer::redostack()
245 {
246         return pimpl_->redostack;
247 }
248
249
250 limited_stack<Undo> const & Buffer::redostack() const
251 {
252         return pimpl_->redostack;
253 }
254
255
256 BufferParams & Buffer::params()
257 {
258         return pimpl_->params;
259 }
260
261
262 BufferParams const & Buffer::params() const
263 {
264         return pimpl_->params;
265 }
266
267
268 ParagraphList & Buffer::paragraphs()
269 {
270         return pimpl_->text.paragraphs();
271 }
272
273
274 ParagraphList const & Buffer::paragraphs() const
275 {
276         return pimpl_->text.paragraphs();
277 }
278
279
280 LyXVC & Buffer::lyxvc()
281 {
282         return pimpl_->lyxvc;
283 }
284
285
286 LyXVC const & Buffer::lyxvc() const
287 {
288         return pimpl_->lyxvc;
289 }
290
291
292 string const & Buffer::temppath() const
293 {
294         return pimpl_->temppath;
295 }
296
297
298 TexRow & Buffer::texrow()
299 {
300         return pimpl_->texrow;
301 }
302
303
304 TexRow const & Buffer::texrow() const
305 {
306         return pimpl_->texrow;
307 }
308
309
310 string const Buffer::getLatexName(bool no_path) const
311 {
312         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
313         return no_path ? OnlyFilename(name) : name;
314 }
315
316
317 pair<Buffer::LogType, string> const Buffer::getLogName() const
318 {
319         string const filename = getLatexName(false);
320
321         if (filename.empty())
322                 return make_pair(Buffer::latexlog, string());
323
324         string const path = temppath();
325
326         string const fname = AddName(path,
327                                      OnlyFilename(ChangeExtension(filename,
328                                                                   ".log")));
329         string const bname =
330                 AddName(path, OnlyFilename(
331                         ChangeExtension(filename,
332                                         formats.extension("literate") + ".out")));
333
334         // If no Latex log or Build log is newer, show Build log
335
336         FileInfo const f_fi(fname);
337         FileInfo const b_fi(bname);
338
339         if (b_fi.exist() &&
340             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
341                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
342                 return make_pair(Buffer::buildlog, bname);
343         }
344         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
345         return make_pair(Buffer::latexlog, fname);
346 }
347
348
349 void Buffer::setReadonly(bool flag)
350 {
351         if (pimpl_->read_only != flag) {
352                 pimpl_->read_only = flag;
353                 readonly(flag);
354         }
355 }
356
357
358 void Buffer::setFileName(string const & newfile)
359 {
360         pimpl_->filename = MakeAbsPath(newfile);
361         pimpl_->filepath = OnlyPath(pimpl_->filename);
362         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
363         updateTitles();
364 }
365
366
367 // We'll remove this later. (Lgb)
368 namespace {
369
370 void unknownClass(string const & unknown)
371 {
372         Alert::warning(_("Unknown document class"),
373                 bformat(_("Using the default document class, because the "
374                         "class %1$s is unknown."), unknown));
375 }
376
377 } // anon
378
379
380 int Buffer::readHeader(LyXLex & lex)
381 {
382         int unknown_tokens = 0;
383
384         while (lex.isOK()) {
385                 lex.nextToken();
386                 string const token = lex.getString();
387
388                 if (token.empty())
389                         continue;
390
391                 if (token == "\\end_header")
392                         break;
393
394                 lyxerr[Debug::PARSER] << "Handling header token: `"
395                                       << token << '\'' << endl;
396
397
398                 string unknown = params().readToken(lex, token);
399                 if (!unknown.empty()) {
400                         if (unknown[0] != '\\') {
401                                 unknownClass(unknown);
402                         } else {
403                                 ++unknown_tokens;
404                                 string const s = bformat(_("Unknown token: "
405                                                            "%1$s %2$s\n"),
406                                                          token,
407                                                          lex.getString());
408                                 error(ErrorItem(_("Header error"), s,
409                                                 -1, 0, 0));
410                         }
411                 }
412         }
413         return unknown_tokens;
414 }
415
416
417 // candidate for move to BufferView
418 // (at least some parts in the beginning of the func)
419 //
420 // Uwe C. Schroeder
421 // changed to be public and have one parameter
422 // if par = 0 normal behavior
423 // else insert behavior
424 // Returns false if "\end_document" is not read (Asger)
425 bool Buffer::readBody(LyXLex & lex)
426 {
427         bool the_end_read = false;
428
429         if (paragraphs().empty()) {
430                 readHeader(lex);
431                 if (!params().getLyXTextClass().load()) {
432                         string theclass = params().getLyXTextClass().name();
433                         Alert::error(_("Can't load document class"), bformat(
434                                         "Using the default document class, because the "
435                                         " class %1$s could not be loaded.", theclass));
436                         params().textclass = 0;
437                 }
438         } else {
439                 // We don't want to adopt the parameters from the
440                 // document we insert, so read them into a temporary buffer
441                 // and then discard it
442
443                 Buffer tmpbuf("", false);
444                 tmpbuf.readHeader(lex);
445         }
446
447         if (text().read(*this, lex))
448                 the_end_read = true;
449
450         return the_end_read;
451 }
452
453
454 // needed to insert the selection
455 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
456                                  LyXFont const & fn, string const & str)
457 {
458         LyXLayout_ptr const & layout = par->layout();
459
460         LyXFont font = fn;
461
462         par->checkInsertChar(font);
463         // insert the string, don't insert doublespace
464         bool space_inserted = true;
465         bool autobreakrows = !par->inInset() ||
466                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
467         for(string::const_iterator cit = str.begin();
468             cit != str.end(); ++cit) {
469                 if (*cit == '\n') {
470                         if (autobreakrows && (!par->empty() || par->allowEmpty())) {
471                                 breakParagraph(params(), paragraphs(), par, pos,
472                                                layout->isEnvironment());
473                                 ++par;
474                                 pos = 0;
475                                 space_inserted = true;
476                         } else {
477                                 continue;
478                         }
479                         // do not insert consecutive spaces if !free_spacing
480                 } else if ((*cit == ' ' || *cit == '\t') &&
481                            space_inserted && !par->isFreeSpacing()) {
482                         continue;
483                 } else if (*cit == '\t') {
484                         if (!par->isFreeSpacing()) {
485                                 // tabs are like spaces here
486                                 par->insertChar(pos, ' ', font);
487                                 ++pos;
488                                 space_inserted = true;
489                         } else {
490                                 const pos_type n = 8 - pos % 8;
491                                 for (pos_type i = 0; i < n; ++i) {
492                                         par->insertChar(pos, ' ', font);
493                                         ++pos;
494                                 }
495                                 space_inserted = true;
496                         }
497                 } else if (!IsPrintable(*cit)) {
498                         // Ignore unprintables
499                         continue;
500                 } else {
501                         // just insert the character
502                         par->insertChar(pos, *cit, font);
503                         ++pos;
504                         space_inserted = (*cit == ' ');
505                 }
506
507         }
508 }
509
510
511 bool Buffer::readFile(string const & filename)
512 {
513         // Check if the file is compressed.
514         string const format = getExtFromContents(filename);
515         if (format == "gzip" || format == "zip" || format == "compress") {
516                 params().compressed = true;
517         }
518
519         bool ret = readFile(filename, paragraphs().begin());
520
521         // After we have read a file, we must ensure that the buffer
522         // language is set and used in the gui.
523         // If you know of a better place to put this, please tell me. (Lgb)
524         updateDocLang(params().language);
525
526         return ret;
527 }
528
529
530 bool Buffer::readFile(string const & filename, ParagraphList::iterator pit)
531 {
532         LyXLex lex(0, 0);
533         lex.setFile(filename);
534         return readFile(lex, filename, pit);
535 }
536
537
538 bool Buffer::fully_loaded() const
539 {
540         return pimpl_->file_fully_loaded;
541 }
542
543
544 void Buffer::fully_loaded(bool value)
545 {
546         pimpl_->file_fully_loaded = value;
547 }
548
549
550 bool Buffer::readFile(LyXLex & lex, string const & filename,
551                       ParagraphList::iterator pit)
552 {
553         BOOST_ASSERT(!filename.empty());
554
555         if (!lex.isOK()) {
556                 Alert::error(_("Document could not be read"),
557                              bformat(_("%1$s could not be read."), filename));
558                 return false;
559         }
560
561         lex.next();
562         string const token(lex.getString());
563
564         if (!lex.isOK()) {
565                 Alert::error(_("Document could not be read"),
566                              bformat(_("%1$s could not be read."), filename));
567                 return false;
568         }
569
570         // the first token _must_ be...
571         if (token != "\\lyxformat") {
572                 lyxerr << "Token: " << token << endl;
573
574                 Alert::error(_("Document format failure"),
575                              bformat(_("%1$s is not a LyX document."),
576                                        filename));
577                 return false;
578         }
579
580         lex.eatLine();
581         string tmp_format = lex.getString();
582         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
583         // if present remove ".," from string.
584         string::size_type dot = tmp_format.find_first_of(".,");
585         //lyxerr << "           dot found at " << dot << endl;
586         if (dot != string::npos)
587                         tmp_format.erase(dot, 1);
588         int file_format = strToInt(tmp_format);
589         //lyxerr << "format: " << file_format << endl;
590
591         if (file_format > LYX_FORMAT) {
592                 Alert::warning(_("Document format failure"),
593                                bformat(_("%1$s was created with a newer"
594                                          " version of LyX. This is likely to"
595                                          " cause problems."),
596                                          filename));
597         } else if (file_format < LYX_FORMAT) {
598                 string const tmpfile = tempName();
599                 if (tmpfile.empty()) {
600                         Alert::error(_("Conversion failed"),
601                                      bformat(_("%1$s is from an earlier"
602                                               " version of LyX, but a temporary"
603                                               " file for converting it could"
604                                               " not be created."),
605                                               filename));
606                         return false;
607                 }
608                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
609                 if (command.empty()) {
610                         Alert::error(_("Conversion script not found"),
611                                      bformat(_("%1$s is from an earlier"
612                                                " version of LyX, but the"
613                                                " conversion script lyx2lyx"
614                                                " could not be found."),
615                                                filename));
616                         return false;
617                 }
618                 command += " -t"
619                         + tostr(LYX_FORMAT)
620                         + " -o " + tmpfile + ' '
621                         + QuoteName(filename);
622                 lyxerr[Debug::INFO] << "Running '"
623                                     << command << '\''
624                                     << endl;
625                 cmd_ret const ret = RunCommand(command);
626                 if (ret.first != 0) {
627                         Alert::error(_("Conversion script failed"),
628                                      bformat(_("%1$s is from an earlier version"
629                                               " of LyX, but the lyx2lyx script"
630                                               " failed to convert it."),
631                                               filename));
632                         return false;
633                 } else {
634                         bool ret = readFile(tmpfile, pit);
635                         // Do stuff with tmpfile name and buffer name here.
636                         return ret;
637                 }
638
639         }
640
641         bool the_end = readBody(lex);
642         params().setPaperStuff();
643
644         if (!the_end) {
645                 Alert::error(_("Document format failure"),
646                              bformat(_("%1$s ended unexpectedly, which means"
647                                        " that it is probably corrupted."),
648                                        filename));
649         }
650         pimpl_->file_fully_loaded = true;
651         return true;
652 }
653
654
655 // Should probably be moved to somewhere else: BufferView? LyXView?
656 bool Buffer::save() const
657 {
658         // We don't need autosaves in the immediate future. (Asger)
659         resetAutosaveTimers();
660
661         // make a backup
662         string s;
663         if (lyxrc.make_backup) {
664                 s = fileName() + '~';
665                 if (!lyxrc.backupdir_path.empty())
666                         s = AddName(lyxrc.backupdir_path,
667                                     subst(os::slashify_path(s),'/','!'));
668
669                 // Rename is the wrong way of making a backup,
670                 // this is the correct way.
671                 /* truss cp fil fil2:
672                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
673                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
674                    open("LyXVC.lyx", O_RDONLY)                     = 3
675                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
676                    fstat(4, 0xEFFFF508)                            = 0
677                    fstat(3, 0xEFFFF508)                            = 0
678                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
679                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
680                    read(3, 0xEFFFD4A0, 8192)                       = 0
681                    close(4)                                        = 0
682                    close(3)                                        = 0
683                    chmod("LyXVC3.lyx", 0100644)                    = 0
684                    lseek(0, 0, SEEK_CUR)                           = 46440
685                    _exit(0)
686                 */
687
688                 // Should probably have some more error checking here.
689                 // Doing it this way, also makes the inodes stay the same.
690                 // This is still not a very good solution, in particular we
691                 // might loose the owner of the backup.
692                 FileInfo finfo(fileName());
693                 if (finfo.exist()) {
694                         mode_t fmode = finfo.getMode();
695                         struct utimbuf times = {
696                                 finfo.getAccessTime(),
697                                 finfo.getModificationTime() };
698
699                         ifstream ifs(fileName().c_str());
700                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
701                         if (ifs && ofs) {
702                                 ofs << ifs.rdbuf();
703                                 ifs.close();
704                                 ofs.close();
705                                 ::chmod(s.c_str(), fmode);
706
707                                 if (::utime(s.c_str(), &times)) {
708                                         lyxerr << "utime error." << endl;
709                                 }
710                         } else {
711                                 lyxerr << "LyX was not able to make "
712                                         "backup copy. Beware." << endl;
713                         }
714                 }
715         }
716
717         if (writeFile(fileName())) {
718                 markClean();
719                 removeAutosaveFile(fileName());
720         } else {
721                 // Saving failed, so backup is not backup
722                 if (lyxrc.make_backup)
723                         rename(s, fileName());
724                 return false;
725         }
726         return true;
727 }
728
729
730 bool Buffer::writeFile(string const & fname) const
731 {
732         if (pimpl_->read_only && fname == fileName())
733                 return false;
734
735         FileInfo finfo(fname);
736         if (finfo.exist() && !finfo.writable())
737                 return false;
738
739         bool retval;
740
741         if (params().compressed) {
742                 gz::ogzstream ofs(fname.c_str());
743                 if (!ofs)
744                         return false;
745
746                 retval = do_writeFile(ofs);
747
748         } else {
749                 ofstream ofs(fname.c_str());
750                 if (!ofs)
751                         return false;
752
753                 retval = do_writeFile(ofs);
754         }
755
756         return retval;
757 }
758
759
760 bool Buffer::do_writeFile(ostream & ofs) const
761 {
762 #ifdef HAVE_LOCALE
763         // Use the standard "C" locale for file output.
764         ofs.imbue(std::locale::classic());
765 #endif
766
767         // The top of the file should not be written by params().
768
769         // write out a comment in the top of the file
770         ofs << "#LyX " << lyx_version
771             << " created this file. For more info see http://www.lyx.org/\n"
772             << "\\lyxformat " << LYX_FORMAT << "\n";
773
774         // now write out the buffer parameters.
775         params().writeFile(ofs);
776
777         ofs << "\\end_header\n";
778
779         // write the text
780         text().write(*this, ofs);
781
782         // Write marker that shows file is complete
783         ofs << "\n\\end_document" << endl;
784
785         // Shouldn't really be needed....
786         //ofs.close();
787
788         // how to check if close went ok?
789         // Following is an attempt... (BE 20001011)
790
791         // good() returns false if any error occured, including some
792         //        formatting error.
793         // bad()  returns true if something bad happened in the buffer,
794         //        which should include file system full errors.
795
796         bool status = true;
797         if (!ofs) {
798                 status = false;
799                 lyxerr << "File was not closed properly." << endl;
800         }
801
802         return status;
803 }
804
805
806 void Buffer::makeLaTeXFile(string const & fname,
807                            string const & original_path,
808                            OutputParams const & runparams,
809                            bool output_preamble, bool output_body)
810 {
811         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
812
813         ofstream ofs;
814         if (!openFileWrite(ofs, fname))
815                 return;
816
817         makeLaTeXFile(ofs, original_path,
818                       runparams, output_preamble, output_body);
819
820         ofs.close();
821         if (ofs.fail())
822                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
823 }
824
825
826 void Buffer::makeLaTeXFile(ostream & os,
827                            string const & original_path,
828                            OutputParams const & runparams_in,
829                            bool output_preamble, bool output_body)
830 {
831         OutputParams runparams = runparams_in;
832
833         // validate the buffer.
834         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
835         LaTeXFeatures features(*this, params(), runparams.nice);
836         validate(features);
837         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
838
839         texrow().reset();
840         // The starting paragraph of the coming rows is the
841         // first paragraph of the document. (Asger)
842         texrow().start(paragraphs().begin()->id(), 0);
843
844         if (output_preamble && runparams.nice) {
845                 os << "%% LyX " << lyx_version << " created this file.  "
846                         "For more info, see http://www.lyx.org/.\n"
847                         "%% Do not edit unless you really know what "
848                         "you are doing.\n";
849                 texrow().newline();
850                 texrow().newline();
851         }
852         lyxerr[Debug::INFO] << "lyx header finished" << endl;
853         // There are a few differences between nice LaTeX and usual files:
854         // usual is \batchmode and has a
855         // special input@path to allow the including of figures
856         // with either \input or \includegraphics (what figinsets do).
857         // input@path is set when the actual parameter
858         // original_path is set. This is done for usual tex-file, but not
859         // for nice-latex-file. (Matthias 250696)
860         if (output_preamble) {
861                 if (!runparams.nice) {
862                         // code for usual, NOT nice-latex-file
863                         os << "\\batchmode\n"; // changed
864                         // from \nonstopmode
865                         texrow().newline();
866                 }
867                 if (!original_path.empty()) {
868                         string inputpath = os::external_path(original_path);
869                         subst(inputpath, "~", "\\string~");
870                         os << "\\makeatletter\n"
871                             << "\\def\\input@path{{"
872                             << inputpath << "/}}\n"
873                             << "\\makeatother\n";
874                         texrow().newline();
875                         texrow().newline();
876                         texrow().newline();
877                 }
878
879                 // Write the preamble
880                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
881
882                 if (!output_body)
883                         return;
884
885                 // make the body.
886                 os << "\\begin{document}\n";
887                 texrow().newline();
888         } // output_preamble
889         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
890
891         if (!lyxrc.language_auto_begin) {
892                 os << subst(lyxrc.language_command_begin, "$$lang",
893                              params().language->babel())
894                     << endl;
895                 texrow().newline();
896         }
897
898         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
899
900         // add this just in case after all the paragraphs
901         os << endl;
902         texrow().newline();
903
904         if (!lyxrc.language_auto_end) {
905                 os << subst(lyxrc.language_command_end, "$$lang",
906                              params().language->babel())
907                     << endl;
908                 texrow().newline();
909         }
910
911         if (output_preamble) {
912                 os << "\\end{document}\n";
913                 texrow().newline();
914
915                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
916         } else {
917                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
918                                      << endl;
919         }
920
921         // Just to be sure. (Asger)
922         texrow().newline();
923
924         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
925         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
926                             << '.' << endl;
927 }
928
929
930 bool Buffer::isLatex() const
931 {
932         return params().getLyXTextClass().outputType() == LATEX;
933 }
934
935
936 bool Buffer::isLinuxDoc() const
937 {
938         return params().getLyXTextClass().outputType() == LINUXDOC;
939 }
940
941
942 bool Buffer::isLiterate() const
943 {
944         return params().getLyXTextClass().outputType() == LITERATE;
945 }
946
947
948 bool Buffer::isDocBook() const
949 {
950         return params().getLyXTextClass().outputType() == DOCBOOK;
951 }
952
953
954 bool Buffer::isSGML() const
955 {
956         LyXTextClass const & tclass = params().getLyXTextClass();
957
958         return tclass.outputType() == LINUXDOC ||
959                tclass.outputType() == DOCBOOK;
960 }
961
962
963 void Buffer::makeLinuxDocFile(string const & fname,
964                               OutputParams const & runparams,
965                               bool body_only)
966 {
967         ofstream ofs;
968         if (!openFileWrite(ofs, fname))
969                 return;
970
971         LaTeXFeatures features(*this, params(), runparams.nice);
972         validate(features);
973
974         texrow().reset();
975
976         LyXTextClass const & tclass = params().getLyXTextClass();
977
978         string top_element = tclass.latexname();
979
980         if (!body_only) {
981                 ofs << tclass.class_header();
982
983                 string preamble = params().preamble;
984                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
985                          : fname;
986                 preamble += features.getIncludedFiles(name);
987                 preamble += features.getLyXSGMLEntities();
988
989                 if (!preamble.empty()) {
990                         ofs << " [ " << preamble << " ]";
991                 }
992                 ofs << ">\n\n";
993
994                 if (params().options.empty())
995                         sgml::openTag(ofs, 0, false, top_element);
996                 else {
997                         string top = top_element;
998                         top += ' ';
999                         top += params().options;
1000                         sgml::openTag(ofs, 0, false, top);
1001                 }
1002         }
1003
1004         ofs << "<!-- LyX "  << lyx_version
1005             << " created this file. For more info see http://www.lyx.org/"
1006             << " -->\n";
1007
1008         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1009
1010         if (!body_only) {
1011                 ofs << "\n\n";
1012                 sgml::closeTag(ofs, 0, false, top_element);
1013         }
1014
1015         ofs.close();
1016         if (ofs.fail())
1017                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1018 }
1019
1020
1021 void Buffer::makeDocBookFile(string const & fname,
1022                              OutputParams const & runparams,
1023                              bool only_body)
1024 {
1025         ofstream ofs;
1026         if (!openFileWrite(ofs, fname))
1027                 return;
1028
1029         LaTeXFeatures features(*this, params(), runparams.nice);
1030         validate(features);
1031
1032         texrow().reset();
1033
1034         LyXTextClass const & tclass = params().getLyXTextClass();
1035         string top_element = tclass.latexname();
1036
1037         if (!only_body) {
1038                 ofs << subst(tclass.class_header(), "#", top_element);
1039
1040                 string preamble = params().preamble;
1041                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1042                          : fname;
1043                 preamble += features.getIncludedFiles(name);
1044                 preamble += features.getLyXSGMLEntities();
1045
1046                 if (!preamble.empty()) {
1047                         ofs << "\n [ " << preamble << " ]";
1048                 }
1049                 ofs << ">\n\n";
1050         }
1051
1052         string top = top_element;
1053         top += " lang=\"";
1054         top += params().language->code();
1055         top += '"';
1056
1057         if (!params().options.empty()) {
1058                 top += ' ';
1059                 top += params().options;
1060         }
1061         sgml::openTag(ofs, 0, false, top);
1062
1063         ofs << "<!-- SGML/XML file was created by LyX " << lyx_version
1064             << "\n  See http://www.lyx.org/ for more information -->\n";
1065
1066         params().getLyXTextClass().counters().reset();
1067         docbookParagraphs(*this, paragraphs(), ofs, runparams);
1068
1069         ofs << "\n\n";
1070         sgml::closeTag(ofs, 0, false, top_element);
1071
1072         ofs.close();
1073         if (ofs.fail())
1074                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1075 }
1076
1077
1078 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1079 // Other flags: -wall -v0 -x
1080 int Buffer::runChktex()
1081 {
1082         busy(true);
1083
1084         // get LaTeX-Filename
1085         string const name = getLatexName();
1086         string const path = temppath();
1087         string const org_path = filePath();
1088
1089         Path p(path); // path to LaTeX file
1090         message(_("Running chktex..."));
1091
1092         // Generate the LaTeX file if neccessary
1093         OutputParams runparams;
1094         runparams.flavor = OutputParams::LATEX;
1095         runparams.nice = false;
1096         makeLaTeXFile(name, org_path, runparams);
1097
1098         TeXErrors terr;
1099         Chktex chktex(lyxrc.chktex_command, name, filePath());
1100         int res = chktex.run(terr); // run chktex
1101
1102         if (res == -1) {
1103                 Alert::error(_("chktex failure"),
1104                              _("Could not run chktex successfully."));
1105         } else if (res > 0) {
1106                 // Insert all errors as errors boxes
1107                 bufferErrors(*this, terr);
1108         }
1109
1110         busy(false);
1111
1112         return res;
1113 }
1114
1115
1116 void Buffer::validate(LaTeXFeatures & features) const
1117 {
1118         LyXTextClass const & tclass = params().getLyXTextClass();
1119
1120         if (params().tracking_changes) {
1121                 features.require("dvipost");
1122                 features.require("color");
1123         }
1124
1125         // AMS Style is at document level
1126         if (params().use_amsmath == BufferParams::AMS_ON
1127             || tclass.provides(LyXTextClass::amsmath))
1128                 features.require("amsmath");
1129
1130         for_each(paragraphs().begin(), paragraphs().end(),
1131                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1132
1133         // the bullet shapes are buffer level not paragraph level
1134         // so they are tested here
1135         for (int i = 0; i < 4; ++i) {
1136                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1137                         int const font = params().user_defined_bullet(i).getFont();
1138                         if (font == 0) {
1139                                 int const c = params()
1140                                         .user_defined_bullet(i)
1141                                         .getCharacter();
1142                                 if (c == 16
1143                                    || c == 17
1144                                    || c == 25
1145                                    || c == 26
1146                                    || c == 31) {
1147                                         features.require("latexsym");
1148                                 }
1149                         } else if (font == 1) {
1150                                 features.require("amssymb");
1151                         } else if ((font >= 2 && font <= 5)) {
1152                                 features.require("pifont");
1153                         }
1154                 }
1155         }
1156
1157         if (lyxerr.debugging(Debug::LATEX)) {
1158                 features.showStruct();
1159         }
1160 }
1161
1162
1163 void Buffer::getLabelList(std::vector<string> & list) const
1164 {
1165         /// if this is a child document and the parent is already loaded
1166         /// Use the parent's list instead  [ale990407]
1167         if (!params().parentname.empty()
1168             && bufferlist.exists(params().parentname)) {
1169                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1170                 if (tmp) {
1171                         tmp->getLabelList(list);
1172                         return;
1173                 }
1174         }
1175
1176         for (inset_iterator it = inset_const_iterator_begin();
1177              it != inset_const_iterator_end(); ++it) {
1178                 it->getLabelList(*this, list);
1179         }
1180 }
1181
1182
1183 // This is also a buffer property (ale)
1184 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys)
1185         const
1186 {
1187         /// if this is a child document and the parent is already loaded
1188         /// use the parent's list instead  [ale990412]
1189         if (!params().parentname.empty() &&
1190             bufferlist.exists(params().parentname)) {
1191                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1192                 if (tmp) {
1193                         tmp->fillWithBibKeys(keys);
1194                         return;
1195                 }
1196         }
1197
1198         for (inset_iterator it = inset_const_iterator_begin();
1199                 it != inset_const_iterator_end(); ++it) {
1200                 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1201                         InsetBibtex const & inset =
1202                                 dynamic_cast<InsetBibtex const &>(*it);
1203                         inset.fillWithBibKeys(*this, keys);
1204                 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1205                         InsetInclude const & inset =
1206                                 dynamic_cast<InsetInclude const &>(*it);
1207                         inset.fillWithBibKeys(*this, keys);
1208                 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1209                         InsetBibitem const & inset =
1210                                 dynamic_cast<InsetBibitem const &>(*it);
1211                         string const key = inset.getContents();
1212                         string const opt = inset.getOptions();
1213                         string const ref; // = pit->asString(this, false);
1214                         string const info = opt + "TheBibliographyRef" + ref;
1215                         keys.push_back(pair<string, string>(key, info));
1216                 }
1217         }
1218 }
1219
1220
1221 bool Buffer::isDepClean(string const & name) const
1222 {
1223         DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1224         if (it == pimpl_->dep_clean.end())
1225                 return true;
1226         return it->second;
1227 }
1228
1229
1230 void Buffer::markDepClean(string const & name)
1231 {
1232         pimpl_->dep_clean[name] = true;
1233 }
1234
1235
1236 bool Buffer::dispatch(string const & command, bool * result)
1237 {
1238         return dispatch(lyxaction.lookupFunc(command), result);
1239 }
1240
1241
1242 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1243 {
1244         bool dispatched = true;
1245
1246         switch (func.action) {
1247                 case LFUN_EXPORT: {
1248                         bool const tmp = Exporter::Export(this, func.argument, false);
1249                         if (result)
1250                                 *result = tmp;
1251                         break;
1252                 }
1253
1254                 default:
1255                         dispatched = false;
1256         }
1257         return dispatched;
1258 }
1259
1260
1261 void Buffer::changeLanguage(Language const * from, Language const * to)
1262 {
1263         lyxerr << "Changing Language!" << endl;
1264
1265         // Take care of l10n/i18n
1266         updateDocLang(to);
1267
1268         ParIterator end = par_iterator_end();
1269         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1270                 it->changeLanguage(params(), from, to);
1271 }
1272
1273
1274 void Buffer::updateDocLang(Language const * nlang)
1275 {
1276         pimpl_->messages.reset(new Messages(nlang->code()));
1277 }
1278
1279
1280 bool Buffer::isMultiLingual() const
1281 {
1282         ParConstIterator end = par_iterator_end();
1283         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1284                 if (it->isMultiLingual(params()))
1285                         return true;
1286
1287         return false;
1288 }
1289
1290
1291 void Buffer::inset_iterator::setParagraph()
1292 {
1293         while (pit != pend) {
1294                 it = pit->insetlist.begin();
1295                 if (it != pit->insetlist.end())
1296                         return;
1297                 ++pit;
1298         }
1299 }
1300
1301
1302 ParIterator Buffer::getParFromID(int id) const
1303 {
1304 #warning FIXME: const correctness! (Andre)
1305         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
1306         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
1307
1308 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
1309         if (id < 0) {
1310                 // John says this is called with id == -1 from undo
1311                 lyxerr << "getParFromID(), id: " << id << endl;
1312                 return end;
1313         }
1314
1315         for (; it != end; ++it)
1316                 if (it->id() == id)
1317                         return it;
1318
1319         return end;
1320 }
1321
1322
1323 bool Buffer::hasParWithID(int id) const
1324 {
1325         ParConstIterator it = par_iterator_begin();
1326         ParConstIterator end = par_iterator_end();
1327
1328         if (id < 0) {
1329                 // John says this is called with id == -1 from undo
1330                 lyxerr << "hasParWithID(), id: " << id << endl;
1331                 return 0;
1332         }
1333
1334         for (; it != end; ++it)
1335                 if (it->id() == id)
1336                         return true;
1337
1338         return false;
1339 }
1340
1341
1342 PosIterator Buffer::pos_iterator_begin()
1343 {
1344         return PosIterator(&paragraphs(), paragraphs().begin(), 0);
1345 }
1346
1347
1348 PosIterator Buffer::pos_iterator_end()
1349 {
1350         return PosIterator(&paragraphs(), paragraphs().end(), 0);
1351 }
1352
1353
1354 ParIterator Buffer::par_iterator_begin()
1355 {
1356         return ParIterator(paragraphs().begin(), paragraphs());
1357 }
1358
1359
1360 ParIterator Buffer::par_iterator_end()
1361 {
1362         return ParIterator(paragraphs().end(), paragraphs());
1363 }
1364
1365
1366 ParConstIterator Buffer::par_iterator_begin() const
1367 {
1368         ParagraphList const & pars = paragraphs();
1369         return ParConstIterator(const_cast<ParagraphList&>(pars).begin(), pars);
1370 }
1371
1372
1373 ParConstIterator Buffer::par_iterator_end() const
1374 {
1375         ParagraphList const & pars = paragraphs();
1376         return ParConstIterator(const_cast<ParagraphList&>(pars).end(), pars);
1377 }
1378
1379
1380 Language const * Buffer::getLanguage() const
1381 {
1382         return params().language;
1383 }
1384
1385
1386 string const Buffer::B_(string const & l10n) const
1387 {
1388         if (pimpl_->messages.get()) {
1389                 return pimpl_->messages->get(l10n);
1390         }
1391
1392         return _(l10n);
1393 }
1394
1395
1396 bool Buffer::isClean() const
1397 {
1398         return pimpl_->lyx_clean;
1399 }
1400
1401
1402 bool Buffer::isBakClean() const
1403 {
1404         return pimpl_->bak_clean;
1405 }
1406
1407
1408 void Buffer::markClean() const
1409 {
1410         if (!pimpl_->lyx_clean) {
1411                 pimpl_->lyx_clean = true;
1412                 updateTitles();
1413         }
1414         // if the .lyx file has been saved, we don't need an
1415         // autosave
1416         pimpl_->bak_clean = true;
1417 }
1418
1419
1420 void Buffer::markBakClean()
1421 {
1422         pimpl_->bak_clean = true;
1423 }
1424
1425
1426 void Buffer::setUnnamed(bool flag)
1427 {
1428         pimpl_->unnamed = flag;
1429 }
1430
1431
1432 bool Buffer::isUnnamed() const
1433 {
1434         return pimpl_->unnamed;
1435 }
1436
1437
1438 void Buffer::markDirty()
1439 {
1440         if (pimpl_->lyx_clean) {
1441                 pimpl_->lyx_clean = false;
1442                 updateTitles();
1443         }
1444         pimpl_->bak_clean = false;
1445
1446         DepClean::iterator it = pimpl_->dep_clean.begin();
1447         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1448
1449         for (; it != end; ++it) {
1450                 it->second = false;
1451         }
1452 }
1453
1454
1455 string const & Buffer::fileName() const
1456 {
1457         return pimpl_->filename;
1458 }
1459
1460
1461 string const & Buffer::filePath() const
1462 {
1463         return pimpl_->filepath;
1464 }
1465
1466
1467 bool Buffer::isReadonly() const
1468 {
1469         return pimpl_->read_only;
1470 }
1471
1472
1473 void Buffer::setParentName(string const & name)
1474 {
1475         params().parentname = name;
1476 }
1477
1478
1479 Buffer::inset_iterator::inset_iterator()
1480         : pit(), pend()
1481 {}
1482
1483
1484 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
1485         : pit(p), pend(e)
1486 {
1487         setParagraph();
1488 }
1489
1490
1491 Buffer::inset_iterator Buffer::inset_iterator_begin()
1492 {
1493         return inset_iterator(paragraphs().begin(), paragraphs().end());
1494 }
1495
1496
1497 Buffer::inset_iterator Buffer::inset_iterator_end()
1498 {
1499         return inset_iterator(paragraphs().end(), paragraphs().end());
1500 }
1501
1502
1503 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
1504 {
1505         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1506         return inset_iterator(pars.begin(), pars.end());
1507 }
1508
1509
1510 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
1511 {
1512         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1513         return inset_iterator(pars.end(), pars.end());
1514 }
1515
1516
1517 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
1518 {
1519         if (pit != pend) {
1520                 ++it;
1521                 if (it == pit->insetlist.end()) {
1522                         ++pit;
1523                         setParagraph();
1524                 }
1525         }
1526         return *this;
1527 }
1528
1529
1530 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
1531 {
1532         inset_iterator tmp = *this;
1533         ++*this;
1534         return tmp;
1535 }
1536
1537
1538 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
1539 {
1540         return *it->inset;
1541 }
1542
1543
1544 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
1545 {
1546         return it->inset;
1547 }
1548
1549
1550 ParagraphList::iterator Buffer::inset_iterator::getPar() const
1551 {
1552         return pit;
1553 }
1554
1555
1556 lyx::pos_type Buffer::inset_iterator::getPos() const
1557 {
1558         return it->pos;
1559 }
1560
1561
1562 bool operator==(Buffer::inset_iterator const & iter1,
1563                 Buffer::inset_iterator const & iter2)
1564 {
1565         return iter1.pit == iter2.pit
1566                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
1567 }
1568
1569
1570 bool operator!=(Buffer::inset_iterator const & iter1,
1571                 Buffer::inset_iterator const & iter2)
1572 {
1573         return !(iter1 == iter2);
1574 }