Learning Hammerspoon中英文互译

Learning Hammerspoon中英文互译

本书主要介绍mac的脚本软件Hammerspoon的基础使用,仅提供可阅读部分翻译。

Unleash the power of automation on your Mac

在您的Mac上释放自动化的力量

Diego Zamboni

This book is for sale at http://leanpub.com/learning-hammerspoon

This version was published on 2020-08-10


This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do.


© 2018 - 2020 Diego Zamboni

Para Susi, Kari, Fabi y Nube

Table of Contents

1 Preface to the book sample
前言
Preface to the early release Release notes
早期版本发行说明的前言

2 Introduction Mac automation
2 Mac自动化简介
What will you learn?

Conventions Used in This Book
本书中使用的约定

3 Getting started with Hammerspoon What is Hammerspoon?

  • How does Hammerspoon work?

  • Installing Hammerspoon

  • Your first Hammerspoon configuration 配置

  • The Hyper key

  • Keeping private information separate

  • 将私人信息分开

  • Debugging tools and the Hammerspoon console

4 Using Spoons in Hammerspoon Using a Spoon to locate your mouse
4 使用锤子中的勺子用勺子定位鼠标

Automated Spoon installation and configuration

5 Just enough Lua to be productive with Hammerspoon Flow control

  • Dot-vs-colon method access in Lua

  • Functions

  • Tables

  • Tables as namespaces

  • Patterns

  • String manipulation

  • 字符串操作

  • Learning more Lua

6 DRAFT 草稿 Exploring the Hammerspoon API Events and Hotkeys

Window, Menus and Screen Manipulation

On-screen Drawing, Images and Alerts

Application and Process Manipulation

Sound and Music

Networking and Web

System and Device Manipulation

Data Processing and Utilities

Hammerspoon itself

7 DRAFT Hammerspoon cookbook, tips and tricks Tip: be mindful of garbage collection

Show Homebrew package info

Tip: using asynchronous methods

Transform URLs before opening them

Other resources and configuration examples

8 Writing your own extensions and Spoons Writing a new Spoon

Writing a Hammerspoon extension in Lua

9 Using and extending Seal Using Seal

Writing your own Seal plugins

Colophon


1 Preface 前言 to the book sample

Thank you for downloading this book sample! In it you get to key chapters of the book which will help you get started with Hammerspoon and the use of Spoons to make life on your Mac easier.

I hope you will find it useful, and encourage you to get the full book to learn a lot more about advanced uses of Hammerspoon, including how to write your own Hammerspoon configuration in Lua, and how to develop your own Spoons.

In addition to this book sample, please take a look at ther Hammerspoon-related articles in my blog at , and at my “Hammerspoon” channel in YouTube, where you will find short videos that explain in a hands-on way some of the concepts that you find in this book: https://www.youtube.com/playlist?list=PLTZ6fO4RcbeOCZQ8OPTfq6KmUYDIC0OFL.

If you have any feedback or questions about this book, please visit the “Email the Author” page at https://leanpub.com/learning-hammerspoon/email_author/new.

Follow me on Twitter at https://twitter.com/zzamboni for more updates.

Preface to the early release

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Release notes

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

August 2020

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

December 2019

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

November 2019

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

August 2019

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

April 8th, 2019

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

October 2018

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

2 Introduction

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Mac automation

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

What will you learn?

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Conventions Used in This Book

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

3 Getting started with Hammerspoon

What is Hammerspoon?

Hammerspoon is a Mac application that allows you to achieve 实现 an unprecedented level 前所未有的水平 of control over your Mac. Hammerspoon enables interaction with the system at multiple layers–from low-level file system or network access, mouse or keyboard event capture and generation, all the way to manipulating applications or windows, processing URLs and drawing on the screen. It also allows interfacing with AppleScript, Unix commands and scripts, and other applications. Hammerspoon configuration is written in Lua, a popular embedded programming language.

Hammerspoon是一款Mac应用程序,它可以让你实现前所未有的实现级别的前所未有的水平控制。Hammerspoon支持在多个层次与系统进行交互-从低级文件系统或网络访问、鼠标或键盘事件捕获和生成,一直到操作应用程序或窗口、处理URL和在屏幕上绘图。它还允许与AppleScript、Unix命令和脚本以及其他应用程序接口。Hammerspoon配置是用流行的嵌入式编程语言Lua编写的。

Using Hammerspoon, you can replace many stand-alone Mac utilities for controlling or customizing specific aspects of your Mac (the kind that tends to overcrowd the menubar). For example, the following are doable using Hammerspoon (these are all things I do with it on my machine - you can see the configuration for these in my own Hammerspoon config file):

使用Hammerspoon,你可以取代许多独立的Mac实用程序来控制或定制你的Mac的特定方面(这类工具往往会挤满菜单栏)。例如,使用Hammerspoon可以执行以下操作(这些都是我在我的机器上使用它执行的所有操作-您可以在我自己的Hammerspoon配置文件中查看这些配置):

Add missing or more convenient keyboard shortcuts to applications, even for complex multi-step actions. For example: automated tagging and filing in Evernote, mail/note archival in Mail, Outlook and Evernote, filing items from multiple applications to OmniFocus using consistent keyboard shortcuts, or muting/unmuting a conversation in Skype.

向应用程序添加缺少的或更方便的键盘快捷键,即使是复杂的多步骤操作也是如此。例如:Evernote中的自动标记和归档,Mail、Outlook和Evernote中的邮件/便笺归档,使用一致的键盘快捷键将多个应用程序中的项目归档到OmniFocus,或者在Skype中静音/取消静音对话。

