AppendPath::ver = "AppendPath requires Mathematica version 7 or later."; If[$VersionNumber < 7, (* We use FileExistsQ and FileNameJoin. *) Message[AppendPath::ver]; Abort[]; ]; AppendPath::usage = "AppendPath[path] appends the given path to $Path in \ Kernel/init.m."; RemovePath::usage = "RemovePath[path] removes the given path from $Path in \ Kernel/init.m."; AppendPath[path_String] := Module[{path1, initm, line, list, stream, failed = False}, path1 = FileNameJoin[{path}]; (* canonicalization *) initm = FileNameJoin[{$UserBaseDirectory, "Kernel", "init.m"}]; line = "AppendTo[$Path, \"" <> path1 <> "\"];"; (* Append the given path to $Path. *) If[Count[$Path, path1] == 0, AppendTo[$Path, path1]; ]; (* Append the given path to $Path in Kernel/init.m. *) If[FileExistsQ[initm], (* Check lines in Kernel/init.m. *) list = ReadList[initm, String]; If[list =!= $Failed, If[Count[list, line] > 0, Message[AppendPath::already, path1, initm]; , (* Append a line to Kernel/init.m. *) Check[ stream = OpenAppend[initm]; If[stream =!= $Failed, WriteString[stream, line <> "\n"]; Close[stream]; ]; , failed = True; ]; If[!failed, Message[AppendPath::succeeded, path1, initm]; , Message[AppendPath::failed, path1, initm]; ]; ]; ]; , (* Kernel/init.m doesn't exist. Create a new one. *) Check[ stream = OpenWrite[initm]; If[stream =!= $Failed, WriteString[stream, "(** User Mathematica initialization file **)\n"]; WriteString[stream, line <> "\n"]; Close[stream]; ]; , failed = True; ]; If[!failed, Message[AppendPath::succeeded, path1, initm]; , Message[AppendPath::failed, path1, initm]; ]; ]; ]; AppendPath::already = "`1` already exists in `2`."; AppendPath::succeeded = "Suceeded to append `1` in `2`."; AppendPath::failed = "Failed to append `1` in `2`."; RemovePath[path_String] := Module[{path1, initm, line, list, stream, failed = False}, path1 = FileNameJoin[{path}]; (* canonicalization *) initm = FileNameJoin[{$UserBaseDirectory, "Kernel", "init.m"}]; line = "AppendTo[$Path, \"" <> path1 <> "\"];"; (* Remove the given path from $Path. *) If[Count[$Path, path1] > 0, $Path = DeleteCases[$Path, path1]; ]; (* Remove the given path from $Path in Kernel/init.m. *) If[FileExistsQ[initm], (* Check lines in Kernel/init.m. *) list = ReadList[initm, String]; If[list =!= $Failed, If[Count[list, line] == 0, Message[RemovePath::already, path1, initm]; , (* Modify Kernel/init.m. *) list = DeleteCases[list, line]; Check[ stream = OpenWrite[initm]; If[stream =!= $Failed, Scan[( WriteString[stream, # <> "\n"]; )&, list]; Close[stream]; ]; , failed = True; ]; If[!failed, Message[RemovePath::succeeded, path1, initm]; , Message[RemovePath::failed, path1, initm]; ]; ]; ]; , (* Kernel/init.m doesn't exist. Create a new one. *) Message[RemovePath::notexist, initm]; ]; ]; RemovePath::already = "`1` already does not exist in `2`."; RemovePath::succeeded = "Suceeded to remove `1` in `2`."; RemovePath::failed = "Failed to remove `1` in `2`."; RemovePath::notexist = "`1` does not exist.";