Error: RPC failed; result=22, HTTP code = 411

If you attempt to push a large set of changes to a Git repository with HTTP or HTTPS, you may get an error message such as error: RPC failed; result=22, HTTP code = 411. This is caused by a Git configuration default which limits certain HTTP operations to 1 megabyte. To override this limitation, update the postBuffer setting on your cloned repo.

try:

 1. Update git to the latest version (2.7.7, as to now), then,

 2.modify http.postBuffer: git config http.postBuffer 524288000 

mencoder进行视频分割合并

2014年9月03日 00:06

选自 http://forum.ubuntu.org.cn/viewtopic.php?f=74&t=153755&start=0

mencoder相当好, 用来合并av精华片段相当棒,价好量又足, 我一直都用它
mencoder可以做视频剪辑和视频格式转换。它既能在Windows操作系统上使用,又能在Linux操作系统上使用。它只能通过命令行的形式使用。

安装:sudo install mencoder

格式:

分割:
mencoder -ss 开始时间 -oac copy -ovc copy -endpos 终止时间 文件名 -o 目标文件名
合并:
mencoder -ovc copy -oac copy 文件名1 文件名2 -o 目标文件名

 

例一:
mencoder basket.rm -ovc lavc -oac lavc -o basket.avi
把basket.rm文件转换为basket.avi文件,其中,视频转换为mp4格式,音频转换为mp2格式。"-o basket.avi"定义转换成的文件名为"basket.avi","-ovc lavc"表示用默认的mp4格式编码图象,"-oac lavc"表示用默认的mp2格式编码声音。

例二:
mencoder basket.rm -ovc lavc -oac mp3lame -o basket.avi
"oac mp3lame"表示用mp3格式编码声音。

例三:
mencoder basket.rm -ovc lavc -oac mp3lame -o basket.avi -ss 5:00 -endpos 8:00
"-ss 5:00 -endpos 8:00"告诉mencoder仅仅转换从5分0秒到13分0秒的片段。

例四:
mencoder basket.avi -ovc copy -oac copy -o newbasket.avi -ss 5:00
-endpos 8:00
"-ovc copy"表示不作视频转换,"-oac copy"表示不作音频转换。这个命令把basket.avi文件中的5分0秒到13分0秒的部分拷贝到newbasket.avi文件中。

例五:
mencoder a1.avi a2.avi -ovc copy -oac copy -o asum.avi
这个命令把a1.avi和a2.avi文件合并为asum.avi文件。

例六:
mencoder basket.rm -ovc lavc -oac lavc -lavcopts vbitrate=100 -lavcopts abitrate=32 -o basket.avi
限制目的文件的大小。目的文件中,一秒种图象占用100kbit空间,一秒钟声音占用32kbit空间。较小的目标文件大小,一般意味着较低的图象和声音的质量。

在Windows下播放mencoder制作的mp4格式的文件,可能需要安装ffmpeg4解码器。

From http://hi.baidu.com/jn1net/blog/item/8431f7380d7db0d4d5622500.html

从 U 盘启动 Virtualbox

2014年9月03日 00:06

转载的文章,介绍了如何从 U 盘启动虚拟机。

Boot your USB Drive in VirtualBox

The GUI of VirtualBox does not have an option to boot a USB drive (Physical Drive) in a virtual machine.

However you can attach a physical drive to a virtual machine using a command line tool that is bundled with Virtual Box.You can then boot your virtual machine from the attached Physical drive.You need to use VirtualBox with Windows installed in order to use the software for a o2 mobile broadband dongle. As you are probably aware, you are unable to use it with Linux.

This is the continuation of my previous article Test bootable USB drive without restarting your computer.You can read more about bootable usb drives in that article.

Note:This tutorial has been updated for Virtualbox 4.

In this article I will show you how you can boot a bootable usb drive in Virtual Machine created by VirtualBox.You can easily test bootable USB drives within Windows or Linux and without restarting using this method.