Open URLs in different browsers based on regular expression patterns. When combined with Site-specific Browsers (I use Epichrome), this allows for highly flexible management of bookmarks, plugins and search configurations.

基于正则表达式模式在不同浏览器中打开URL。当与特定于站点的浏览器(我使用的是Epichrome)结合使用时,可以高度灵活地管理书签、插件和搜索配置。

Replace Spotlight, Lacona and other launchers with a fully configurable, extensible launcher, which allows not only to open applications, files and bookmarks, but to trigger arbitrary Lua functions.

用一个完全可配置、可扩展的启动器取代Spotlight、Lacona和其他启动器,它不仅允许打开应用程序、文件和书签,还可以触发任意的Lua功能。

Manipulate windows using keyboard shortcuts to resize, move and arrange them.

Set up actions to happen automatically when switching between WiFi networks–for example for reconfiguring proxies in some applications.

Keyboard-triggered translation of selected text between arbitrary human languages.

键盘触发的选定文本在任意人类语言之间的翻译。

Keep a configurable and persistent clipboard history.

Automatically pause audio playback when headphones are unplugged.

拔下耳机插头后自动暂停音频播放。

Hammerspoon is the most powerful Mac automation utility I have ever used. If you are a programmer, it can make using your Mac vastly more fun and productive.

Hammerspoon是我用过的最强大的Mac自动化工具。如果你是一名程序员,它可以让使用Mac变得更加有趣和高效。

How does Hammerspoon work?

Hammerspoon acts as a thin layer between the operating system and a Lua-based configuration language. It includes extensions for querying and controlling many aspects of the system. Some of the lower-level extensions are written in Objective-C, but all of them expose a Lua API, and it is trivial to write your own extensions or modules to extend its functionality.

Hammerspoon充当操作系统和基于Lua的配置语言之间的薄层。它包括用于查询和控制系统的许多方面的扩展。一些较低级别的扩展是用Objective-C编写的,但所有这些扩展都公开了Lua API,编写自己的扩展或模块来扩展其功能是微不足道的。

From the Hammerspoon configuration you can also execute external commands, run AppleScript or JavaScript code using the OSA scripting framework, establish network connections and even run network servers; you can capture and generate keyboard events, detect network changes, USB or audio devices being plugged in or out, changes in screen or keyboard language configuration; you can draw directly on the screen to display whatever you want; and many other things. Take a quick look at the Hammerspoon API index page to get a feeling of its extensive capabilities. And that is only the libraries that are built into Hammerspoon. There is an extensive and growing collection of Spoons, modules written in pure Lua that provide additional functionality and integration. And of course, the configuration is simply Lua code, so you can write your own code to do whatever you want.

在Hammerspoon配置中,您还可以执行外部命令,使用OSA脚本框架运行AppleScript或JavaScript代码,建立网络连接,甚至运行网络服务器;您可以捕获和生成键盘事件、检测网络更改、插入或拔出USB或音频设备、更改屏幕或键盘语言配置;您可以直接在屏幕上绘制以显示您想要的任何内容;以及许多其他功能。快速浏览Hammerspoon API索引页,了解其广泛的功能。这只是Hammerspoon内置的图书馆。有一个广泛且不断增长的勺子集合,即用纯Lua编写的模块,它们提供额外的功能和集成。当然,配置只是Lua代码,所以您可以编写自己的代码来做任何您想做的事情。

Interested? Let’s get started!

Installing Hammerspoon

Hammerspoon is a regular Mac application. To install it by hand, you just need to download it from https://github.com/Hammerspoon/hammerspoon/releases/latest, unzip the downloaded file and drag it to your /Applications folder (or anywhere else you want).

If you are automation-minded like me, you probably use Homebrew and its plugin Cask to manage your applications. In this case, you can use Cask to install Hammerspoon:

brew cask install hammerspoon

When you run Hammerspoon for the first time, you will see its icon appear in the menubar, and a notification telling you that it couldn’t find a configuration file. Let’s fix that!

If you click on the initial notification, your web browser will open to the excellent Getting Started with Hammerspoon page, which I highly recommend you read for more examples.

Your first Hammerspoon configuration

Let us start with a few simple examples. As tradition mandates, we will start with a “Hello World” example. Open $HOME/.hammerspoon/init.lua (Hammerspoon will create the directory upon first startup, but you need to create the file) in your favorite editor, and type the following:

hs.hotkey.bindSpec({ { "ctrl", "cmd", "alt" }, "h" }, function() hs.notify.show("Hello World!", "Welcome to Hammerspoon", "") end )

Save the file, and from the Hammerspoon icon in the menubar, select “Reload config”. Apparently nothing will happen, but if you then press Ctrl​-​Alt​-​⌘​-​h on your keyboard, you will see a notification on your screen welcoming you to the world of Hammerspoon.

保存文件,并从菜单栏的Hammerspoon图标中选择“重新加载配置”。显然什么都不会发生,但是如果您随后按下键盘上的CtrlAltAlt​-​⌘​-​h,您将在屏幕上看到一个通知,欢迎您来到Hammerspoon的世界。

Although it should be fairly self-explanatory, let us dissect this example to give you a clearer understanding of its components:

虽然它应该是相当不言自明的,但让我们仔细分析这个示例,让您更清楚地了解它的组件:

