commit 306b136cc005a1aeb9a6861ee0ac6fe2a2dd53e3
Author: Enrico Forestieri <[email protected]>
Date:   Wed May 13 21:40:51 2015 +0200

    Fix bug #4812 (Layout in local directory lost on Save As, Copying)
    
    The "save-as" part of the bug is fixed by extending the \textclass tag
    such that, if a local layout file is used, its path relative to the
    document directory is now stored together with the name. If a relative
    path cannot be used, an absolute one is used but, in this case, the
    document is not usable on a different platform.
    
    The "copy" part is fixed by introducing a new \origin tag, which is
    written when the file is saved. This tag stores the absolute path of
    the document directory. If the document is manually copied to a
    different location, the local layout file is retrivied by using
    \origin (which is only updated on save).
    This new tag may prove useful also for locating other files when the
    document is manually moved to a different directory.
    
    As in the original implementation the files needed for the layout
    (for example, a latex class) had to be in the same directory as the
    layout file, this directory has also to be added to TEXINPUTS.

diff --git a/development/FORMAT b/development/FORMAT
index e4dda6e..68e1d33 100644
--- a/development/FORMAT
+++ b/development/FORMAT
@@ -11,6 +11,14 @@ adjustments are made to tex2lyx and bugs are fixed in 
lyx2lyx.
 
 -----------------------
 
+2015-05-13 Enrico Forestieri <[email protected]>
+       * Format incremented to 490: new \origin tag, extended \textclass tag.
+         The \origin tag keeps track of the document directory and is useful
+         for locating files if the document is moved to a new location.
+         The \textclass tag can now contain a path (possibly relative to the
+         document directory) pointing to the location of a local layout file
+         if it is not located in the document directory.
+
 2015-05-11 Uwe Stöhr <[email protected]>
        * Format incremented to 489: support to set line thickness, box 
separation
              and shadow size in the box dialog 
diff --git a/lib/lyx2lyx/LyX.py b/lib/lyx2lyx/LyX.py
index 934f995..15bbf08 100644
--- a/lib/lyx2lyx/LyX.py
+++ b/lib/lyx2lyx/LyX.py
@@ -85,7 +85,7 @@ format_relation = [("0_06",    [200], minor_versions("0.6" , 
4)),
                    ("1_6", list(range(277,346)), minor_versions("1.6" , 10)),
                    ("2_0", list(range(346,414)), minor_versions("2.0" , 8)),
                    ("2_1", list(range(414,475)), minor_versions("2.1" , 0)),
-                   ("2_2", list(range(475,490)), minor_versions("2.2" , 0))
+                   ("2_2", list(range(475,491)), minor_versions("2.2" , 0))
                   ]
 
 ####################################################################
diff --git a/lib/lyx2lyx/lyx_2_2.py b/lib/lyx2lyx/lyx_2_2.py
index 57324ac..10e78ac 100644
--- a/lib/lyx2lyx/lyx_2_2.py
+++ b/lib/lyx2lyx/lyx_2_2.py
@@ -1015,6 +1015,30 @@ def revert_BoxFeatures(document):
         i = i + 11
 
 
+def convert_origin(document):
+    " Insert the origin tag "
+
+    i = find_token(document.header, "\\textclass ", 0)
+    if i == -1:
+        document.warning("Malformed LyX document: No \\textclass!!")
+        return;
+    if document.dir == "":
+        origin = "stdin"
+    else:
+        origin = document.dir.replace('\\', '/')
+    document.header[i:i] = ["\\origin " + origin]
+
+
+def revert_origin(document):
+    " Remove the origin tag "
+
+    i = find_token(document.header, "\\origin ", 0)
+    if i == -1:
+        document.warning("Malformed LyX document: No \\origin!!")
+        return;
+    del document.header[i]
+
+
 ##
 # Conversion hub
 #