Download and install Virtual Box and VirtualBox 4.0.2 Oracle VM VirtualBox Extension Pack from http://www.virtualbox.org/wiki/Downloads
The Extension pack adds support for USB 2.0 devices.

Attaching a Physical Disk to a Virtual Machine

Section 9.6 in the VirtualBox manual contains all the details required to attach a physical disk to a virtual machine.Using the vboxmanage.exe tool you can create a tiny vmdk file which points to your real USB drive (Physical Drive/Disk).You can attach this tiny vmdk to your virtual machine.A vmdk file is a virtual hard disk file which can be used with VirtualBox and VMWare.

The vboxmanage.exe tool is bundled with VirtualBox.You don’t have to download it separately

Open Command Prompt

Navigate to your Virtual Box installation Directory.

cd "c:\Program Files\Oracle\VirtualBox"

Type the following command and press enter
Syntax of the command

VBoxManage internalcommands createrawvmdk -filename path\to\usb.vmdk -rawdisk \\.\PhysicalDrive1

You have to replace pathtousb.vmdk with the path of your choice

Example

VBoxManage internalcommands createrawvmdk -filename "%USERPROFILE%\usb.vmdk" -rawdisk \\.\PhysicalDrive1

createraw Boot your USB Drive in VirtualBox

In Windows your 1st Hard Disk will be \.PhysicalDrive0.Your 2nd Hard disk will be \.PhysicalDrive1.

Warning:Do not Attach your Primary hard disk to your Virtual Machine and Boot it in the Virtual machine

To find the correct number for your USB Drive

Right Click on My Computer-Manage-Disk Management

Here you can find the correct disk number of your USB Drive

15zi9s6 Boot your USB Drive in VirtualBox

You will have to replace \.PhysicalDrive1 with the correct drive number.

In this case there was only 1 hard disk and 1 USB disk.So the USB drive is referred by \.PhysicalDrive1

In linux you have to replace \.PhysicalDrive1 with the correct /dev/sdx reference.

Now you should have a tiny vmdk file.You can start your Virtual Machine with this tiny vmdk and boot from it.

  1. Start VirtualBox.
  2. Create a new Machine or Select an Existing Machine.
  3. Click on Settings
    vmsettings Boot your USB Drive in VirtualBox
  4. Storage-Add Hard Diskaddharddisk Boot your USB Drive in VirtualBox
  5. Select the vmdk file that you had created.selectharddisk Boot your USB Drive in VirtualBoxvmdkfile Boot your USB Drive in VirtualBox
  6. Make sure that usb.vmdk is your Primary Master.attachedusb Boot your USB Drive in VirtualBox
  7. System-Boot Order.Set your Hard Disk as the first boot device.
  8. Now start your Virtual Machine.

Your virtual machine will boot from your bootable physical USB Drive.

In this screenshot I have used a bootable Ubuntu USB drive created using Unetbootin.

2jfiy39 Boot your USB Drive in VirtualBox

1470ut Boot your USB Drive in VirtualBox

121bekz Boot your USB Drive in VirtualBox

使用 github 替代 google code

2014年9月03日 00:05

可能是 XXX 防火墙近来发疯了,访问 google code 总是出错,所以把几个小项目转移到了 github 上,主要有:

  1. tubo-env
  2. 我的开发环境和桌面环境的备份,包括: Emacs, fvwm, GNU global 等的配制。
  3. tubo-books
  4. 整理的电子书籍,可以通过 devhelp 来看。 repository 中也包括了我修改过的 devhelp 及 gentoo 用的 ebuild 。
  5. wcmd
  6. 一个简单的文件管理器,仅依赖于 wxwidget 。
  7. kmu
  8. 一个用于管理 gentoo 的 keyword, USE 和 mask 的小工具。

在次做个记录,也欢迎有兴趣的人士来折腾它们。

xelatex 果然好用

2014年9月03日 00:05

尝试了一下 xelatex , 果然强悍,默认支持汉字,支持 UTF-8 编码, 并可以直接使用 TTF 字体,有时间再好好看看他的文档。