All Hammerspoon built-in extensions start with hs. In this case, hs.hotkey is the extension that handles keyboard bindings. It allows us to easily define which functions will be called in response to different keyboard combinations. You can even differentiate between the keys being pressed, released or held down if you need to. The other extension used in this example is hs.notify, which allows us to interact with the macOS Notification Center to display, react and interact with notifications.

所有Hammerspoon内置扩展名都以hs开头。在本例中,hs.hotkey是处理键盘绑定的扩展。它允许我们轻松地定义将调用哪些函数来响应不同的键盘组合。如果需要,您甚至可以区分按下、松开或按住的键。本例中使用的另一个扩展是hs.Notify,它允许我们与MacOS通知中心交互,以显示、反应和交互通知。

Within hs.hotkey, the hs.hotkey.bindSpec function allows you to bind a function to a pressed key. Its first argument is a key specification which consists of a list (Lua lists and table literals are represented using curly braces) with two elements: a list of the key modifiers, and the key itself. In this example, { { "ctrl", "cmd", "alt" }, "h" } represents pressing Ctrl​-​Alt​-​⌘​-​h.

在hs.hotkey中,hs.hotkey.bindSpec函数允许您将函数绑定到按下的键。它的第一个参数是一个键规范,它由一个列表(LUA列表和表字面值用大括号表示)和两个元素组成:键修饰符列表和键本身。在本例中,{{“ctrl”,“cmd”,“alt”},“h”}表示按CtrlAlt​-​​-​⌘​-​h。

The second argument to bindSpec is the function to call when the key is pressed. Here we are defining an inline anonymous function using function() ... end.

bindSpec的第二个参数是按键时要调用的函数。在这里,我们使用function()定义内联匿名函数.结束。

The callback function uses hs.notify.show to display the message. Take a quick look at the hs.notify documentation to get an idea of its extensive capabilities, including configuration of all aspects of a notification’s appearance and buttons, and the functions to call upon different user actions.

回调函数使用hs.notfy.show显示消息。快速浏览h.tify文档以了解其广泛的功能,包括配置通知外观和按钮的所有方面,以及调用不同用户操作的功能。

Try changing the configuration to display a different message or use a different key. After every change, you need to instruct Hammerspoon to reload its configuration, which you can do through its menubar item (although we will learn how to automate it below).

尝试更改配置以显示不同的消息或使用不同的密钥。每次更改之后,您都需要指示Hammerspoon重新加载其配置,这可以通过其菜单栏项目来完成(尽管我们将在下面学习如何自动化)。

The Hyper key

You will notice through this book that we use the Ctrl​-​Alt​-​⌘ combination very frequently in our keybindings. The idea behind this is to use a modifier key combination which is never used by other applications, so that we can setup global Hammerspoon keybindings without worrying about conflicts with application-specific key bindings.

通过本书,您会注意到我们在键绑定中非常频繁地使用Ctrl-Alt​-​⌘组合。这背后的想法是使用其他应用程序从未使用过的修饰键组合,这样我们就可以设置全局Hammerspoon键绑定,而不必担心与特定于应用程序的键绑定冲突。

To avoid having to type {"ctrl","alt","cmd"} every time in the configuration file, we can define them as variable. For example, I have the following at the top of my init.lua:

hyper = { "ctrl", "alt", "cmd" } shift_hyper = { "shift", "ctrl", "alt", "cmd" }

Then we can simply use hyper or shift_hyper in our key binding declarations. The example above becomes:

hs.hotkey.bindSpec({ hyper, "h" }, function() hs.notify.show("Hello World!", "Welcome to Hammerspoon", "") end )

I find Ctrl​-​Alt​-​⌘ handy because the three keys are next to each other in a row right next to the spacebar in my keyboard, so I can easily hit them as a chord. You are of course free to use a different combination depending on your preferences and your keyboard layout.

我发现CtrlAlt​-​​-​⌘很方便,因为这三个键紧挨着键盘上的空格键,所以我可以很容易地按下它们作为和弦。当然,根据您的偏好和键盘布局,您可以自由使用不同的组合。

All the keybinding examples in this book will assume you have defined the hyper variable to represent the modifier key combination you want to use for most of your global keybindings.

本书中的所有键绑定示例都假定您已经定义了hyper变量来表示要用于大多数全局键绑定的修改键组合。

Mapping a single key as Hyper using Karabiner Elements

If you have a real, physical key to spare in your keyboard, you may want to map it as Hyper. For example, some people like to use the Caps Lock key as Hyper (I remap my Caps Lock key as a second Ctrl key, which I find more useful). To achieve this, you can use another free utility called Karabiner Elements, which allows you to do low-level keyboard remapping with use. You first need to install Karabiner:

如果您的键盘上有一个真正的物理按键可供备用,您可能希望将其映射为Hyper。例如,有些人喜欢使用Caps Lock键作为Hyper(我将Caps Lock键重新映射为第二个Ctrl键,我觉得这个键更有用)。要实现这一点,您可以使用另一个名为Karabiner Elements的免费实用程序,它允许您使用USE进行低级键盘重新映射。您首先需要安装Karabiner:

brew cask install karabiner-elements

Karabiner needs to install a kernel extension to do its work, and recent versions of macOS will block it by default. You will get a dialog notifying you about this, and asking you to use the Security Preferences Pane to allow it if you want. Once you click “Allow” in this pane, Karabiner should be ready to use:

Karabiner需要安装内核扩展才能完成工作,MacOS的最新版本默认情况下会对其进行挡路操作。您将看到一个对话框,通知您这一点,并要求您根据需要使用Security Preferences窗格进行允许。在此窗格中单击“允许”后,Karabiner就可以使用了:

Once you run the Karabiner-Elements app, you can remap the Caps Lock key to any other key. Within the “Simple Modifications” tab you could, for example, remap Caps Lock to a nonexisting function key such as F20:

一旦你运行了Karabiner-Elements应用程序,你就可以将Caps Lock键重新映射到任何其他键。例如,在“Simple Modiments”(简单修改)选项卡中,您可以将Caps Lock(大写锁定)重新映射到不存在的功能键,如F20:

You need to map the hyper and shift_hyper variables in your Hammerspoon configuration according to the key you used. For example:

hyper = { "f20" } shift_hyper = { "shift", "f20" }

Afterwards, you can use hyper and shift_hyper in your keybindings as shown before.

Keeping private information separate

It makes sense to keep your configuration files (as you should most other files) under control of a version control system like Git or Mercurial. This allows you to keep track of changes you make to your files, and it also makes it easy to share your configuration with others, for example by keeping them in Github or BitBucket.

将您的配置文件(就像您应该控制的大多数其他文件一样)置于Git或Mercurial等版本控制系统的控制之下是有意义的。这使您可以跟踪您对文件所做的更改,还可以轻松地与其他人共享您的配置,例如,通过将它们保存在Github或BitBucket中。

However, it is also common to have in your configuration pieces of information that you do not want to share publicly: passwords, authentication tokens, or simply experimental code that you are not ready to share yet. In theses cases, you can keep some configuration in separate files that are not committed to your shared files. In Lua, you can read an external file as code using the dofile() function. You can have a “local-only” configuration file which is read from your main init.lua file:

但是,在您的配置中有一些您不想公开共享的信息也是很常见的:密码、身份验证令牌,或者只是您还没有准备好共享的实验性代码。在这些情况下,您可以将一些配置保存在不提交到共享文件的单独文件中。在Lua中,可以使用dofile()函数将外部文件作为代码读取。您可以拥有从主init.lua文件读取的“仅本地”配置文件:

local localfile = hs.configdir .. "/init-local.lua" if hs.fs.attributes(localfile) then dofile(localfile) end

A couple of noteworthy points about this code:

We use the hs.configdir variable instead of hardcoding the path. This ensures that the code will execute properly even if (for some reason) the configuration directory is stored somewhere else.

我们使用hs.configdir变量,而不是对路径进行硬编码。这确保了即使(由于某些原因)配置目录存储在其他位置,代码也将正确执行。

The dofile() function throws an error if the file contains a syntax error which we want, but also if the file does not exist, which we do not want. For this reason we enclose the call to dofile in a check for existence of the file. Lua does not have a function to explicitly check for file existence, but we can use hs.fs.attributes, which returns nil if the file cannot be found.

如果文件包含我们想要的语法错误,但如果文件不存在(我们不想要的),则dofile()函数会抛出错误。出于这个原因,我们将对dofile的调用包含在检查文件是否存在的过程中。Lua没有显式检查文件是否存在的函数,但是我们可以使用hs.fs.tributes,如果找不到文件,它将返回nil。

Debugging tools and the Hammerspoon console

As you start modifying your configuration, errors will happen, as they always do when coding. To help in development and debugging, Hammerspoon offers a console window where you can see any errors and messages printed by your Lua code as it executes, and also type code to be evaluated. It is a very useful tool while developing your Hammerspoon configuration.

当您开始修改配置时,将会出现错误,就像它们在编码时经常发生的那样。为了帮助开发和调试,Hammerspoon提供了一个控制台窗口,您可以在其中看到Lua代码在执行时打印的任何错误和消息,还可以键入要评估的代码。在开发Hammerspoon配置时,它是一个非常有用的工具。

To invoke the console, you normally choose “Console…” from the Hammerspoon menubar item. However, this is such a common operation, that you might find it useful to also set a key combination for showing the console. Most of Hammerspoon’s internal functionality is also accessible through its API. In this case, looking at the documentation for the main hs module reveals that there is an hs.toggleConsole function. Using the knowledge you have acquired so far, you can easily configure a hotkey for opening and hiding the console:

要调用控制台,通常选择“Console…”从Hammerspoon菜单栏项目中拿到的。但是,这是一个非常常见的操作,因此您可能会发现还可以设置用于显示控制台的组合键。Hammerspoon的大部分内部功能也可以通过其API访问。在本例中,查看主hs模块的文档会发现有一个hs.toggleConsole函数。使用到目前为止所学的知识,您可以轻松配置用于打开和隐藏控制台的热键:

hs.hotkey.bindSpec({ hyper, "y" }, hs.toggleConsole)

``

tell application "Hammerspoon"
  execute lua code "hs.toggleConsole()"
end tell

Once you reload your configuration, you should be able to use Ctrl​-​Alt​-​⌘​-​y to open and close the console. Any Lua code you type in the Console will be evaluated in the main Hammerspoon context, so you can add to your configuration directly from there. This is a good way to incrementally develop your code before committing it to the init.lua file.

重新加载配置后,您应该能够使用Ctrl​-​Alt​-​⌘​-​y打开和关闭控制台。您在控制台中键入的任何Lua代码都将在主Hammerspoon上下文中求值,因此您可以直接从那里添加到您的配置中。这是在将代码提交到init.lua文件之前增量开发代码的好方法。