@@ -1038,10 +1062,12 @@ convert = [
            [486, []],
            [487, []],
            [488, [convert_newgloss]],
-           [489, [convert_BoxFeatures]]
+           [489, [convert_BoxFeatures]],
+           [490, [convert_origin]]
           ]
 
 revert =  [
+           [489, [revert_origin]],
            [488, [revert_BoxFeatures]],
            [487, [revert_newgloss, revert_glossgroup]],
            [486, [revert_forest]],
diff --git a/src/Buffer.cpp b/src/Buffer.cpp
index e12d830..bd063a7 100644
--- a/src/Buffer.cpp
+++ b/src/Buffer.cpp
@@ -252,6 +252,12 @@ public:
        /// Keeps track of old buffer filePath() for save-as operations
        string old_position;
 
+       /** Keeps track of the path of local layout files.
+        *  If possible, it is always relative to the buffer path.
+        *  Empty for layouts in system or user directory.
+        */
+       string layout_position;
+
        /// Container for all sort of Buffer dependant errors.
        map<string, ErrorList> errorLists;
 
@@ -432,6 +438,7 @@ Buffer::Impl::Impl(Buffer * owner, FileName const & file, 
bool readonly_,
        cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
        unnamed = cloned_buffer_->d->unnamed;
        internal_buffer = cloned_buffer_->d->internal_buffer;
+       layout_position = cloned_buffer_->d->layout_position;
        preview_file_ = cloned_buffer_->d->preview_file_;
        preview_format_ = cloned_buffer_->d->preview_format_;
        preview_error_ = cloned_buffer_->d->preview_error_;
@@ -922,12 +929,11 @@ int Buffer::readHeader(Lexer & lex)
                LYXERR(Debug::PARSER, "Handling document header token: `"
                                      << token << '\'');
 
-               string unknown = params().readToken(lex, token, 
d->filename.onlyPath());
-               if (!unknown.empty()) {
-                       if (unknown[0] != '\\' && token == "\\textclass") {
-                               Alert::warning(_("Unknown document class"),
-                      bformat(_("Using the default document class, because the 
"
-                                             "class %1$s is unknown."), 
from_utf8(unknown)));
+               string const result =
+                       params().readToken(lex, token, d->filename.onlyPath());
+               if (!result.empty()) {
+                       if (token == "\\textclass") {
+                               d->layout_position = result;
                        } else {
                                ++unknown_tokens;
                                docstring const s = bformat(_("Unknown token: "
@@ -1542,7 +1548,7 @@ bool Buffer::write(ostream & ofs) const
 
        // now write out the buffer parameters.
        ofs << "\\begin_header\n";
-       params().writeFile(ofs);
+       params().writeFile(ofs, this);
        ofs << "\\end_header\n";
 
        // write the text
@@ -2542,7 +2548,8 @@ void Buffer::dispatch(FuncRequest const & func, 
DispatchResult & dr)
 
                // Execute the command in the background
                Systemcall call;
-               call.startscript(Systemcall::DontWait, command, filePath());
+               call.startscript(Systemcall::DontWait, command,
+                                filePath(), layoutPos());
                break;
        }
 
@@ -2730,7 +2737,7 @@ void Buffer::dispatch(FuncRequest const & func, 
DispatchResult & dr)
                                // First run dvips.
                                // If successful, then spool command
                                res = one.startscript(Systemcall::Wait, command,
-                                                     filePath());
+                                                     filePath(), layoutPos());
 
                                if (res == 0) {
                                        // If there's no GUI, we have to wait 
on this command. Otherwise,
@@ -2739,7 +2746,8 @@ void Buffer::dispatch(FuncRequest const & func, 
DispatchResult & dr)
                                        Systemcall::Starttype stype = use_gui ?
                                                Systemcall::DontWait : 
Systemcall::Wait;
                                        res = one.startscript(stype, command2,
-                                                             filePath());
+                                                             filePath(),
+                                                             layoutPos());
                                }
                        } else {
                                // case 2: print directly to a printer
@@ -2748,8 +2756,9 @@ void Buffer::dispatch(FuncRequest const & func, 
DispatchResult & dr)
                                // as above....
                                Systemcall::Starttype stype = use_gui ?
                                        Systemcall::DontWait : Systemcall::Wait;
-                               res = one.startscript(stype, command +
-                                               quoteName(dviname), filePath());
+                               res = one.startscript(stype,
+                                               command + quoteName(dviname),
+                                               filePath(), layoutPos());
                        }
 
                } else {
@@ -2772,7 +2781,7 @@ void Buffer::dispatch(FuncRequest const & func, 
DispatchResult & dr)
                        // as above....
                        Systemcall::Starttype stype = use_gui ?
                                Systemcall::DontWait : Systemcall::Wait;
-                       res = one.startscript(stype, command, filePath());
+                       res = one.startscript(stype, command, filePath(), 
layoutPos());
                }
 
                if (res == 0)
@@ -3018,6 +3027,29 @@ string Buffer::filePath() const
 }
 
 
+string Buffer::layoutPos() const
+{
+       return d->layout_position;
+}
+
+
+void Buffer::setLayoutPos(string const & path)
+{
+       if (path.empty()) {
+               d->layout_position.clear();
+               return;
+       }
+
+       LATTEST(FileName::isAbsolute(path));
+
+       d->layout_position =
+               to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
+
+       if (d->layout_position.empty())
+               d->layout_position = ".";
+}
+
+
 bool Buffer::isReadonly() const
 {
        return d->read_only;
@@ -3675,7 +3707,7 @@ void Buffer::getSourceCode(odocstream & os, string const 
& format,
                        if (output == FullSource)
                                write(ods);
                        else if (output == OnlyPreamble)
-                               params().writeFile(ods);
+                               params().writeFile(ods, this);
                        else if (output == OnlyBody)
                                text().write(ods);
                        os << from_utf8(ods.str());
diff --git a/src/Buffer.h b/src/Buffer.h
index ad0c2aa..50b2733 100644
--- a/src/Buffer.h
+++ b/src/Buffer.h
@@ -403,6 +403,18 @@ public:
        /// It is always an absolute path.
        std::string filePath() const;
 
+       /** Returns the path where a local layout file lives.
+        *  An empty string is returned for standard system and user layouts.
+        *  If possible, it is always relative to the buffer path.
+        */
+       std::string layoutPos() const;
+
+       /** Set the path to a local layout file.
+        *  This must be an absolute path but, if possible, it is always
+        *  stored as relative to the buffer path.
+        */
+       void setLayoutPos(std::string const & path);
+
        /** A transformed version of the file name, adequate for LaTeX.
            \param no_path optional if \c true then the path is stripped.
        */
diff --git a/src/BufferParams.cpp b/src/BufferParams.cpp
index a12a286..451736e 100644
--- a/src/BufferParams.cpp
+++ b/src/BufferParams.cpp
@@ -20,6 +20,7 @@
 #include "Author.h"
 #include "LayoutFile.h"
 #include "BranchList.h"
+#include "Buffer.h"
 #include "buffer_funcs.h"
 #include "Bullet.h"
 #include "Color.h"
@@ -601,6 +602,8 @@ void BufferParams::setDefSkip(VSpace const & vs)
 string BufferParams::readToken(Lexer & lex, string const & token,
        FileName const & filepath)
 {
+       string result;
+
        if (token == "\\textclass") {
                lex.next();
                string const classname = lex.getString();
@@ -609,13 +612,31 @@ string BufferParams::readToken(Lexer & lex, string const 
& token,
                // be available.
                string tcp;
                LayoutFileList & bcl = LayoutFileList::get();
-               if (!filepath.empty())
-                       tcp = bcl.addLocalLayout(classname, 
filepath.absFileName());
+               if (!filepath.empty()) {
+                       // If classname is an absolute path, the document is
+                       // using a local layout file which could not be accessed
+                       // by a relative path. In this case the path is correct
+                       // even if the document was moved to a different
+                       // location. However, we will have a problem if the
+                       // document was generated on a different platform.
+                       bool isabsolute = FileName::isAbsolute(classname);
+                       string const classpath = onlyPath(classname);
+                       string const path = isabsolute ? classpath
+                               : FileName(addPath(filepath.absFileName(),
+                                               classpath)).realPath();
+                       string const oldpath = isabsolute ? string()
+                               : FileName(addPath(origin, 
classpath)).realPath();
+                       tcp = bcl.addLocalLayout(onlyFileName(classname), path, 
oldpath);
+               }
                // that returns non-empty if a "local" layout file is found.
-               if (!tcp.empty())
-                       setBaseClass(tcp);
-               else
-                       setBaseClass(classname);
+               if (!tcp.empty()) {
+                       result = to_utf8(makeRelPath(from_utf8(onlyPath(tcp)),
+                                               
from_utf8(filepath.absFileName())));
+                       if (result.empty())
+                               result = ".";
+                       setBaseClass(onlyFileName(tcp));
+               } else
+                       setBaseClass(onlyFileName(classname));
                // We assume that a tex class exists for local or unknown
                // layouts so this warning, will only be given for system 
layouts.
                if (!baseClass()->isTeXClassAvailable()) {
@@ -636,6 +657,9 @@ string BufferParams::readToken(Lexer & lex, string const & 
token,
                        frontend::Alert::warning(_("Document class not 
available"),
                                       msg, true);
                }
+       } else if (token == "\\origin") {
+               lex.eatLine();
+               origin = lex.getString();
        } else if (token == "\\begin_preamble") {
                readPreamble(lex);
        } else if (token == "\\begin_local_layout") {
@@ -936,17 +960,22 @@ string BufferParams::readToken(Lexer & lex, string const 
& token,
                return token;
        }
 
-       return string();
+       return result;
 }
 
 
-void BufferParams::writeFile(ostream & os) const
+void BufferParams::writeFile(ostream & os, Buffer const * buf) const
 {
        // The top of the file is written by the buffer.
        // Prints out the buffer info into the .lyx file given by file
 
+       // the document directory
+       os << "\\origin " << buf->filePath() << '\n';
+
        // the textclass
-       os << "\\textclass " << baseClass()->name() << '\n';
+       os << "\\textclass " << buf->includedFilePath(addName(buf->layoutPos(),
+                                               baseClass()->name()), "layout")
+          << '\n';
 
        // then the preamble
        if (!preamble.empty()) {
diff --git a/src/BufferParams.h b/src/BufferParams.h
index 3258b82..a6cd211 100644
--- a/src/BufferParams.h
+++ b/src/BufferParams.h
@@ -77,7 +77,7 @@ public:
                support::FileName const & filepath);
 
        ///
-       void writeFile(std::ostream &) const;
+       void writeFile(std::ostream &, Buffer const *) const;
 
        /// check what features are implied by the buffer parameters.
        void validate(LaTeXFeatures &) const;
@@ -305,6 +305,8 @@ public:
        /// Individual pieces of text can use different encodings.
        Encoding const & encoding() const;
        ///
+       std::string origin;
+       ///
        std::string preamble;
        ///
        std::string options;
diff --git a/src/Converter.cpp b/src/Converter.cpp
index 0e0251e..f10d563 100644
--- a/src/Converter.cpp
+++ b/src/Converter.cpp
@@ -306,8 +306,9 @@ bool Converters::convert(Buffer const * buffer,
                        LYXERR(Debug::FILES, "No converter defined! "
                                   "I use convertDefault.py:\n\t" << command);
                        Systemcall one;
-                       one.startscript(Systemcall::Wait, command, buffer ?
-                                       buffer->filePath() : string());
+                       one.startscript(Systemcall::Wait, command,
+                                       buffer ? buffer->filePath() : string(),
+                                       buffer ? buffer->layoutPos() : 
string());
                        if (to_file.isReadableFile()) {
                                if (conversionflags & try_cache)
                                        ConverterCache::get().add(orig_from,
@@ -474,13 +475,16 @@ bool Converters::convert(Buffer const * buffer,
                        if (dummy) {
                                res = one.startscript(Systemcall::DontWait,
                                        to_filesystem8bit(from_utf8(command)),
-                                       buffer ? buffer->filePath() : string());
+                                       buffer ? buffer->filePath() : string(),
+                                       buffer ? buffer->layoutPos() : 
string());
                                // We're not waiting for the result, so we 
can't do anything
                                // else here.
                        } else {
                                res = one.startscript(Systemcall::Wait,
                                                
to_filesystem8bit(from_utf8(command)),
                                                buffer ? buffer->filePath()
+                                                      : string(),
+                                               buffer ? buffer->layoutPos()
                                                       : string());
                                if (!real_outfile.empty()) {
                                        Mover const & mover = 
getMover(conv.to());
@@ -501,7 +505,8 @@ bool Converters::convert(Buffer const * buffer,
                                                " > " + quoteName(logfile);
                                        one.startscript(Systemcall::Wait,
                                                
to_filesystem8bit(from_utf8(command2)),
-                                               buffer->filePath());
+                                               buffer->filePath(),
+                                               buffer->layoutPos());
                                        if (!scanLog(*buffer, command, 
makeAbsPath(logfile, path), errorList))
                                                return false;
                                }
@@ -644,7 +649,8 @@ bool Converters::runLaTeX(Buffer const & buffer, string 
const & command,
        // do the LaTeX run(s)
        string const name = buffer.latexName();
        LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
-                   buffer.filePath(), buffer.lastPreviewError());
+                   buffer.filePath(), buffer.layoutPos(),
+                   buffer.lastPreviewError());
        TeXErrors terr;
        ShowMessage show(buffer);
        latex.message.connect(show);
diff --git a/src/Format.cpp b/src/Format.cpp
index bf31026..eba00b9 100644
--- a/src/Format.cpp
+++ b/src/Format.cpp
@@ -716,7 +716,8 @@ bool Formats::view(Buffer const & buffer, FileName const & 
filename,
 
        PathChanger p(filename.onlyPath());
        Systemcall one;
-       one.startscript(Systemcall::DontWait, command, buffer.filePath());
+       one.startscript(Systemcall::DontWait, command,
+                       buffer.filePath(), buffer.layoutPos());
 
        // we can't report any sort of error, since we aren't waiting
        return true;
@@ -785,7 +786,8 @@ bool Formats::edit(Buffer const & buffer, FileName const & 
filename,
        buffer.message(_("Executing command: ") + from_utf8(command));
 
        Systemcall one;
-       one.startscript(Systemcall::DontWait, command, buffer.filePath());
+       one.startscript(Systemcall::DontWait, command,
+                       buffer.filePath(), buffer.layoutPos());
 
        // we can't report any sort of error, since we aren't waiting
        return true;
diff --git a/src/LaTeX.cpp b/src/LaTeX.cpp
index 3b82fa9..55e31ec 100644
--- a/src/LaTeX.cpp
+++ b/src/LaTeX.cpp
@@ -92,8 +92,9 @@ bool operator!=(AuxInfo const & a, AuxInfo const & o)
  */
 
 LaTeX::LaTeX(string const & latex, OutputParams const & rp,
-            FileName const & f, string const & p, bool const clean_start)
-       : cmd(latex), file(f), path(p), runparams(rp), biber(false)
+            FileName const & f, string const & p, string const & lp,
+            bool const clean_start)
+       : cmd(latex), file(f), path(p), lpath(lp), runparams(rp), biber(false)
 {
        num_errors = 0;
        if (prefixIs(cmd, "pdf")) { // Do we use pdflatex ?
@@ -425,7 +426,7 @@ int LaTeX::startscript()
                     + quoteName(onlyFileName(file.toFilesystemEncoding()))
                     + " > " + os::nulldev();
        Systemcall one;
-       return one.startscript(Systemcall::Wait, tmp, path);
+       return one.startscript(Systemcall::Wait, tmp, path, lpath);
 }
 
 
@@ -452,7 +453,7 @@ bool LaTeX::runMakeIndex(string const & f, OutputParams 
const & runparams,
        tmp += quoteName(f);
        tmp += params;
        Systemcall one;
-       one.startscript(Systemcall::Wait, tmp, path);
+       one.startscript(Systemcall::Wait, tmp, path, lpath);
        return true;
 }
 
@@ -468,7 +469,7 @@ bool LaTeX::runMakeIndexNomencl(FileName const & file,
        tmp += " -o "
                + onlyFileName(changeExtension(file.toFilesystemEncoding(), 
nls));
        Systemcall one;
-       one.startscript(Systemcall::Wait, tmp, path);
+       one.startscript(Systemcall::Wait, tmp, path, lpath);
        return true;
 }
 
@@ -608,7 +609,7 @@ bool LaTeX::runBibTeX(vector<AuxInfo> const & bibtex_info,
                tmp += quoteName(onlyFileName(removeExtension(
                                it->aux_file.absFileName())));
                Systemcall one;
-               one.startscript(Systemcall::Wait, tmp, path);
+               one.startscript(Systemcall::Wait, tmp, path, lpath);
        }
        // Return whether bibtex was run
        return result;
diff --git a/src/LaTeX.h b/src/LaTeX.h
index d040b43..08c9dfd 100644
--- a/src/LaTeX.h
+++ b/src/LaTeX.h
@@ -160,6 +160,7 @@ public:
        LaTeX(std::string const & cmd, OutputParams const &,
              support::FileName const & file,
              std::string const & path = empty_string(),
+             std::string const & lpath = empty_string(),
              bool const clean_start = false);
 
        /// runs LaTeX several times
@@ -222,9 +223,12 @@ private:
        ///
        support::FileName file;
 
-       ///
+       /// The document directory path.
        std::string path;
 
+       /// Extra path, possibly relative to the document directory path.
+       std::string lpath;
+
        /// used by scanLogFile
        int num_errors;
 
diff --git a/src/LayoutFile.cpp b/src/LayoutFile.cpp
index e428b5d..d0fc248 100644
--- a/src/LayoutFile.cpp
+++ b/src/LayoutFile.cpp
@@ -268,7 +268,7 @@ LayoutFileIndex LayoutFileList::addEmptyClass(string const 
& textclass)
 
 
 LayoutFileIndex  LayoutFileList::addLocalLayout(
-       string const & textclass, string const & path)
+       string const & textclass, string const & path, string const & oldpath)
 {
        // FIXME  There is a bug here: 4593
        //
@@ -277,10 +277,22 @@ LayoutFileIndex  LayoutFileList::addLocalLayout(
        // different from textclass
        string fullName = addName(path, textclass + ".layout");
        
-       FileName const layout_file(fullName);
-
-       if (!layout_file.exists())
-               return string();
+       FileName layout_file(fullName);
+       bool moved = false;
+
+       if (!layout_file.exists()) {
+               if (oldpath.empty())
+                       return string();
+               // The document has been moved to a different directory.
+               // However, oldpath always points to the right spot, unless
+               // the user also moved the layout file.
+               fullName = addName(oldpath, textclass + ".layout");
+               layout_file.set(fullName);
+               layout_file.refresh();
+               if (!layout_file.exists())
+                       return string();
+               moved = true;
+       }
 
        LYXERR(Debug::TCLASS, "Adding class " << textclass << " from directory 
" << path);
        // Read .layout file and get description, real latex classname etc
@@ -327,15 +339,18 @@ LayoutFileIndex  LayoutFileList::addLocalLayout(
        // This textclass is added on request so it will definitely be
        // used. Load it now because other load() calls may fail if they
        // are called in a context without buffer path information.
-       tmpl->load(path);
+       tmpl->load(moved ? oldpath : path);
        // There will be only one textclass with this name, even if different
        // layout files are loaded from different directories.
        if (haveClass(textclass)) {
-               LYXERR0("Existing textclass " << textclass << " is redefined by 
" << fullName);
+               // Unconditionally issuing the warning may be confusing when
+               // saving the document with a different name, as it is exactly
+               // the same textclass that is being re-established.
+               LYXERR(Debug::TCLASS, "Existing textclass " << textclass << " 
is redefined by " << fullName);
                delete classmap_[textclass];
        }
        classmap_[textclass] = tmpl;
-       return textclass;
+       return removeExtension(fullName);
 }
 
 
diff --git a/src/LayoutFile.h b/src/LayoutFile.h
index 1632cda..e911aa5 100644
--- a/src/LayoutFile.h
+++ b/src/LayoutFile.h
@@ -118,8 +118,9 @@ public:
        /// add a textclass from user local directory.
        /// \return the identifier for the loaded file, or else an
        /// empty string if no file was loaded.
-       LayoutFileIndex
-               addLocalLayout(std::string const & textclass, std::string const 
& path);
+       LayoutFileIndex addLocalLayout(std::string const & textclass,
+                                      std::string const & path,
+                                      std::string const & oldpath = 
empty_string());
        /// a list of the available classes
        std::vector<LayoutFileIndex> classList() const;
 
diff --git a/src/VCBackend.cpp b/src/VCBackend.cpp
index 06fa0df..974fa7d 100644
--- a/src/VCBackend.cpp
+++ b/src/VCBackend.cpp
@@ -43,7 +43,7 @@ int VCS::doVCCommandCall(string const & cmd, FileName const & 
path)
        LYXERR(Debug::LYXVC, "doVCCommandCall: " << cmd);
        Systemcall one;
        support::PathChanger p(path);
-       return one.startscript(Systemcall::Wait, cmd, string(), false);
+       return one.startscript(Systemcall::Wait, cmd, string(), string(), 
false);
 }
 
 
diff --git a/src/frontends/qt4/GuiDocument.cpp 
b/src/frontends/qt4/GuiDocument.cpp
index 3297f70..31bf10b 100644
--- a/src/frontends/qt4/GuiDocument.cpp
+++ b/src/frontends/qt4/GuiDocument.cpp
@@ -1228,7 +1228,7 @@ GuiDocument::GuiDocument(GuiView & lv)
        connect(latexModule->psdriverCO, SIGNAL(activated(int)),
                this, SLOT(change_adaptor()));
        connect(latexModule->classCO, SIGNAL(activated(int)),
-               this, SLOT(classChanged()));
+               this, SLOT(classChanged_adaptor()));
        connect(latexModule->classCO, SIGNAL(activated(int)),
                this, SLOT(change_adaptor()));
        connect(latexModule->layoutPB, SIGNAL(clicked()),
@@ -2102,9 +2102,9 @@ void GuiDocument::browseLayout()
 
        int const ret = Alert::prompt(_("Local layout file"),
                _("The layout file you have selected is a local layout\n"
-                 "file, not one in the system or user directory. Your\n"
-                 "document may not work with this layout if you do not\n"
-                 "keep the layout file in the document directory."),
+                 "file, not one in the system or user directory.\n"
+                 "Your document will not work with this layout if you\n"
+                 "move the layout file to a different directory."),
                  1, 1, _("&Set Layout"), _("&Cancel"));
        if (ret == 1)
                return;
@@ -2113,9 +2113,9 @@ void GuiDocument::browseLayout()
        LayoutFileList & bcl = LayoutFileList::get();
        string classname = layoutFile.onlyFileName();
        // this will update an existing layout if that layout has been loaded 
before.
-       LayoutFileIndex name = bcl.addLocalLayout(
+       LayoutFileIndex name = support::onlyFileName(bcl.addLocalLayout(
                classname.substr(0, classname.size() - 7),
-               layoutFile.onlyPath().absFileName());
+               layoutFile.onlyPath().absFileName()));
 
        if (name.empty()) {
                Alert::error(_("Error"),
@@ -2123,6 +2123,8 @@ void GuiDocument::browseLayout()
                return;
        }
 
+       const_cast<Buffer 
&>(buffer()).setLayoutPos(layoutFile.onlyPath().absFileName());
+
        // do not trigger classChanged if there is no change.
        if (latexModule->classCO->currentText() == toqstr(name))
                return;
@@ -2161,6 +2163,13 @@ void GuiDocument::browseMaster()
 }
 
 
+void GuiDocument::classChanged_adaptor()
+{
+       const_cast<Buffer &>(buffer()).setLayoutPos(string());
+       classChanged();
+}
+
+
 void GuiDocument::classChanged()
 {
        int idx = latexModule->classCO->currentIndex();
@@ -3671,11 +3680,11 @@ DocumentClass const & GuiDocument::documentClass() const
 
 
 static void dispatch_bufferparams(Dialog const & dialog,
-       BufferParams const & bp, FuncCode lfun)
+       BufferParams const & bp, FuncCode lfun, Buffer const * buf)
 {
        ostringstream ss;
        ss << "\\begin_header\n";
-       bp.writeFile(ss);
+       bp.writeFile(ss, buf);
        ss << "\\end_header\n";
        dialog.dispatch(FuncRequest(lfun, ss.str()));
 }
@@ -3693,7 +3702,7 @@ void GuiDocument::dispatchParams()
 
        // Apply the BufferParams. Note that this will set the base class
        // and then update the buffer's layout.
-       dispatch_bufferparams(*this, params(), LFUN_BUFFER_PARAMS_APPLY);
+       dispatch_bufferparams(*this, params(), LFUN_BUFFER_PARAMS_APPLY, 
&buffer());
 
        if (!params().master.empty()) {
                FileName const master_file = 
support::makeAbsPath(params().master,
@@ -3777,7 +3786,7 @@ void GuiDocument::setLanguage() const
 
 void GuiDocument::saveAsDefault() const
 {
-       dispatch_bufferparams(*this, params(), LFUN_BUFFER_SAVE_AS_DEFAULT);
+       dispatch_bufferparams(*this, params(), LFUN_BUFFER_SAVE_AS_DEFAULT, 
&buffer());
 }
 
 
diff --git a/src/frontends/qt4/GuiDocument.h b/src/frontends/qt4/GuiDocument.h
index 1018c8f..c35aec3 100644
--- a/src/frontends/qt4/GuiDocument.h
+++ b/src/frontends/qt4/GuiDocument.h
@@ -105,6 +105,7 @@ private Q_SLOTS:
        void browseLayout();
        void browseMaster();
        void classChanged();
+       void classChanged_adaptor();
        void languagePackageChanged(int);
        void biblioChanged();
        void bibtexChanged(int);
diff --git a/src/graphics/PreviewLoader.cpp b/src/graphics/PreviewLoader.cpp
index cc25e05..1715b5d 100644
--- a/src/graphics/PreviewLoader.cpp
+++ b/src/graphics/PreviewLoader.cpp
@@ -694,7 +694,7 @@ void PreviewLoader::Impl::startLoading(bool wait)
        string const command = cs.str();
 
        if (wait) {
-               ForkedCall call(buffer_.filePath());
+               ForkedCall call(buffer_.filePath(), buffer_.layoutPos());
                int ret = call.startScript(ForkedProcess::Wait, command);
                // FIXME THREAD
                static int fake = (2^20) + 1;
diff --git a/src/support/ForkedCalls.cpp b/src/support/ForkedCalls.cpp
index 6330797..14be7af 100644
--- a/src/support/ForkedCalls.cpp
+++ b/src/support/ForkedCalls.cpp
@@ -270,8 +270,8 @@ int ForkedProcess::waitForChild()
 //
 /////////////////////////////////////////////////////////////////////
 
-ForkedCall::ForkedCall(string const & path)
-       : cmd_prefix_(to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path))))
+ForkedCall::ForkedCall(string const & path, string const & lpath)
+       : cmd_prefix_(to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path, 
lpath))))
 {}
 
 
diff --git a/src/support/ForkedCalls.h b/src/support/ForkedCalls.h
index 7729398..191a2b5 100644
--- a/src/support/ForkedCalls.h
+++ b/src/support/ForkedCalls.h
@@ -150,7 +150,8 @@ private:
 class ForkedCall : public ForkedProcess {
 public:
        ///
-       ForkedCall(std::string const & path = empty_string());
+       ForkedCall(std::string const & path = empty_string(),
+                  std::string const & lpath = empty_string());
        ///
        virtual shared_ptr<ForkedProcess> clone() const {
                return shared_ptr<ForkedProcess>(new ForkedCall(*this));
diff --git a/src/support/Systemcall.cpp b/src/support/Systemcall.cpp
index 28cbdc8..0e4cec7 100644
--- a/src/support/Systemcall.cpp
+++ b/src/support/Systemcall.cpp
@@ -101,9 +101,11 @@ ProgressInterface * ProgressInterface::instance()
 // Reuse of instance
 #ifndef USE_QPROCESS
 int Systemcall::startscript(Starttype how, string const & what,
-                           std::string const & path, bool /*process_events*/)
+                           string const & path, string const & lpath,
+                           bool /*process_events*/)
 {
-       string command = to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path)))
+       string command =
+               to_filesystem8bit(from_utf8(latexEnvCmdPrefix(path, lpath)))
                       + commandPrep(what);
 
        if (how == DontWait) {
@@ -233,7 +235,8 @@ string const parsecmd(string const & incmd, string & 
infile, string & outfile,
 
 
 int Systemcall::startscript(Starttype how, string const & what,
-                           string const & path, bool process_events)
+                           string const & path, string const & lpath,
+                           bool process_events)
 {
        string const what_ss = commandPrep(what);
        LYXERR(Debug::INFO,"Running: " << what_ss);
@@ -252,7 +255,7 @@ int Systemcall::startscript(Starttype how, string const & 
what,
        // is started with QProcess::startDetached, a console window is shown 
every 
        // time a viewer is started. To avoid this, we fall back on Windows to 
the 
        // original implementation that creates a QProcess object.
-       d.startProcess(cmd, path, false);
+       d.startProcess(cmd, path, lpath, false);
        if (!d.waitWhile(SystemcallPrivate::Starting, process_events, -1)) {
                LYXERR0("Systemcall: '" << cmd << "' did not start!");
                LYXERR0("error " << d.errorMessage());
@@ -263,7 +266,7 @@ int Systemcall::startscript(Starttype how, string const & 
what,
                return 0;
        }
 #else
-       d.startProcess(cmd, path, how == DontWait);
+       d.startProcess(cmd, path, lpath, how == DontWait);
        if (how == DontWait && d.state == SystemcallPrivate::Running)
                return 0;
 
@@ -360,12 +363,13 @@ SystemcallPrivate::SystemcallPrivate(std::string const & 
sf,
 }
 
 
-void SystemcallPrivate::startProcess(QString const & cmd, string const & path, 
bool detached)
+void SystemcallPrivate::startProcess(QString const & cmd, string const & path,
+                                     string const & lpath, bool detached)
 {
        cmd_ = cmd;
        if (detached) {
                state = SystemcallPrivate::Running;
-               if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path)) + 
cmd_)) {
+               if (!QProcess::startDetached(toqstr(latexEnvCmdPrefix(path, 
lpath)) + cmd_)) {
                        state = SystemcallPrivate::Error;
                        return;
                }
@@ -373,7 +377,7 @@ void SystemcallPrivate::startProcess(QString const & cmd, 
string const & path, b
                delete released;
        } else if (process_) {
                state = SystemcallPrivate::Starting;
-               process_->start(toqstr(latexEnvCmdPrefix(path)) + cmd_);
+               process_->start(toqstr(latexEnvCmdPrefix(path, lpath)) + cmd_);
        }
 }
 
diff --git a/src/support/Systemcall.h b/src/support/Systemcall.h
index 5b0750d..876aa35 100644
--- a/src/support/Systemcall.h
+++ b/src/support/Systemcall.h
@@ -42,13 +42,15 @@ public:
         *  The string "what" contains a commandline with arguments separated
         *  by spaces and encoded in the filesystem encoding. "$$s" will be
         *  replaced accordingly by commandPrep(). The string "path" contains
-        *  the path to be prepended to the TEXINPUTS environment variable and
-        *  encoded in the path to be prepended to the TEXINPUTS environment
-        *  variable and utf-8. Unset "process_events" in case UI should be
-        *  blocked while processing the external command.
+        *  the path to be prepended to the TEXINPUTS environment variable
+        *  encoded in utf-8. Similarly for the string "lpath" that, if not
+        *  empty, specifies an additional directory to be added to TEXINPUTS
+        *  but after "path". Unset "process_events" in case UI should be
+        *  blocked while  processing the external command.
         */
        int startscript(Starttype how, std::string const & what,
                        std::string const & path = empty_string(),
+                       std::string const & lpath = empty_string(),
                        bool process_events = false);
 };
 
diff --git a/src/support/SystemcallPrivate.h b/src/support/SystemcallPrivate.h
index 6534d07..5aac543 100644
--- a/src/support/SystemcallPrivate.h
+++ b/src/support/SystemcallPrivate.h
@@ -45,7 +45,8 @@ public:
        State state;
 
        bool waitWhile(State, bool processEvents, int timeout = -1);
-       void startProcess(QString const & cmd, std::string const & path, bool 
detach);
+       void startProcess(QString const & cmd, std::string const & path,
+                         std::string const & lpath, bool detach);
        
        int exitCode();
 
diff --git a/src/support/filetools.cpp b/src/support/filetools.cpp
index a05f984..bab9687 100644
--- a/src/support/filetools.cpp
+++ b/src/support/filetools.cpp
@@ -700,16 +700,31 @@ string const replaceEnvironmentPath(string const & path)
 
 
 // Return a command prefix for setting the environment of the TeX engine.
-string latexEnvCmdPrefix(string const & path)
+string latexEnvCmdPrefix(string const & path, string const & lpath)
 {
-       if (path.empty() || lyxrc.texinputs_prefix.empty())
+       bool use_lpath = !(lpath.empty() || lpath == "." || lpath == "./");
+
+       if (path.empty() || (lyxrc.texinputs_prefix.empty() && !use_lpath))
                return string();
 
-       string const texinputs_prefix = os::latex_path_list(
+       string texinputs_prefix = lyxrc.texinputs_prefix.empty() ? string()
+               : os::latex_path_list(
                        replaceCurdirPath(path, lyxrc.texinputs_prefix));
        string const sep = string(1, os::path_separator(os::TEXENGINE));
        string const texinputs = getEnv("TEXINPUTS");
 
+       if (use_lpath) {
+               string const abslpath = FileName::isAbsolute(lpath)
+                       ? os::latex_path(lpath)
+                       : os::latex_path(FileName(path + "/" + 
lpath).realPath());
+               if (texinputs_prefix.empty())
+                       texinputs_prefix = abslpath;
+               else if (suffixIs(texinputs_prefix, sep))
+                       texinputs_prefix.append(abslpath + sep);
+               else
+                       texinputs_prefix.append(sep + abslpath);
+       }
+
        if (os::shell() == os::UNIX)
                return "env TEXINPUTS=\"." + sep + texinputs_prefix
                                          + sep + texinputs + "\" ";
diff --git a/src/support/filetools.h b/src/support/filetools.h
index b041b36..2953a81 100644
--- a/src/support/filetools.h
+++ b/src/support/filetools.h
@@ -261,9 +261,9 @@ std::string const replaceEnvironmentPath(std::string const 
& path);
 
 /**
    Return a string to be used as a prefix to a command for setting the
-   environment of the TeX engine with respect to the path \p path.
+   environment of the TeX engine with respect to the paths \p path and \p 
lpath.
  */
-std::string latexEnvCmdPrefix(std::string const & path);
+std::string latexEnvCmdPrefix(std::string const &path, std::string const & 
lpath);
 
 /** Replace all references to a current directory (a lonely '.' or
     the prefix "./") in \c pathlist with \c path. Also prefixes
diff --git a/src/version.h b/src/version.h
index 8407528..35de8f0 100644
--- a/src/version.h
+++ b/src/version.h
@@ -32,8 +32,8 @@ extern char const * const lyx_version_info;
 
 // Do not remove the comment below, so we get merge conflict in
 // independent branches. Instead add your own.
-#define LYX_FORMAT_LYX 489 // uwestoehr: new box features
-#define LYX_FORMAT_TEX2LYX 489
+#define LYX_FORMAT_LYX 490 // forenr: new origin tag
+#define LYX_FORMAT_TEX2LYX 490
 
 #if LYX_FORMAT_TEX2LYX != LYX_FORMAT_LYX
 #ifndef _MSC_VER

Reply via email to