下面是一个简单的例子:

\documentclass[11pt,a4paper]{article}
\usepackage{fontspec}
\setmainfont[BoldFont=SimHei,ItalicFont=KaiTi_GB2312]{SimSun}
\setsansfont[BoldFont=SimHei]{KaiTi_GB2312}
\setmonofont{Microsoft YaHei}

\begin{document}
世界,你好!
\end{document}

使用方法和 latex 类似, 直接 xelatex filename.tex 就可以了。

XeLatex 写个人简历

2014年9月03日 00:05

\usepackage {ctex}

logviewer-mode of Emacs(Updated)

2014年9月03日 00:05

上一篇日志中写到了 logviewer-mode , 昨天晚上稍作修改, 添加了 logviewer-level 支持,这里重新贴下代码, 并说明下几个基本的热键。

代码如下:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; logviewer.el --- Simple log viewer.
;;
;; Copyright (C) 2011, Yang, Ying-chao
;;
;; Author:        Yang, Ying-chao <yangyingchao@gmail.com>
;;
;; This file is NOT part of GNU Emacs.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License
;; as published by the Free Software Foundation; either version 2
;; of the License, or (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program; if not, write to the Free Software
;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
;;
;; Commentary:
;;
;;   This is a simple log viewer, with syntax highlight.
;;
;;   To use logviewer, you should put logviewer.el into the top of load-path
;; of emacs, the add following lines into your .emacs:
;; (require 'logviewer)
;;
;;   When log files are huge, it will try to split huge logs into small ones
;; to speed up loading. In that case, you can press "n" & "p" to go to next
;; part (or previous part) to the log file. You can custom variable
;; logviewer-split-line to proper number to control the size of the slice of
;; huge file.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


;; Code
;; custom hooks
(defvar logviewer-mode-hook nil)

;; default mode map, really simple
(defvar logviewer-mode-map
  (let ((logviewer-mode-map (make-keymap)))
    (define-key logviewer-mode-map "n"
      (lambda (&optional arg)
        (interactive "^p")
        (or arg (setq arg 1))
        (logviewer-next-part t arg)))
    (define-key logviewer-mode-map "p"
      (lambda (&optional arg)
        (interactive "^p")
        (or arg (setq arg 1))
        (logviewer-next-part nil arg)))
    (define-key logviewer-mode-map "R" 'logviewer-reload-file)
    (define-key logviewer-mode-map "F" 'logviewer-set-filter)
    logviewer-mode-map)
  "Keymap for PS major mode")

(defvar logviewer-indent-width 4)

(defvar logviewer-font-lock-keywords
  `(
    ;; Date & time.
    (,(rx symbol-start
          (group (or "ERROR" "FATAL" "error" "fatal" "WARNING" "warning")) ":"
          (group (+ (*? not-newline))) line-end)
     (1 font-lock-warning-face) (2 font-lock-comment-face))
    (,(rx line-start
          (*? not-newline) (+ digit) ":" (+ digit) ":" (+ digit)
          (? "." (+ digit)))
     . font-lock-builtin-face)
    (,(rx symbol-start
          (group (*? not-newline) (+ digit) ":" (+ digit) ":" (+ digit) (? "." (+ digit)))
          (1+ space) (group (1+ (or alnum "-" "_"  blank))) (? "["(* digit) "]")":")
     (1 font-lock-builtin-face) (2 font-lock-variable-name-face))

    (,(rx symbol-start
          (group (or "info" "INFO" )) ":"
          (group (+ (*? not-newline))) line-end)
     (1 font-lock-function-name-face))
    (,(rx symbol-start
          (group (or "DEBUG" "debug" )) ":"
          (group (+ (*? not-newline))) line-end)
     (1 font-lock-keyword-face) (2 font-lock-doc-face))
    )
  )

(defvar logviewer-mode-syntax-table (make-syntax-table)
  "Syntax table for Logviewer mode")
;; (modify-syntax-entry ?( "()" logviewer-mode-syntax-table)
;;                      (modify-syntax-entry ?) ")("
;;                      logviewer-mode-syntax-table)

(defvar logviewer-imenu-expressions
  '((nil "^\\(?:[fF]unction\\|Add-Class\\)\\s-+\\([-a-z0-9A-Z_^:.]+\\)[^-a-z0-9A-Z_^:.]" 1))
  "alist of regexp identifying the start of logviewer definitions"
  )


(defvar logviewer-split-line 50000 "Lines when trying to split files.")
(defvar logviewer-current-file nil
  "Log file viewed by logviewer")

(defun logviewer-process-sentinel (process event)
  "description"
  (when (memq (process-status process) '(signal exit))
    (let* ((exit-status       (process-exit-status process))
           (command           (process-command process))
           (source-buffer     (process-buffer process))
           )

      (condition-case err
          (delete-process process)
        (error
         (let ((err-str (format "Error in process sentinel: %s"
                                 (error-message-string err))))
           (message err-str)))))))


;;;; Overrite function provied by Emacs itself.
(defun abort-if-file-too-large (size op-type filename)
  "If file SIZE larger than `large-file-warning-threshold', allow user to abort.
OP-TYPE specifies the file operation being performed (for message to user)."
  (let* ((re-log-str (rx (or "LOG" "log" "Log")))
         (log-cache (expand-file-name "~/.emacs.d/log_cache"))
         (cur-file nil)
         (process nil)
         (filename-base (file-name-sans-extension
                         (file-name-nondirectory filename)))
         (out-file-prefix (format "%s/%s" log-cache filename-base)))
    (if (and  large-file-warning-threshold size
              (> size large-file-warning-threshold))
        (if (string-match re-log-str filename) ;; This is logfile.
            (if (y-or-n-p
                 (format "LogFile %s is large (%dMB), really %s? "
                         (file-name-nondirectory filename)
                         (/ size 1048576) op-type))
                (if (and (string= op-type "open")
                         (executable-find "split"))
                    (progn
                      (if (file-exists-p log-cache)
                          nil
                        (mkdir log-cache t))
                      (setq logviewer-current-file
                            (format "%s000" out-file-prefix))

                      (message (format "%s*" out-file-prefix))
                      (call-process-shell-command "rm" nil "*Messages*" nil
                                    "-rf"
                                    (format "%s*" out-file-prefix))
                      (setq process
                            (start-process "Split-process" "*Messages*"
                                           "split"  "--suffix-length=3"
                                           "-d" "-l"
                                           (format "%s" logviewer-split-line)
                                           (expand-file-name filename)
                                           out-file-prefix))
                      (set-process-sentinel process
                                            'logviewer-process-sentinel)
                      (push filename recentf-list )
                      (while (not (file-exists-p logviewer-current-file))
                        (sleep-for 0.5))

                      (set-buffer (get-buffer-create filename-base))
                      (toggle-read-only 0)
                      (erase-buffer)
                      (insert-file-contents logviewer-current-file nil)
                      (switch-to-buffer filename-base)
                      (toggle-read-only 1)
                      (logviewer-mode)
                      (error "See this instead")
                      )
                  nil
                  (error "Aborted")
                  )
              (when  (not (y-or-n-p
                           (format "YC: File %s is large (%dMB), really %s? "
                                   (file-name-nondirectory filename)
                                   (/ size 1048576) op-type)))
                (error "Aborted"))
              )
          )
      )))



(defun logviewer-is-tmpfile ()
  "See whether current file is a temporary file or not."
  (if (string-match "log_cache" logviewer-current-file)
      t
    nil
    )
  )

(defun logviewer-reload-file ()
  "Reload current file."
  (interactive)
  (let ((pt (point)))
    (toggle-read-only 0)
    (erase-buffer)
    (insert-file-contents logviewer-current-file nil)
    (toggle-read-only 1)
    (goto-char pt)
    (message "Readload finished.")))

(defun get-next-slice (num cc)
  "Get next file, or previous file.
if direc = t, it returns next file, or it returns previous file"
  (let ((filename-pre nil)
        (filename-sub nil)
        (filename logviewer-current-file)
        (filename-sub-num 0)
        (sub-len 0)
        (new-seq 0)
        (fmt "")
        (bname (buffer-name))
        (pre-rx (rx line-start (group (+? not-newline))
                    (group (+ digit)) line-end)))
    (if (string-match pre-rx filename)
        (progn
          (setq filename-pre (match-string 1 filename))
          (setq filename-sub (match-string 2 filename))
          (setq sub-len (length filename-sub))
          (if cc
              (setq new-seq (+ (string-to-number filename-sub) num))
            (setq new-seq (- (string-to-number filename-sub) num)))
          (if (string-match (rx (group (+? anything)) "-P" (+ digit)) bname)
              (setq bname (match-string 1 bname))
            )
          (list (format (format "%%s%%0%dd" sub-len)
                        filename-pre new-seq)
                (format "%s-P%d" bname new-seq)))
      (error "Failed to parse filename"))))


(defun logviewer-next-part (dir &optional arg)
  "view next/previous file"
  (interactive "^p")
  (or arg (setq arg 1))
  (let ((n-list (get-next-slice arg dir))
        (next-file nil)
        (bname nil))
    (if (logviewer-is-tmpfile)
        (progn
          (setq next-file (car n-list))
          (setq bname (nth 1 n-list))
          (if (file-exists-p next-file)
              (progn
                (message (format "Now viewing: %s" next-file))
                (toggle-read-only 0)
                (erase-buffer)
                (insert-file-contents next-file nil)
                (setq logviewer-current-file next-file)
                (toggle-read-only 1)
                (rename-buffer bname))
            (progn
              (let ((msg nil))
                (if dir
                  (setq msg (concat "Head of log reached. File "
                                    next-file " does not exist!" ))
                  (setq msg (concat "Head of log reached. File "
                                    next-file " does not exist!" ))
                  )
                (error msg)))))
      (error "This is the whole file")))
  )


(defconst logviewer-levels
  '("FATAL" "ERROR" "WARRNING" "INFO" "DEBUG"))

(defvar logviewer-filter-level 9 "nil")

(defun get-lvl-str (num)
  "description"
  (let ((x (/ num 2))
        (lst nil))
    (while (>= x 0 )
      (setq x (1- x))
      (add-to-list  'lst (nth x logviewer-levels))
      )
    lst
    )
  )


(defun logviewer-get-filter (lvl)
  "Get filter beyond LVL."
  (if (string= lvl "FATAL")
      (progn
        (setq logviewer-filter-level 1)
        (rx bow "FATAL:"))

    (if (string= lvl "ERROR")
      (progn
        (setq logviewer-filter-level 3)
        (rx bow (or "FATAL" "ERROR") ":"))
      (if (string= lvl "WARRNING")
          (progn
            (setq logviewer-filter-level 7)
            (rx bow (or "FATAL" "ERROR" "WARRNING") ":"))
        (if (string= lvl "INFO")
            (progn
              (setq logviewer-filter-level 9)
              (rx bow (or "FATAL" "ERROR" "WARRNING" "INFO") ":")  ))
        )
      )
    )
  )

(defvar logviewer-filter-list '() "nil")

(defun logviewer-iter (reg-str)
  ""
  (if (search-forward-regexp reg-str (point-max) t)
      (progn
        (let ((pos1)
              (pos2))
          (move-beginning-of-line 1)
          (setq pos1 (point))
          (move-end-of-line 1)
          (setq pos2 (point))
          (cons pos1 pos2)
          (add-to-list 'logviewer-filter-list (cons pos1 pos2))
          (logviewer-iter reg-str)
          )
        )
    nil
      )
  )

(defun logviewer-set-filter ()
  "Set and show result of filter lvl"
  (interactive)
  (setq logviewer-filter-list nil)
  (let ((lvl nil)
        (cur-lvl   logviewer-filter-level ))
    (setq lvl (completing-read "Filter Level: " logviewer-levels))
    (if (string= lvl "DEBUG")
        (outline-flag-region (point-min) (point-max) nil)
      (progn
        (let ((logviewer-filter (logviewer-get-filter lvl))
              (content (buffer-substring-no-properties
                        (point-min) (point-max))))
          (if (< cur-lvl logviewer-filter-level)
              (outline-flag-region (point-min) (point-max) nil)
            )

          (goto-char (point-min))
          (logviewer-iter logviewer-filter)

          (outline-flag-region (point-min) (point-max) t)
          (if (> (length logviewer-filter-list) 0)
              (let ((i 0)
                    (len (length logviewer-filter-list))
                    (frange))
                (while (< i len)
                  (setq frange (nth i logviewer-filter-list))
                  (outline-flag-region (car frange) (1+ (cdr frange)) nil)
                  (setq i (1+ i))
                  ))
            )
          )))
    )
  )



(defun logviewer-setup-imenu ()
  "Installs logviewer-imenu-expression."
  (require 'imenu t)
  ;; imenu doc says these 3 are buffer-local by default
  (setq imenu-generic-expression logviewer-imenu-expressions)
  (imenu-add-menubar-index)
  )

(defun logviewer-mode ()
  "Major mode for editing Logviewer files"
  (interactive)
  (kill-all-local-variables)
  (setq major-mode 'logviewer-mode)
  (setq mode-name "logviewer")
  (set-syntax-table logviewer-mode-syntax-table)
  (use-local-map logviewer-mode-map)
  (set (make-local-variable 'font-lock-defaults)
       '(logviewer-font-lock-keywords))
  (toggle-read-only t)
  (if logviewer-current-file
      nil
    (setq logviewer-current-file (buffer-file-name))
      )
  (run-hooks 'logviewer-mode-hook))

(add-to-list 'auto-mode-alist '("\\.log\\'" .
                                logviewer-mode))
(provide 'logviewer)

主要热键有:

  • n:
    转到大文件(已被分割)的前一部分。
  • p:
    转到大文件(已被分割)的后一部分。
  • R:
    Reload, 重新装载文件。
  • F:
    设置 Filter, 包括 FATAL, ERROR, WARNING, INFO, DEBUG 几个级别。

附截图三张:

  • 通过 logviewer-mode 来查看一个 log 文件:

  • 起用 Log-filter:

  • 起用 Log-filter 以后的显示:

Tron Legacy 中的 Emacs

2014年9月03日 00:05

简介:
Tron Legacy 中的 Emacs 。
转载请注明出处


昨天看了一下 Tron Legacy 这个电影,从中截了两张图, 彰显一下 Emacs 的魅力。

 

2011年03月21日 - vic_kk - Live and Learn

图1. Emacs 中的 eshell


2011年03月21日 - vic_kk - Live and Learn
 

                                                               
图2 : 不知道这个 hanoi tower 在影片中用来表示什么……


Author:yangyingchao, 2011-03-21

2011年03月28日

2014年9月03日 00:05

今天删了上百行的代码,然后又把很多面向过程的代码用对象重新封装,改了很多的地方。

虽然在这个上面花费了一个下午的时间,但是相信随着后续代码的逐步加入,这个花费时间所做的改动,会为后续的开发带来很大的方便。

最后加句废话:应该在适当的场合使用合适的设计模式。

powershell-mode.el of emacs

2014年9月03日 00:05

简介:
更新了一下 powershell-mode 的代码
转 载请注明出处



;;
powershell-mode.el, version 0.5
;;
;; Author: Vivek Sharma (http://www.viveksharma.com/techlog)
;; Provides: Major mode for editing PS (PowerShell) scripts
;; Last Updated: 08/19/08
;;
;; Modified by Yang,Ying-chao(yangyingchao@gmail.com)
;;

;; custom hooks
(defvar powershell-mode-hook nil)

;; default mode map, really simple
(defvar powershell-mode-map
(let ((powershell-mode-map (make-keymap)))
;; (define-key powershell-mode-map "\r" 'powershell-indent-line)
(define-key powershell-mode-map "\t" 'powershell-indent-line)
powershell-mode-map)
"Keymap for PS major mode")

(defvar powershell-indent-width 4)

(defvar powershell-continued-regexp ".*\\(|[\\t ]*\\|`\\)$"
"Regexp matching a continued line (ending either with an
explicit backtick, or with a pipe)."
)

(defun powershell-continuation-line-p ()
"Returns t is the current line is a continuation line (i.e. the
previous line is a continued line, ending with a backtick or a pipe"

(interactive)
(save-excursion
(forward-line -1)
(looking-at powershell-continued-regexp)))

(defun powershell-indent-line-amount ()
"Returns the column to which the current line ought to be indented."
(interactive)
(beginning-of-line)
(let ((closing-paren (looking-at "[\t ]*[])}]")))
(if (powershell-continuation-line-p)
(progn
(while (powershell-continuation-line-p)
(forward-line -1))
(+ (current-indentation) powershell-indent-width))
(condition-case nil
(progn
(backward-up-list)
(cond ((not (looking-at ".[\t ]*\\(#.*\\)?$"))
(forward-char)
(skip-chars-forward " \t")
(current-column))
(closing-paren
(current-indentation))
(t
(+ (current-indentation) powershell-indent-width))))
(scan-error ;; most likely, we are at the top-level
0)))))

(defun powershell-indent-line ()
"Indent the current line of powershell mode, leaving the point
in place if it is inside the meat of the line"

(interactive)
(let ((savep (> (current-column) (current-indentation)))
(amount (save-excursion (powershell-indent-line-amount))))
(if savep
(save-excursion (indent-line-to amount))
(indent-line-to amount))))

(defvar pws-font-lock-keywords
`(
;; Basic keywords.
(,(rx symbol-start
(or
"default" "try" "continue" "return" "param" "finally" "catch"
"elseif" "foreach" "unction" "if" "else" "switch" "throw" "trap"
"where" "while" "for" "Default" "Try" "Continue" "Return" "Param"
"Finally" "Catch" "Elseif" "Foreach" "Unction" "If" "Else"
"Switch" "Throw" "Trap" "Where" "While" "For" "break" "Break"
"exit" "Exit"
) symbol-end)
. font-lock-keyword-face)
(,(rx symbol-start
(or
"env" "function" "global" "local" "private" "script" "variable")
symbol-end)
. font-lock-type-face)
;; Variables.
(,(rx symbol-start
(or
"Args" "ConfirmPreference" "ConsoleFileName" "DebugPreference"
"Error" "ErrorActionPreference" "ErrorView" "ExecutionContext"
"foreach" "FormatEnumerationLimit" "HOME" "Host" "Input"
"LASTEXITCODE" "MaximumAliasCount" "MaximumDriveCount"
"MaximumErrorCount" "MaximumFunctionCount"
"MaximumHistoryCount" "MaximumVariableCount" "MyInvocation"
"NestedPromptLevel" "OFS" "OutputEncoding" "PID" "PROFILE"
"PSHOME" "PWD" "ProgressPreference"
"ReportErrorShowExceptionClass" "ReportErrorShowInnerException"
"ReportErrorShowSource" "ReportErrorShowStackTrace" "ShellId"
"ShouldProcessPreference" "ShouldProcessReturnPreference"
"StackTrace" "VerbosePreference" "WarningPreference"
"WhatIfPreference" "false" "input" "lastWord" "line" "null"
"true" ))
. font-lock-variable-name-face)
(, (rx symbol-start "$" (1+ word) (0+ "_" (1+ word)))
. font-lock-variable-name-face)
;; Digital Numbers.
(,(rx symbol-start (1+ digit) (0+ "." (1+ digit)))
. font-lock-constant-face)
;; Function declaretions.
(,(rx symbol-start (group (any "f" "F") "unction")
(1+ space) (group (1+ (or word ? (any "_" "-")))))
(1 font-lock-keyword-face) (2 font-lock-function-name-face))
;; @blocks.
(,(rx line-start (* (any " \t"))
(group "@" (1+ (or word ?_)) (0+ "." (1+ (or word ?_)))))
(1 font-lock-type-face))
;; built-in comparations
(,(rx symbol-start "in"
symbol-end)
. font-lock-builtin-face)
(, (rx symbol-start "-"
(or

"and" "as" "band" "bnot" "bor" "bxor" "casesensitive"
"ccontains" "ceq" "cge" "cgt" "cle" "clike" "clt" "cmatch"
"cne" "cnotcontains" "cnotlike" "cnotmatch" "contains"
"creplace" "eq" "exact" "f" "file" "ge" "gt" "icontains"
"ieq" "ige" "igt" "ile" "ilike" "ilt" "imatch" "ine"
"inotcontains" "inotlike" "inotmatch" "ireplace" "is"
"isnot" "le" "like" "lt" "match" "ne" "not" "notcontains"
"notlike" "notmatch" "or" "replace" "wildcard")
)
. font-lock-builtin-face)
;; Builtin Functions
(,(rx (1+ (1+ word) "-") (1+ word))
. font-lock-function-name-face)
)
)

(defvar powershell-mode-syntax-table (make-syntax-table)
"Syntax table for Powershell mode")
(modify-syntax-entry ?# "<" powershell-mode-syntax-table)
(modify-syntax-entry ?' "\"" powershell-mode-syntax-table)
(modify-syntax-entry ?- "w" powershell-mode-syntax-table)
(modify-syntax-entry ?. "_" powershell-mode-syntax-table)
(modify-syntax-entry ?: "_" powershell-mode-syntax-table)
(modify-syntax-entry ?\\ "_" powershell-mode-syntax-table)
(modify-syntax-entry ?\n ">" powershell-mode-syntax-table)
(modify-syntax-entry ?_ "w" powershell-mode-syntax-table)
(modify-syntax-entry ?` "\\" powershell-mode-syntax-table)
(modify-syntax-entry ?{ "(}" powershell-mode-syntax-table)
(modify-syntax-entry ?} "){" powershell-mode-syntax-table)
(modify-syntax-entry ?[ "(]" powershell-mode-syntax-table)
(modify-syntax-entry ?] ")["
powershell-mode-syntax-table)
(modify-syntax-entry ?( "()" powershell-mode-syntax-table)
(modify-syntax-entry ?) ")("
powershell-mode-syntax-table)

(defvar powershell-imenu-expressions
'((nil "^\\(?:[fF]unction\\|Add-Class\\)\\s-+\\([-a-z0-9A-Z_^:.]+\\)[^-a-z0-9A-Z_^:.]" 1))
"alist of regexp identifying the start of powershell definitions"
)
(defun powershell-setup-imenu ()
"Installs powershell-imenu-expression."
(require 'imenu t)
;; imenu doc says these 3 are buffer-local by default
(setq imenu-generic-expression powershell-imenu-expressions)
(imenu-add-menubar-index)
(require 'which-func t)
(which-function-mode t)
)

(defun powershell-mode ()
"Major mode for editing PowerShell files"
(interactive)
(kill-all-local-variables)
(setq major-mode 'powershell-mode)
(setq mode-name "PS")
(set-syntax-table powershell-mode-syntax-table)
(use-local-map powershell-mode-map)
(setq indent-line-function 'powershell-indent-line)
(set (make-local-variable 'font-lock-defaults)
'(pws-font-lock-keywords))
(make-local-variable 'powershell-indent-width)
(set (make-local-variable 'comment-start) "#")
(set (make-local-variable 'comment-start-skip) "#+\\s*")
(set-syntax-table powershell-mode-syntax-table)
(run-hooks 'powershell-mode-hook))

(provide 'powershell-mode)









Author:yangyingchao, 2011-03-31