You may have noticed by now another common operation while developing Hammerspoon code: reloading the configuration, which you normally have to do from the Hammerspoon menu. So why not set up a hotkey to do that as well? Again, the hs module comes to our help with the hs.reload method:

到目前为止,您可能已经注意到开发Hammerspoon代码时的另一个常见操作:重新加载配置,这通常需要从Hammerspoon菜单执行。那么,为什么不设置一个热键来实现这一点呢?同样,hs模块通过hs.reload方法向我们提供帮助:

hs.hotkey.bindSpec({ hyper, "r" }, hs.reload)

Another useful development tool is the hs command, which you can run from your terminal to get a Hammerspoon console. To install it, you can use the hs.ipc.cliInstall function, which you can just add to your init.lua file to check and install the command every time Hammerspoon runs.

另一个有用的开发工具是hs命令,您可以从终端运行该命令来获取Hammerspoon控制台。要安装它,您可以使用hs.ipc.cliInstall函数,您只需将其添加到init.lua文件中,即可在Hammerspoon每次运行时检查并安装该命令。

The hs.ipc.cliInstall function creates symlinks under /usr/local/ to the hs command and its manual page file, located inside the Hammerspoon application bundle. Under some circumstances (particularly if you build Hammerspoon from source, or if you install different versions of it), you may end up with broken symlinks. If the hs command stops working and hs.ipc.cliInstall() doesn’t fix it, look for broken symlinks left behind from old versions of Hammerspoon. Remove them and things should work again.

hs.ipc.cliInstall函数在/usr/local/下创建指向hs命令及其手册页文件的符号链接,这些文件位于Hammerspoon应用程序包中。在某些情况下(特别是如果您从源代码构建Hammerspoon,或者如果您安装了不同版本的Hammerspoon),您可能会得到断开的符号链接。如果hs命令停止工作,并且hs.ipc.cliInstall()无法修复它,请查找旧版本的Hammerspoon留下的断开的符号链接。把它们移走,事情就会恢复正常。

Now you have all the tools for developing your Hammerspoon configuration.

4 Using Spoons in Hammerspoon

Spoons are modules written in Lua which can be easily installed and loaded into Hammerspoon to provide ready-to-use functionality. Spoons provide a predefined API to configure and use them. They are also a good way to share your own work with other users.

勺子是用Lua编写的模块,可以很容易地安装和加载到Hammerspoon中,以提供随时可用的功能。勺子提供预定义的API来配置和使用它们。它们也是与其他用户共享您自己的工作的好方法。

Using a Spoon to locate your mouse

As a first example, we will use the MouseCircle spoon, which allows us to set up a hotkey that displays a color circle around the current location of the mouse pointer for a few seconds, to help you locate it.

作为第一个示例,我们将使用MouseCircle勺子,它允许我们设置一个热键,该热键在鼠标指针的当前位置周围显示一个颜色圆圈几秒钟,以帮助您定位它。

To install the spoon, download its zip file from https://www.hammerspoon.org/Spoons/MouseCircle.html, unpack it, and double-click on the resulting MouseCircle.spoon file. Hammerspoon will install the Spoon under ~/.hammerspoon/Spoons/.

Once a Spoon is installed, you need to use the hs.loadSpoon() function to load it. Type the following in the Hammerspoon console, or add it to your init.lua file and reload the configuration:

hs.loadSpoon("MouseCircle")

After a spoon is loaded, and depending on what it does, you may need to configure it, assign hotkeys, and start it. A spoon’s API is available through the spoon. namespace. To learn the API you need to look at the spoon documentation page. In the case of MouseCircle, a look at http://www.hammerspoon.org/Spoons/MouseCircle.html reveals that it has two methods (bindHotkeys() and show()) and one configuration variable (color) available under spoon.MouseCircle.

加载勺子后,根据它的功能,您可能需要配置它、分配热键并启动它。勺子的API可以通过spoon.名称空间获得。要了解API,您需要查看勺子文档页面。在MouseCircle的例子中,查看http://www.hammerspoon.org/Spoons/MouseCircle.html会发现它在spoon.MouseCircle下有两个方法(bindHotkey()和show())和一个配置变量(COLOR)。

The first API call is spoon.MouseCircle:bindHotkeys(), which allows us to set up a hotkey that shows the mouse locator circle around the location of the mouse pointer. Let’s say we wanted to bind the mouse circle to Ctrl​-​Alt​-​⌘​-​d. According to the MouseCircle documentation, the name for this action is show, so we can do the following:

第一个API调用是spoon.MouseCircle:bindHotkey(),它允许我们设置一个热键来显示鼠标指针位置周围的鼠标定位器圆。假设我们想要将鼠标圈绑定到Ctrl​-​Alt​-​⌘​-​d。根据鼠标圈文档,此操作的名称为SHOW,因此我们可以执行以下操作:

spoon.MouseCircle:bindHotkeys({ show = { hyper, "d" } })

See The “Hyper” key for instructions on how to set up the hyper variable, if you have not done so yet.

有关如何设置HYPER变量的说明,请参见“Hyper”键(如果您尚未这样做)。

Once you do this, press the hotkey and you should see a red circle appear around the mouse cursor, and fade away after 3 seconds.

一旦你这样做了,按下热键,你应该会看到一个红色的圆圈出现在鼠标光标周围,并在3秒后消失。

All spoons which offer the possibility of binding hotkeys have to expose it through the same API:

所有提供绑定热键可能性的勺子都必须通过相同的API公开它:

spoon.SpoonName:bindHotkeys({ action1 = keySpec1, action2 = keySpec2, ... })

Each actionX is a name defined by the spoon, which refers to something that can be bound to a hotkey, and each keySpecX is a table with two elements: a list of modifiers and the key itself, such as { { "ctrl", "cmd", "alt" }, "d" } (or equivalently, { hyper, "d"})

每个actionX是由勺子定义的名称,它指的是可以绑定到热键的东西,而每个keySpecX是一个包含两个元素的表:修饰符列表和键本身,例如{{“ctrl”,“cmd”,“alt”},“d”}(或者等价地,{hyper,“d”})

The second API call in the MouseCircle spoon is show(), which triggers the functionality of showing the locator circle directly. Let’s try it! Type the following in the console:

MouseCircle勺子中的第二个API调用是show(),它触发直接显示定位器圆的功能。让我们试一试吧!在控制台中键入以下内容:

spoon.MouseCircle:show()

Most spoons are structured like this: you can set up hotkeys to trigger the main functionality, but you can also trigger it via method calls. Normally you won’t use these methods, but their availability makes it possible for you to use spoon functionality from our own configuration, or from other spoons, to create further automation.

大多数勺子的结构是这样的:您可以设置热键来触发主要功能,但也可以通过方法调用来触发它。通常情况下,您不会使用这些方法,但是它们的可用性使您可以从我们自己的配置或从其他勺子中使用勺子功能,以创建进一步的自动化。

spoon.MouseCircle.color is a public configuration variable exposed by the spoon, which specifies the color that will be used to draw the circle. Colors are defined according to the documentation for the hs.drawing.color module. Several color collections are supported, including the OS X system collections and a few defined by Hammerspoon itself. Color definitions are stored in Lua tables indexed by their name. For example, you can view the hs.drawing.color.hammerspoon table, including the color definitions, by using the convenient hs.inspect method on the console:

color是由勺子公开的公共配置变量,它指定将用于绘制圆的颜色。颜色是根据hs.draing.color模块的文档定义的。支持几个颜色集合,包括OS X系统集合和由Hammerspoon本身定义的几个集合。颜色定义存储在按其名称索引的LUA表中。例如,您可以在控制台使用方便的hs.spect方法查看hs.draing.Color.hammerspoon表,包括颜色定义:

 hs.inspect(hs.drawing.color.hammerspoon) { black = { alpha = 1, blue = 0.0, green = 0.0, red = 0.0 }, green = { alpha = 1, blue = 0.0, green = 1.0, red = 0.0 }, osx_red = { alpha = 1, blue = 0.302, green = 0.329, red = 0.996 }, osx_green = { ...

Lua does not include a function to easily get the keys of a table so you have to use the pairs() function to loop over the key/value pairs of the table. The hs.inspect function is convenient, but to get just the list of tables and the color names, without the color definitions themselves, you can use the following code (if you type this in the console you have to type it all in a single line – and beware, the output is a long list):

LUA不包括轻松获取表的键的函数,因此您必须使用PILES()函数来循环表的键/值对。hs.check函数很方便,但是要只获得表和颜色名称的列表,而不是颜色定义本身,您可以使用以下代码(如果您在控制台中键入这些内容,则必须在一行中全部键入-请注意,输出是一个很长的列表):

for listname,colors in pairs(hs.drawing.color.lists()) do print(listname) for color,def in pairs(colors) do print(" " .. color) end end

对于listname,成对的颜色(hs.draing.Color.list())执行打印(Listname);对于颜色,成对定义(Colors)执行打印(“”.颜色)结束端

If we wanted to make the circle green, we can assign the configuration value like this:

如果我们想让圆变成绿色,我们可以这样分配配置值:

spoon.MouseCircle.color = hs.drawing.color.hammerspoon.green

The next time you invoke the show() method, either directly or through the hotkey, you will see the circle in the new color.

下次直接或通过热键调用show()方法时,您将看到新颜色的圆。

You may have noticed that we accessed the configuration variable with a dot (spoon.MouseCircle.color), and we also used it for some function calls (e.g. hs.notify.show, whereas for show() we used a colon (spoon.MouseCircle:show()). The latter is Lua’s object-method-call notation, and its effect is to implicitly pass the object as an implicit first argument called self. This is simply a syntactic shortcut, i.e. the following two are equivalent:

您可能已经注意到,我们使用圆点(spoon.MouseCircle.color)访问配置变量,并且还将其用于一些函数调用(例如,hs.notfy.show,而对于show(),我们使用冒号(spoon.MouseCircle:show()。后者是Lua的对象-方法-调用表示法,其效果是隐式地将对象作为名为self的隐式第一个参数传递。这只是一个语法快捷方式,即以下两个是等效的:

spoon.MouseCircle:show() spoon.MouseCircle.show(spoon.MouseCircle)

Normally you would use colon notation, but the alternative can be useful when constructing function pointers. For example, if you wanted to bind a second key to show the mouse circle, you might initially try the following:

通常情况下,您会使用冒号表示法,但在构造函数指针时,另一种方法可能会很有用。例如,如果要绑定第二个关键点以显示鼠标圆,最初可能会尝试以下操作:

hs.hotkey.bindSpec({ hyper, "p" }, spoon.MouseCircle:show)

But this results in an error. The correct way is to wrap the call in an anonymous function:

但这会导致错误。正确的方法是将调用封装在匿名函数中:

hs.hotkey.bindSpec({ hyper, "p" }, function() spoon.MouseCircle:show() end)

Alternatively, you can use the hs.fnutils.partial function to construct a function pointer that includes the correct first argument:

或者,您可以使用hs.fnutils.part函数构造包含正确第一个参数的函数指针:

hs.hotkey.bindSpec({ hyper, "p" }, hs.fnutils.partial(spoon.MouseCircle.show, spoon.MouseCircle))

Lua supports using functions as first-class values, and the hs.fnutils extension includes a number of functions that make it easy to use them.

LUA支持将函数用作一级值,并且hs.fnutils扩展包括许多函数,使其易于使用。

By now you know enough to use spoons with Hammerspoon’s native capabilities: look for the ones you want, download and install them by hand, and configure them in your init.lua using their configuration variables and API. In the next section we will explore how to install and configure spoons in a more automated way.

到目前为止,您已经足够了解如何使用具有Hammerspoon原生功能的勺子了:查找所需的勺子,手动下载并安装它们,然后使用它们的配置变量和API在init.lua中配置它们。在下一节中,我们将探索如何以更自动化的方式安装和配置勺子。

Automated Spoon installation and configuration

Once you develop a complex Hammerspoon configuration using spoons, you may start wondering if there is an easy way to manage them. There are no built-in mechanisms for automatically installing spoons, but you can use a spoon called SpoonInstall that implements this functionality. You can download it from http://www.hammerspoon.org/Spoons/SpoonInstall.html. Once installed, you can use it to declaratively install, configure and run spoons. For example, with SpoonInstall you can use the MouseCircle spoon as follows:

一旦您使用勺子开发了一个复杂的Hammerspoon配置,您可能会开始想知道是否有一种简单的方法来管理它们。没有自动安装勺子的内置机制,但是您可以使用一个名为SpoonInstall的勺子来实现此功能。您可以从http://www.hammerspoon.org/Spoons/SpoonInstall.html.下载安装后,您可以使用它来声明性地安装、配置和运行勺子。例如,对于SpoonInstall,您可以按如下方式使用MouseCircle勺子:

hs.loadSpoon("SpoonInstall") spoon.SpoonInstall:andUse("MouseCircle", { config = { color = hs.drawing.color.osx_red, }, hotkeys = { show = { hyper, "d" } }})

If the MouseCircle spoon is not yet installed, spoon.SpoonInstall:andUse() will automatically download and install it, and set its configuration variables and hotkeys according to the declaration.

如果尚未安装MouseCircle勺子,spoon.SpoonInstall:anduse()将自动下载并安装,并根据声明设置其配置变量和热键。

If there is nothing to configure in the spoon, spoon.SpoonInstall:and-Use("SomeSpoon") does exactly the same as hs.loadSpoon("SomeSpoon"). But if you want to set configuration variables, hotkey bindings or other parameters, the following keys are recognized in the map provided as a second parameter:

如果在勺子中没有需要配置的内容,则spoon.SpoonInstall:and-use(“SomeSpoon”)的作用与hs.loadSpoon(“SomeSpoon”)完全相同。但是,如果您想要设置配置变量、热键绑定或其他参数,则会在提供的映射中将以下键识别为第二个参数:

config is a Lua table containing keys corresponding to configuration variables in the spoon. In the example above, config = { color = hs.drawing.color.osx_red } has the same effect as setting spoon.MouseCircle.color = hs.drawing.color.osx_red

CONFIG是一个LUA表,其中包含与勺子中的配置变量相对应的密钥。在上面的示例中,config={color=hs.draing.Color.osx_red}与设置spoon.MouseCircle.color=hs.draing.Color.osx_red的效果相同

hotkeys is a Lua table with the same structure as the mapping parameter passed to the bindHotkeys method of the spoon. In our example above, hotkeys = { show = { hyper, "d" } } automatically triggers a call to spoon.MouseCircle:bindHotkeys({ show = { hyper, "d" } }).

HotKey是一个Lua表,其结构与传递给勺子的bindHotkey方法的映射参数具有相同的结构。在上面的示例中,hotkey={show={hyper,“d”}}自动触发对spoon.MouseCircle:bindHotkey({show={hyper,“d”}})的调用。

loglevel sets the log level of the logger attribute within the spoon, if it exists. The valid values for this attribute are ‘nothing’, ‘error’, ‘warning’, ‘info’, ‘debug’, or ‘verbose’.

loglevel设置勺子内记录器属性的日志级别(如果存在)。此属性的有效值为‘Nothing’、‘Error’、‘Warning’、‘info’、‘debug’或‘Verbose’。

start is a boolean value which indicates whether to call the Spoon’s start() method (if it has one) after configuring everything else.

start是一个布尔值,它指示在配置其他所有内容之后是否调用Spoon的start()方法(如果有)。

fn specifies a function which will be called with the freshly-loaded Spoon object as its first argument. This can be used to execute other startup or configuration actions that are not covered by the other attributes. For example, if you use the Seal spoon (a configurable launcher), you need to call its loadPlugins() method to specify which Seal plugins to use. You can achieve this with something like this: spoon.SpoonInstall:andUse("Seal", { hotkeys = { show = { {"cmd"}, "space" } }, fn = function(s) s:loadPlugins({"apps", "calc", "safari_bookmarks"}) end, start = true, })

fn指定一个函数,该函数将使用新加载的Spoon对象作为其第一个参数进行调用。这可用于执行其他属性未涵盖的其他启动或配置操作。例如,如果您使用Seal Spoon(一个可配置的启动器),则需要调用其loadPlugins()方法来指定要使用的Seal插件。您可以这样实现:spoon.SpoonInstall:anduse(“Seal”,{hotkey={show={{“cmd”},“space”}},fn=function(S)s:loadPlugins({“apps”,“calc”,“safari_bookmark”})end,start=true,})

repo indicates the repository from where the Spoon should be installed if needed. Defaults to "default", which indicates the official Spoon repository at http://www.hammerspoon.org/Spoons/. I keep a repository of unofficial Spoons at http://zzamboni.github.io/zzSpoons/, and others may be available by the time you read this.

repo指示如果需要,应该从哪个存储库安装Spoon。缺省为“Default”,表示http://www.hammerspoon.org/Spoons/.的官方勺库我在http://zzamboni.github.io/zzSpoons/,有一个非官方的勺子储存库,当你读到这篇文章的时候,可能已经有其他的勺子了。

disable can be set to true to disable the Spoon (easier than commenting it out when you want to temporarily disable a spoon) in your configuration.

可以将DISABLE设置为TRUE以禁用配置中的勺子(当您要临时禁用勺子时,将其注释掉比将其注释掉更容易)。

You can assign functions and modules to variables to improve readability of your code. For example, in my init.lua file I make the following assignment:

您可以将函数和模块分配给变量,以提高代码的可读性。例如,在我的init.lua文件中,我进行了以下分配:

Install=spoon.SpoonInstall

Which allows me to write Install:andUse("MouseCircle",...), which is shorter and easier to read.

它允许我编写install:and use(“MouseCircle”,.),它更短,更容易阅读。

Managing repositories and spoons using SpoonInstall

使用SpoonInstall管理存储库和勺子

Apart from the andUse() “all-in-one” method, SpoonInstall has methods for specific repository- and spoon-maintenance operations. As of this writing, there are two Spoon repositories: the official one at http://www.hammerspoon.org/Spoons/, and my own at http://zzamboni.github.io/zzSpoons/, where I host some unofficial and in-progress Spoons.

除了anduse()“All-in-one”方法之外,SpoonInstall还具有用于特定存储库和勺子维护操作的方法。在撰写本文时,有两个Spoon存储库:一个是http://www.hammerspoon.org/Spoons/,的官方存储库,另一个是我自己的http://zzamboni.github.io/zzSpoons/,存储库,我在那里托管一些非官方的和正在进行的勺子。

The configuration variable used to specify repositories is SpoonInstall.repos. Its default value is the following, which configures the official repository identified as “default”:

用于指定存储库的配置变量是SpoonInstall.repos。其默认值如下,配置标识为默认的官方存储库:

{ default = { url = "https://github.com/Hammerspoon/Spoons", desc = "Main Hammerspoon Spoon repository", } }

To configure a new repository, you can define an extra entry in this variable. The following code creates an entry named “zzspoons” for my Spoon repository:

要配置新的存储库,您可以在此变量中定义额外的条目。下面的代码为我的Spoon存储库创建了一个名为“zzspoons”的条目:

spoon.SpoonInstall.repos.zzspoons = { url = "https://github.com/zzamboni/zzSpoons", desc = "zzamboni's spoon repository", }

After this, both “zzspoons” and “default” can be used as values to the repo attribute in the andUse() method, and in any of the other methods that take a repository identifier as a parameter. You can find the full API documentation at http://www.hammerspoon.org/Spoons/SpoonInstall.html.

此后,“zzspoons”和“default”都可以用作anduse()方法中的repo属性的值,也可以在任何其他接受存储库标识符作为参数的方法中使用。您可以在http://www.hammerspoon.org/Spoons/SpoonInstall.html.找到完整的api文档。

5 Just enough Lua to be productive with Hammerspoon

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Flow control

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Dot-vs-colon method access in Lua

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Functions

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Tables

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Tables as namespaces

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Patterns

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

String manipulation

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Learning more Lua

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

6 DRAFT Exploring the Hammerspoon API

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Events and Hotkeys

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

hs.hotkey and hs.hotkey.modal

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

hs.keycodes and hs.keycodes.map

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

hs.eventtap and hs.eventtap.event

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

hs.mouse

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Window, Menus and Screen Manipulation

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

hs.screen

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

hs.window and other window-manipulation libraries

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Other modules

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

On-screen Drawing, Images and Alerts

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Application and Process Manipulation

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Sound and Music

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Networking and Web

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

System and Device Manipulation

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Data Processing and Utilities

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Hammerspoon itself

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

7 DRAFT Hammerspoon cookbook, tips and tricks

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Tip: be mindful of garbage collection

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Show Homebrew package info

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Tip: using asynchronous methods

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Transform URLs before opening them

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Other resources and configuration examples

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Spacehammer: a Spacemacs-like modal config

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

8 Writing your own extensions and Spoons

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Writing a new Spoon

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

The Spoon API

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Designing a new spoon: Leanpub

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Creating the skeleton for a new spoon

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Spoon metadata and configuration

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Spoon methods

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Testing your Spoon

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Packaging and sharing the new Spoon

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

What’s next?

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Writing a Hammerspoon extension in Lua

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

9 Using and extending Seal

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Using Seal

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Writing your own Seal plugins

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Seal plugin structure and API

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

The myactions Seal plugin

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Adding commands to your Seal plugin

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

Colophon

This content is not available in the sample book. The book can be purchased on Leanpub at http://leanpub.com/learning-hammerspoon.

本文由博客群发一文多发等运营工具平台 OpenWrite 发布

你可能感兴趣的:(Learning Hammerspoon中英文互译)