最終更新日 2024-09-25
「hmV8」の例題 相対パスや絶対パス
概要
エディタで開いているファイルと、何か別のターゲットのファイルの相対パスを得たい、
絶対パスを得たい、といったことはあります。
そういった例を見てみましょう。
エディタと相対パスと絶対パス
/*
* This codes is licensed under CC0 1.0 Universal
*/
#JS = loaddll( hidemarudir + @"\hmV8.dll" );
#r = dllfuncw( #JS, "DoString", R"JS(
function GetBaseDirectory() {
// 秀丸マクロのシンボル"filename2"を利用。今編集中のファイルのフルパス
let filename2 = hm.Macro.Var["filename2"];
// パスからディレクトリへ
let strBaseUrl = clr.System.IO.Path.GetDirectoryName(filename2);
return strBaseUrl + "/";
}
function GetTargetFilePath(strBaseDirectory) {
// ダイアログ表示のため
let lib = host.lib("System.Windows.Forms");
let ofd = new lib.System.Windows.Forms.OpenFileDialog();
// 最初に選択するフォルダを指定する
ofd.InitialDirectory = strBaseDirectory;
ofd.Filter = "HTMLファイル(*.html;*.htm;*.png)|*.html;*.htm;*.png|すべてのファイル(*.*)|*.*"
// ダイアログ表示して選択した?
if (ofd.ShowDialog() == lib.System.Windows.Forms.DialogResult.OK)
{
return ofd.FileName;
} else {
throw "未選択";
}
}
try {
// ベースのディレクトリを得る。
let strBaseDirectory = GetBaseDirectory();
let baseUrl = new clr.System.Uri(strBaseDirectory);
// ターゲットのファイルのフルパスを得る
let strTargetPath = GetTargetFilePath(strBaseDirectory);
let targetUrl = new clr.System.Uri(strTargetPath);
// ベースUriから対象のUrlの相対Uriを得る
let relativeUri = baseUrl.MakeRelativeUri(targetUrl);
// Uriオブジェクト→文字列に変換する
let relativePath = relativeUri.ToString();
// そのパスはローカルに本当に存在するのか?
if ( !clr.System.IO.File.Exists(targetUrl.LocalPath) ) {
throw "ファイルが無い";
}
// 秀丸マクロへと伝搬
hm.Macro.Var["$relativePath"] = relativePath;
hm.Macro.Var["$localPath"] = targetUrl.LocalPath;
hm.Macro.Var["$absolutePath"] = targetUrl.AbsolutePath;
} catch(e) {
hm.Macro.Var["$exceptionMessage"] = e;
}
)JS"
);
if ($exceptionMessage != "") {
message $exceptionMessage;
} else {
message $relativePath;
message $localPath;
message $absolutePath;
}
freedll(#JS);