Skip to content

Instantly share code, notes, and snippets.

@twflts
Created February 13, 2022 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twflts/b12f5ce58a8398e8236867e7f3add151 to your computer and use it in GitHub Desktop.
Save twflts/b12f5ce58a8398e8236867e7f3add151 to your computer and use it in GitHub Desktop.
# openemacs.ps1
# example
# powershell -nologo -NonInteractive -ExecutionPolicy Unrestricted "C:\Path\To\openemacs.ps1" "C:\Path\to\Target"
## variables
$server_dir = "${Env:USERPROFILE}\AppData\Roaming\.emacs.d\server\"
$emacsclient_bin = "C:\ProgramData\chocolatey\bin\emacsclientw.exe"
$runemacs_bin = "C:\ProgramData\chocolatey\bin\runemacs.exe"
## functions
function open_with_emacs($p, $s){
if ($s -eq $null) {
Start-Process -FilePath $emacsclient_bin -ArgumentList "-a $runemacs_bin $p"
}
else {
Start-Process -FilePath $emacsclient_bin -ArgumentList "-f $s -a $runemacs_bin $p"
}
}
function get_z_order($hWnd) {
$source = @"
using System;
using System.Runtime.InteropServices;
public static class HwndHelper
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
public static int GetWindowZOrder(IntPtr hWnd)
{
var zOrder = -1;
while ((hWnd = GetWindow(hWnd, 2 /* GW_HWNDNEXT */)) != IntPtr.Zero) zOrder++;
return zOrder;
}
}
"@
Add-Type -TypeDefinition $source
[HwndHelper]::GetWindowZOrder($hWnd)
}
function list_emacs_servers($dir) {
$array = @()
$items = Get-ChildItem $dir
foreach($i in $items) {
$name = $i.Name
$processid = ($i | Get-Content)[0].Split("")[1]
$hwnd = (Get-Process -Id $processid).MainWindowHandle
$z_order = get_z_order($hwnd)
$array += [pscustomobject]@{"name" = $name; "pid" = $processid; "hwnd" = $hwnd; "z_order" = $z_order}
}
return $array
}
function get_server_of_top_window($array) {
return ($array | Sort-Object -Property z_order -Descending)[0]
}
## main
if ($Args.length -ne 1) {
Write-Host "Invalid args."
exit
}
$filepath = $Args[0]
$list = list_emacs_servers $server_dir
if ($list.length -eq 0) {
open_with_emacs $filepath
}
else {
$s = get_server_of_top_window $list
open_with_emacs $filepath $s.name
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment