使用 Swift 编译 Latex 代码

Compile Latex code using Swift

我想使用 Swift 编译一个 .tex 文件。我有以下代码:

class FileManager {
    class func compileLatex(#file: String) {
        let task = NSTask()
        task.launchPath = "/usr/texbin/latexmk"
        task.currentDirectoryPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String).stringByAppendingString("/roster")
        task.arguments = ["-xelatex", file]
        task.launch()
    }
}

但是,调用 FileManager.compileLatex(file: "latex.tex") 时出现错误 'launch path not accessible'。很明显,发射路径是错误的,但我不知道如何找出它到底是什么?我怎样才能找到或是否有一般路径?感谢您的帮助

编辑:

更新代码并出现此错误:

Latexmk: This is Latexmk, John Collins, 10 January 2015, version: 4.42.
Latexmk: applying rule 'pdflatex'...
Rule 'pdflatex': Rules & subrules not known to be previously run:
   pdflatex
Rule 'pdflatex': The following rules & subrules became out-of-date:
      'pdflatex'
------------
Run number 1 of rule 'pdflatex'
------------
------------
Running 'xelatex  -recorder  "Praktikumsbericht.tex"'
------------
sh: xelatex: command not found
Latexmk: Errors, so I did not complete making targets
Collected error summary (may duplicate other messages):
  pdflatex: (Pdf)LaTeX failed to generate the expected log file 'Praktikumsbericht.log'
Latexmk: Did not finish processing file 'Praktikumsbericht.tex':
   (Pdf)LaTeX failed to generate the expected log file 'Praktikumsbericht.log'
Latexmk: Use the -f option to force complete processing,
 unless error was exceeding maximum runs of latex/pdflatex.

launchPath必须设置为可执行文件的路径, 例如

task.launchPath = "/usr/texbin/latexmk"

可以选择设置currentDirectoryPath来执行 指定目录下的任务。 "Documents" 目录 通常是这样确定的:

task.currentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString

最后,arguments 是命令行参数 可执行文件,例如

task.arguments = ["-xelatex", file]

或者, 您可以使用 shell 启动可执行文件, 像

task.launchPath = "/bin/sh"
task.currentDirectoryPath = ...
task.arguments = ["-c", "latexmk -xelatex \"\(file)\""]

优点是shell使用PATH环境变量 找到可执行文件。一个缺点是引用参数 正确更难。

更新: 似乎“/usr/texbin”必须在 PATH 中 乳胶工艺。这可以按如下方式完成:

// Get current environment:
var env = NSProcessInfo.processInfo().environment
// Get PATH:
var path = env["PATH"] as String
// Prepend "/usr/texbin":
path = "/usr/texbin:" + path
// Put back to environment:
env["PATH"] = path
// And use this as environment for the task:
task.environment = env