]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
Hopefully this works on other archs too.
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "update_flags.h"
16
17 #include "insets/InsetCode.h"
18
19 #include "support/strfwd.h"
20 #include "support/types.h"
21 #include "support/SignalSlot.h"
22
23 #include <list>
24 #include <string>
25 #include <vector>
26
27
28 namespace lyx {
29
30 class BiblioInfo;
31 class BufferParams;
32 class BufferSet;
33 class DispatchResult;
34 class DocIterator;
35 class docstring_list;
36 class ErrorItem;
37 class ErrorList;
38 class FuncRequest;
39 class FuncStatus;
40 class Inset;
41 class InsetRef;
42 class InsetLabel;
43 class Font;
44 class Format;
45 class Lexer;
46 class LyXRC;
47 class Text;
48 class LyXVC;
49 class LaTeXFeatures;
50 class Language;
51 class MacroData;
52 class MacroNameSet;
53 class MacroSet;
54 class OutputParams;
55 class Paragraph;
56 class ParConstIterator;
57 class ParIterator;
58 class ParagraphList;
59 class TeXErrors;
60 class TexRow;
61 class TocBackend;
62 class Undo;
63 class WordLangTuple;
64
65 namespace frontend {
66 class GuiBufferDelegate;
67 class WorkAreaManager;
68 }
69
70 namespace support {
71 class FileName;
72 class FileNameList;
73 }
74
75 /** The buffer object.
76  * This is the buffer object. It contains all the informations about
77  * a document loaded into LyX.
78  * The buffer object owns the Text (wrapped in an InsetText), which
79  * contains the individual paragraphs of the document.
80  *
81  *
82  * I am not sure if the class is complete or
83  * minimal, probably not.
84  * \author Lars Gullik Bjønnes
85  */
86 class Buffer {
87 public:
88         /// What type of log will \c getLogName() return?
89         enum LogType {
90                 latexlog, ///< LaTeX log
91                 buildlog  ///< Literate build log
92         };
93
94         /// Result of \c readFile()
95         enum ReadStatus {
96                 failure, ///< The file could not be read
97                 success, ///< The file could not be read
98                 wrongversion ///< The version of the file does not match ours
99         };
100
101
102         /// Method to check if a file is externally modified, used by
103         /// isExternallyModified()
104         /**
105          * timestamp is fast but inaccurate. For example, the granularity
106          * of timestamp on a FAT filesystem is 2 second. Also, various operations
107          * may touch the timestamp of a file even when its content is unchanged.
108          *
109          * checksum is accurate but slow, which can be a problem when it is
110          * frequently used, or used for a large file on a slow (network) file
111          * system.
112          *
113          * FIXME: replace this method with support/FileMonitor.
114          */
115         enum CheckMethod {
116                 checksum_method,  ///< Use file checksum
117                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
118         };
119
120         ///
121         enum UpdateScope {
122                 UpdateMaster,
123                 UpdateChildOnly
124         };
125
126         /// Constructor
127         explicit Buffer(std::string const & file, bool b = false);
128
129         /// Destructor
130         ~Buffer();
131
132         /** High-level interface to buffer functionality.
133             This function parses a command string and executes it.
134         */
135         void dispatch(std::string const & command, DispatchResult & result);
136
137         /// Maybe we know the function already by number...
138         void dispatch(FuncRequest const & func, DispatchResult & result);
139
140         /// Can this function be exectued?
141         /// \return true if we made a decision
142         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
143
144         /// read a new document from a string
145         bool readString(std::string const &);
146         /// load a new file
147         bool readFile(support::FileName const & filename);
148
149         /// read the header, returns number of unknown tokens
150         int readHeader(Lexer & lex);
151
152         /** Reads a file without header.
153             \param par if != 0 insert the file.
154             \return \c true if file is not completely read.
155         */
156         bool readDocument(Lexer &);
157
158         ///
159         DocIterator getParFromID(int id) const;
160         /// do we have a paragraph with this id?
161         bool hasParWithID(int id) const;
162
163         ///
164         frontend::WorkAreaManager & workAreaManager() const;
165
166         /** Save file.
167             Takes care of auto-save files and backup file if requested.
168             Returns \c true if the save is successful, \c false otherwise.
169         */
170         bool save() const;
171
172         /// Write document to stream. Returns \c false if unsuccesful.
173         bool write(std::ostream &) const;
174         /// Write file. Returns \c false if unsuccesful.
175         bool writeFile(support::FileName const &) const;
176
177         /// Loads LyX file \c filename into buffer, *  and \return success
178         bool loadLyXFile(support::FileName const & s);
179
180         /// Fill in the ErrorList with the TeXErrors
181         void bufferErrors(TeXErrors const &, ErrorList &) const;
182
183         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
184         bool makeLaTeXFile(support::FileName const & filename,
185                            std::string const & original_path,
186                            OutputParams const &,
187                            bool output_preamble = true,
188                            bool output_body = true) const;
189         /** Export the buffer to LaTeX.
190             If \p os is a file stream, and params().inputenc is "auto" or
191             "default", and the buffer contains text in different languages
192             with more than one encoding, then this method will change the
193             encoding associated to \p os. Therefore you must not call this
194             method with a string stream if the output is supposed to go to a
195             file. \code
196             ofdocstream ofs;
197             ofs.open("test.tex");
198             writeLaTeXSource(ofs, ...);
199             ofs.close();
200             \endcode is NOT equivalent to \code
201             odocstringstream oss;
202             writeLaTeXSource(oss, ...);
203             ofdocstream ofs;
204             ofs.open("test.tex");
205             ofs << oss.str();
206             ofs.close();
207             \endcode
208          */
209         void writeLaTeXSource(odocstream & os,
210                            std::string const & original_path,
211                            OutputParams const &,
212                            bool output_preamble = true,
213                            bool output_body = true) const;
214         ///
215         void makeDocBookFile(support::FileName const & filename,
216                              OutputParams const & runparams_in,
217                              bool only_body = false) const;
218         ///
219         void writeDocBookSource(odocstream & os, std::string const & filename,
220                              OutputParams const & runparams_in,
221                              bool only_body = false) const;
222         ///
223         void makeLyXHTMLFile(support::FileName const & filename,
224                              OutputParams const & runparams_in,
225                              bool only_body = false) const;
226         ///
227         void writeLyXHTMLSource(odocstream & os,
228                              OutputParams const & runparams_in,
229                              bool only_body = false) const;
230         /// returns the main language for the buffer (document)
231         Language const * language() const;
232         /// get l10n translated to the buffers language
233         docstring const B_(std::string const & l10n) const;
234
235         ///
236         int runChktex();
237         /// return true if the main lyx file does not need saving
238         bool isClean() const;
239         ///
240         bool isBakClean() const;
241         ///
242         bool isDepClean(std::string const & name) const;
243
244         /// whether or not disk file has been externally modified
245         bool isExternallyModified(CheckMethod method) const;
246
247         /// save timestamp and checksum of the given file.
248         void saveCheckSum(support::FileName const & file) const;
249
250         /// mark the main lyx file as not needing saving
251         void markClean() const;
252
253         ///
254         void markBakClean() const;
255
256         ///
257         void markDepClean(std::string const & name);
258
259         ///
260         void setUnnamed(bool flag = true);
261
262         ///
263         bool isUnnamed() const;
264
265         /// Mark this buffer as dirty.
266         void markDirty();
267
268         /// Returns the buffer's filename. It is always an absolute path.
269         support::FileName fileName() const;
270
271         /// Returns the buffer's filename. It is always an absolute path.
272         std::string absFileName() const;
273
274         /// Returns the the path where the buffer lives.
275         /// It is always an absolute path.
276         std::string filePath() const;
277
278         /** A transformed version of the file name, adequate for LaTeX.
279             \param no_path optional if \c true then the path is stripped.
280         */
281         std::string latexName(bool no_path = true) const;
282
283         /// Get the name and type of the log.
284         std::string logName(LogType * type = 0) const;
285
286         /// Change name of buffer. Updates "read-only" flag.
287         void setFileName(std::string const & newfile);
288
289         /// Set document's parent Buffer.
290         void setParent(Buffer const *);
291         Buffer const * parent() const;
292
293         // Collect all relative buffer
294         std::vector<Buffer const *> allRelatives() const;
295
296         /** Get the document's master (or \c this if this is not a
297             child document)
298          */
299         Buffer const * masterBuffer() const;
300
301         /// \return true if \p child is a child of this \c Buffer.
302         bool isChild(Buffer * child) const;
303         
304         /// return a vector with all children and grandchildren
305         std::vector<Buffer *> getChildren() const;
306
307         /// Is buffer read-only?
308         bool isReadonly() const;
309
310         /// Set buffer read-only flag
311         void setReadonly(bool flag = true);
312
313         /// returns \c true if the buffer contains a LaTeX document
314         bool isLatex() const;
315         /// returns \c true if the buffer contains a DocBook document
316         bool isDocBook() const;
317         /// returns \c true if the buffer contains a Wed document
318         bool isLiterate() const;
319
320         /** Validate a buffer for LaTeX.
321             This validates the buffer, and returns a struct for use by
322             #makeLaTeX# and others. Its main use is to figure out what
323             commands and packages need to be included in the LaTeX file.
324             It (should) also check that the needed constructs are there
325             (i.e. that the \refs points to coresponding \labels). It
326             should perhaps inset "error" insets to help the user correct
327             obvious mistakes.
328         */
329         void validate(LaTeXFeatures &) const;
330
331         /// Update the cache with all bibfiles in use (including bibfiles
332         /// of loaded child documents).
333         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
334         ///
335         void invalidateBibinfoCache();
336         /// Return the cache with all bibfiles in use (including bibfiles
337         /// of loaded child documents).
338         support::FileNameList const & 
339                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
340         /// \return the bibliography information for this buffer's master,
341         /// or just for it, if it isn't a child.
342         BiblioInfo const & masterBibInfo() const;
343         /// \return the bibliography information for this buffer ONLY.
344         BiblioInfo const & localBibInfo() const;
345         ///
346         void getLabelList(std::vector<docstring> &) const;
347
348         ///
349         void changeLanguage(Language const * from, Language const * to);
350
351         ///
352         bool isMultiLingual() const;
353
354         ///
355         BufferParams & params();
356         BufferParams const & params() const;
357
358         /** The list of paragraphs.
359             This is a linked list of paragraph, this list holds the
360             whole contents of the document.
361          */
362         ParagraphList & paragraphs();
363         ParagraphList const & paragraphs() const;
364
365         /// LyX version control object.
366         LyXVC & lyxvc();
367         LyXVC const & lyxvc() const;
368
369         /// Where to put temporary files.
370         std::string const temppath() const;
371
372         /// Used when typesetting to place errorboxes.
373         TexRow const & texrow() const;
374         TexRow & texrow();
375
376         ///
377         ParIterator par_iterator_begin();
378         ///
379         ParConstIterator par_iterator_begin() const;
380         ///
381         ParIterator par_iterator_end();
382         ///
383         ParConstIterator par_iterator_end() const;
384
385         // Position of the child buffer where it appears first in the master.
386         DocIterator firstChildPosition(Buffer const * child);
387
388         /** \returns true only when the file is fully loaded.
389          *  Used to prevent the premature generation of previews
390          *  and by the citation inset.
391          */
392         bool isFullyLoaded() const;
393         /// Set by buffer_funcs' newFile.
394         void setFullyLoaded(bool);
395
396         /// Our main text (inside the top InsetText)
397         Text & text() const;
398
399         /// Our top InsetText
400         Inset & inset() const;
401
402         //
403         // Macro handling
404         //
405         /// Collect macro definitions in paragraphs
406         void updateMacros() const;
407         /// Iterate through the whole buffer and try to resolve macros
408         void updateMacroInstances() const;
409
410         /// List macro names of this buffer, the parent and the children
411         void listMacroNames(MacroNameSet & macros) const;
412         /// Collect macros of the parent and its children in front of this buffer.
413         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
414
415         /// Return macro defined before pos (or in the master buffer)
416         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
417         /// Return macro defined anywhere in the buffer (or in the master buffer)
418         MacroData const * getMacro(docstring const & name, bool global = true) const;
419         /// Return macro defined before the inclusion of the child
420         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
421
422         /// Replace the inset contents for insets which InsetCode is equal
423         /// to the passed \p inset_code.
424         void changeRefsIfUnique(docstring const & from, docstring const & to,
425                 InsetCode code);
426
427         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
428         /// including preamble
429         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
430                 bool full_source) const;
431
432         /// Access to error list.
433         /// This method is used only for GUI visualisation of Buffer related
434         /// errors (like parsing or LateX compilation). This method is const
435         /// because modifying the returned ErrorList does not touch the document
436         /// contents.
437         ErrorList & errorList(std::string const & type) const;
438
439         /// The Toc backend.
440         /// This is useful only for screen visualisation of the Buffer. This
441         /// method is const because modifying this backend does not touch
442         /// the document contents.
443         TocBackend & tocBackend() const;
444
445         ///
446         Undo & undo();
447
448         /// This function is called when the buffer is changed.
449         void changed() const;
450         ///
451         void updateTocItem(std::string const &, DocIterator const &) const;
452         /// This function is called when the buffer structure is changed.
453         void structureChanged() const;
454         /// This function is called when some parsing error shows up.
455         void errors(std::string const & err, bool from_master = false) const;
456         /// This function is called when the buffer busy status change.
457         void setBusy(bool on) const;
458         /// This function is called when the buffer readonly status change.
459         void setReadOnly(bool on) const;
460         /// Update window titles of all users.
461         void updateTitles() const;
462         /// Reset autosave timers for all users.
463         void resetAutosaveTimers() const;
464         ///
465         void message(docstring const & msg) const;
466
467         ///
468         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
469         ///
470         bool hasGuiDelegate() const;
471
472         ///
473         void autoSave() const;
474         ///
475         void removeAutosaveFile() const;
476         ///
477         void moveAutosaveFile(support::FileName const & old) const;
478         ///
479         support::FileName getAutosaveFilename() const;
480
481         /// return the format of the buffer on a string
482         std::string bufferFormat() const;
483         /// return the default output format of the current backend
484         std::string getDefaultOutputFormat() const;
485
486         ///
487         bool doExport(std::string const & format, bool put_in_tempdir,
488                 std::string & result_file) const;
489         ///
490         bool doExport(std::string const & format, bool put_in_tempdir) const;
491         ///
492         bool preview(std::string const & format) const;
493         ///
494         bool isExportable(std::string const & format) const;
495         ///
496         std::vector<Format const *> exportableFormats(bool only_viewable) const;
497
498         ///
499         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
500         References & references(docstring const & label);
501         References const & references(docstring const & label) const;
502         void clearReferenceCache() const;
503         void setInsetLabel(docstring const & label, InsetLabel const * il);
504         InsetLabel const * insetLabel(docstring const & label) const;
505
506         /// return a list of all used branches (also in children)
507         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
508
509         /// sets the buffer_ member for every inset in this buffer.
510         // FIXME This really shouldn't be needed, but at the moment it's not
511         // clear how to do it just for the individual pieces we need.
512         void setBuffersForInsets() const;
513         ///
514         void updateLabels(UpdateScope = UpdateMaster) const;
515         ///
516         void updateLabels(ParIterator & parit) const;
517
518         /// Spellcheck starting from \p from.
519         /// \p from initial position, will then points to the next misspelled
520         ///    word.
521         /// \p to will points to the end of the next misspelled word.
522         /// \p word_lang will contain the found misspelled word.
523         /// \return progress if a new word was found.
524         int spellCheck(DocIterator & from, DocIterator & to,
525                 WordLangTuple & word_lang, docstring_list & suggestions) const;
526
527 private:
528         /// search for macro in local (buffer) table or in children
529         MacroData const * getBufferMacro(docstring const & name,
530                                          DocIterator const & pos) const;
531         /** Update macro table starting with position of it
532             \param it in some text inset
533         */
534         void updateMacros(DocIterator & it,
535                                      DocIterator & scope) const;
536
537         ///
538         void collectRelatives(BufferSet & bufs) const;
539
540         ///
541         bool readFileHelper(support::FileName const & s);
542         ///
543         std::vector<std::string> backends() const;
544         /** Inserts a file into a document
545             \return \c false if method fails.
546         */
547         ReadStatus readFile(Lexer &, support::FileName const & filename,
548                             bool fromString = false);
549
550         /** If we have branches that use the file suffix
551             feature, return the file name with suffix appended.
552         */
553         support::FileName exportFileName() const;
554
555         /// Use the Pimpl idiom to hide the internals.
556         class Impl;
557         /// The pointer never changes although *pimpl_'s contents may.
558         Impl * const d;
559
560         frontend::GuiBufferDelegate * gui_;
561
562         /// This function is called when the buffer structure is changed.
563         Signal structureChanged_;
564         /// This function is called when some parsing error shows up.
565         //Signal errors(std::string const &) = 0;
566         /// This function is called when some message shows up.
567         //Signal message(docstring const &) = 0;
568         /// This function is called when the buffer busy status change.
569         //Signal setBusy(bool) = 0;
570         /// Reset autosave timers for all users.
571         Signal resetAutosaveTimers_;
572 };
573
574
575 } // namespace lyx
576
577 #endif