Mac配置

Octopress安装和配置

2015-10-04  本文已影响2030人  holaOla

安装Octopress步骤

git config --global user.name "name"
git config --global user.email "emailaddress"
cd ~
mkdir git
cd git
git clone git@github.com:name/name.github.io.git 
cd ~/git
git clone git://github.com/imathis/octopress.git octopress
cd octopress
#修改Gemfile中源地址为ruby.taobao.org
bundle install
rake install
rake setup_github_pages 
#输入github.io.git地址
rake generate
rake preview    #在http://localhost:4000
cd source/_deploy
git pull origin master  #先同步一次,否则deploy可能报错
cd ..
rake deploy #该命令首先清空_deploy目录,然后将public目录整个拷贝过来,然后commit到github。_deploy 目录对应着master分支。
    
#备份source到github
git add .  
git commit -m 'your message'
git push origin source #source 目录下保存了所有的markdown源文件,是博客的原始数据,以及一些模板文件。因此很有必要备份。用上述命令提交到github,这样就用git管理起来了,再也不用担心数据丢失了。

1.Ruby等依赖安装

Ruby 需要1.9.3版本的,同时由于Jekyll和octopress都是ruby写的,会有诸多ruby依赖,建议切换ruby源为国内源。对于git版本没有太大要求。

查看ruby版本

ruby --version  

如果版本符合要求则进入下一步,否则请参照官方手册安装ruby或者使用RVM来安装。

gem install bundler  

建议国内用户切换gem源为国内源,方法如下:

gem source -r https://rubygems.org/ #删除官方源  
gem source -a http://ruby.taobao.org/  #添加淘宝源  
gem source -l #查看当前源  
git --version
#git version 1.9.1  

2.clone网站repo

先设置git

git config --global user.name "name"  
git config --global user.email "emailaddress"  

然后生成ssh key

$ ssh-keygen -t rsa -C "emailaddress"  

按3个回车,密码为空。
复制~/.ssh/id_rsa.pub的内容,添加到github账户中

然后clone网站repo

cd ~  
mkdir git  
cd git  
git clone git@github.com:name/name.github.io.git  

3.octopress安装

octopress的安装也比较简单,下载源码后会有Gemfile文件来指示所有依赖,使用bundle即可。

cd ~  
cd git  
git clone git://github.com/imathis/octopress.git octopress  
cd octopress  
source "http://ruby.taobao.org"  

然后执行命令bundle install就会自动安装所有octopress及其所有依赖。
注意: 如果上面的命令执行失败,提示下面的错误:

Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
/usr/bin/ruby1.9.1 extconf.rb 
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in 'require': cannot load such file -- mkmf   (LoadError)  

请执行下面的命令安装ruby1.9.1-dev

sudo apt-get install ruby1.9.1-dev  
rake install  

在octopress根目录下的Rakefile定义了如何将octopress跟Jekyll连接起来,rake打包了一些常见的如发布博客主题、生成博客数据、发布博客等一系列命令来简化博主的操作。直接使用Jekyll每一个任务都需要不少命令和文件编辑。

bundle update  

4.部署到github

github pages支持托管,地址为https://pages.github.com/, 在这个页面你只需要大概了解一下什么是github page,如何申请就行了。

新建一个仓库,这里以your_user_name.github.io为例(当然也可以是project,这个方法有点不一样)。
在octopress根目录执行

rake setup_github_pages

按照要求输入仓库地址等,这个命令会在跟目录下新建_deploy目录,这个会push到仓库的master分支,也就是访问博客的文件。
生成博客, rake generate 这个会按照既定规则生成静态文件的博客。
发布博客,rake deploy 将前一步生成的文件拷贝到_deploy目录并push到github

! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/yeesterbunny/yeesterbunny.github.com.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.  

解决方法是手动进入_deploy目录手动强制push一次。

cd octopress/_deploy
git pull origin master
cd ..
rake deploy 

这样再次执行就不会报错了。

git add .
git commit -m 'Initial source commit'
git push origin source

5.安装主题

cd ~/git
git clone git://github.com/bkutil/bootstrap-theme.git bootstrap-theme
rake install['bootstrap']
#rake install[bootstrap]/noglob rake install['bootstrap'] ,using zsh 
rake generate
rake preview

6.新建博文

新建博文也非常简单,octopress已经预定义了脚本rake new_post[“title”]方便我们操作,因为Jekyll有一套固定的文档路径以及命名规范,需要按照它的规定来实现才能成功生成博文。博文必须存储在source/_posts目录下,并且需要按照Jekyll的命名规范对文章进行命名:YYYY-MM-DD-post-title.markdown。文章的名字会被当做url的一部分,而其中的日期用于对博文的区分和排序。

new_post执行后会自动新建博文,并在相应的markdown文件中写入yaml元数据。

---
layout: post
title: "title"
date: 2013-08-03 16:36
comments: true
categories:
---

这里的categories是自定义的分类名,支持的定义方式如下:

# One category
categories: Sass
# Multiple categories example 1
categories: [CSS3, Sass, Media Queries]
# Multiple categories example 2
categories:
- CSS3
- Sass
- Media Queries

除此之外,还支持author: Your Name来指明作者,支持 published: false表明当前博文是草稿暂时不发布。

rake new_post["New Post"]
#edit the file source/_posts/{DATETIME}-New-Post.markdown
rake generate
git add .
git commit -am "Some comment here." 
git push origin source
rake deploy
rake new_page[super-awesome] # creates /source/super-awesome/index.markdown
rake new_page[super-awesome/page.html] # creates /source/super-awesome/page.html

像发布博文一样,默认后缀依然是markdown,但是你可以再Rakefile中修改这个默认配置;一个干净的页面文件如下:

---
layout: page
title: "Super Awesome"
date: 2011-07-03 5:59
comments: true
sharing: true
footer: true
---

这里的title来自于文件名。你也可以手动修改。跟博文的一样,除了不包含分类 categories,对于 sharing 和 comments 你可以关闭,对于 footer 你可以删除,这样就不会添加默认的footer信息到该页面;如果你不像要再页面中显示日期,可以删除这里的 date。

默认首页是显示全文,要想仅仅显示摘要,请在合适的地方插入下面的代码

<!-- more -->  

这个会生成一个Continue → 链接来指向完整博文,这个跟wordpress的一样。

7.用alfred命令创建新的Octopress post

在alfred的workflows里点+号,添加Templates-essentials-keyword to script,language选zsh,escaping里不要勾选space,在脚本里输入内容:

#!/bin/bash
#Path for your octopress installation
octopath=/Users/sia/git/octopress
#Editor to open the post in. (Exact name of the .app bundle in your Applications folder)
editorapp=MacDown
    
if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then
    
source "$HOME/.rvm/scripts/rvm"
fi
    
cd $octopath
rvm use 1.9.3@octopress
octopost=$(noglob rake new_post["{query}"]| grep -o 'source/_posts/.*')
open -a "$editorapp" $octopath/$octopost

这里打开方式用了MacDown,由于zsh不支持中括号,rake new_post命令需要用noglob rake new_post

编辑完成markdown内容后,发布:

rake generate
git add .
git commit -am "Some comment here." 
git push origin source
rake deploy

8.Octopress的一些常见问题

zsh: no matches found: new_post[...]

原因是诸如"["、"]"之类的不是正确的命令字符。当然,我们也可以使用转义符来解决这一问题。但每次都需要敲入转义符,实在是太麻烦了。解决方案是在~/.zshrc文件下,加入这样一行内容:

alias rake="noglob rake"  
gems/ruby-1.9.2-p290/gems/jekyll-0.11.0/lib/jekyll/convertible.rb:32:in 'read_yaml': invalid byte sequence in US-ASCII (ArgumentError)

这是因为jekyll代码没有很好地支持多种编码的缘故。解决办法是找到提示信息中的convertible.rb文件,将第29行的如下代码:

self.content = File.read(File.join(base, name))

修改为:

self.content = File.read(File.join(base, name), :encoding => "utf-8")

如果遇到ruby环境的问题,可以修改ruby环境下的setup_environment.bat文件,在文件最后加入2行:

set LC_ALL=en_US.UTF-8  
set LANG=en_US.UTF-8  

打开在octopress根目录下的Rakefile文件,在文件末尾增加如下代码

desc "Begin a new post in #{source_dir}/#{posts_dir} with Alias"
task :post, :title, :title_alias do |t, args|
 raise "### You haven't set anything up yet. First run rake install to set up an Octopress theme." unless File.directory?(source_dir)
 mkdir_p "#{source_dir}/#{posts_dir}"
 args.with_defaults(:title => 'new-post')
 title = args.title
 title_alias = args.title_alias
 filename = "#{source_dir}/#{posts_dir}/#{Time.now.strftime('%Y-%m-%d')}-#{title.to_url}.#{new_post_ext}"
 if File.exist?(filename)
   abort("rake aborted!") if ask("#{filename} already exists. Do you want to overwrite?", ['y', 'n']) == 'n'
 end
 puts "Creating new post: #{filename}"
 open(filename, 'w') do |post|
   post.puts "---"
   post.puts "layout: post"
   post.puts "title: \"#{title_alias}\""
   post.puts "date: #{Time.now.strftime('%Y-%m-%d %H:%M')}"
   post.puts "comments: true"
   post.puts "categories: "
   post.puts "---"
 end
end 

新的post任务接收两个参数,第一个参数与之前的new_post任务需要的参数完全相同,第二个参数alias就可以设置到markdown文件的title:中。例如我们要建立一个博客,标题为“如何建立Octopress博客”,则可以输入命令:

rake post["How to create octopress blog","如何建立Octopress博客"]       

注意,除了第二个参数引号内的内容可以用中文外,其他字符包括双引号、逗号和中括号都应该是Utf-8字符。此外,Title和Alias之间用“,”隔开,“,”后不能加空格。

加入图片在Octopress中,支持的Markdown语法为:

{% img [position] [url] [width] [height] %}

position可以设置为left,right或center。url可以是网上的图片url。如果是自己博客的图片,通常建议放在source/images目录下。为了将来更好地维护,建议按照年和月建立两层目录,如2012/12。因为rake generate命令会自动生成博客,放在source/images目录下的图片也会被复制过去。因而在markdown的img语法中,图片的url应该是/images/2012/12/picture.jpg。

Octopress支持的代码高亮有很多。我个人还是比较喜欢直接用codeblock标签。虽然每次敲入这个codeblock不太方便,但它胜在灵活见解。例如,粘贴的代码为ruby语言,就可以在代码片段前后分别加上:

{% codeblock lang:ruby %}  
# Here is ruby source code  
{% endcodeblock %}  

如果希望在首页只显示一部分内容,例如摘要,也非常简单。只需要在你希望首页显示的内容最后,输入:

<!--more-->  

9.octopress配置

实际上octopress已经很好的隐藏了Jekyll的诸多配置,我们只需要简单操作几个文件。octopress就会自动生成相应的Jekyll配置。这里我们仅仅讲解一下_config.yml文件的部分配置项,具体请看官网Configuring Octopress。

该文件的配置分为三大部分:Main config、Jekyll&Plugin、3rd Party Settings。

Main config
url:                # For rewriting urls for RSS, etc  
title:              # Used in the header and title tags
subtitle:           # A description used in the header
author:             # Your name, for RSS, Copyright, Metadata
simple_search:      # Search engine for simple site search
description:        # A default meta description for your site
date_format:        # Format dates using Ruby's date strftime syntax
subscribe_rss:      # Url for your blog's feed, defauts to /atom.xml
subscribe_email:    # Url to subscribe by email (service required)
category_feeds:     # Enable per category RSS feeds (defaults to false in 2.1)
email:              # Email address for the RSS feed if you want it.

注释说明已经很详细了,有一点需要强调的是,如果你想启用自己的域名来访问,这里的url务必修改为你自己的域名,否则即便你添加了CNAME文件,使用rake部署的时候也不会部署该CNAME文件。

建议

最好把里面的twitter相关的信息全部删掉,否则由于GFW的原因,将会造成页面load很慢。涉及到的文件比较多,小心删除,如果以发表博客,_deploy目录下无需手动删除,重新生成博客后会自动删除。
同理,修改定制文件/source/_includes/custom/head.html 把google的自定义字体去掉。

编辑 source_includes\custom\asides\about.html,内容如下:

<section>
 <h1>About Me</h1>
 <p>一句话自我介绍.</p>
 <p>新浪微博: <a href="http://weibo.com/soulmachine">@soulmachine</a><br/>
    Twitter: <a href="https://twitter.com/#!/soulmachine">@soulmachine</a><br/>
    Other: <a href="https://github.com/soulmachine">Github</a>, <a href="https://plus.google.com/103519507226474510310">Google+</a>, <a href="http://www.linkedin.com/in/soulmachine">LinkedIn</a>, <a href="http://www.quora.com/Jason-Day-2">Quora</a></p>
 </p>
</section> 

在 _config.yml 的 default_asides 里添加 custom/asides/about.html。

rake new_page[about]  

会生成 source/about/index.markdown 文件。

编辑该文件的内容。

然后在头部导航菜单中添加页面的超链接。具体做法是编辑 /source/_includes/custom/navigation.html 文件。

使用addthis.com的分享按钮,在网站上获取代码,粘贴到source/_includes/post/sharing.html 中,例如我的代码如下:

<div class="sharing">
 <!-- AddThis Button BEGIN -->
 <div class="addthis_toolbox addthis_default_style addthis_32x32_style">
   <a class="addthis_button_sinaweibo"></a>
   <a class="addthis_button_facebook"></a>
   <a class="addthis_button_twitter"></a>
   <a class="addthis_button_google_plusone_share"></a>
   <a class="addthis_button_delicious"></a>
   <a class="addthis_button_digg"></a>
   <a class="addthis_button_reddit"></a>
   <a class="addthis_button_compact"></a><a class="addthis_counter addthis_bubble_style"></a>
 </div>
 <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=undefined"></script>
 <!-- AddThis Button END -->

在_config.yml 中,将twitter, google+ 和facebook like的按钮设置为false,取消显示,因为 AddThis 已经集成了这三者。

启用Disqus,填入 short name即可。 Disqus在国外流行,在国内的加载速度太慢,而且只有twitter, facebook, g+,没有照顾到国内的用户习惯,因此替换成国内的多说,如下:

```bash


<div class="ds-thread" data-title="我的Octopress配置"></div>
<script type="text/javascript">
var duoshuoQuery = {short_name:"yanjiuyanjiu"};
(function() {
var ds = document.createElement('script');
ds.type = 'text/javascript';ds.async = true;
ds.src = 'http://static.duoshuo.com/embed.js';
ds.charset = 'UTF-8';
(document.getElementsByTagName('head')[0]
|| document.getElementsByTagName('body')[0]).appendChild(ds);
})();
</script>

_config.yml 中的配置也略有不同:  

 ```bash
duoshuo_comments: true
duoshuo_short_name: yanjiuyanjiu
duoshuo_asides_num: 5       # 侧边栏评论显示条目数
duoshuo_asides_avatars: 1   # 侧边栏评论是否显示头像
duoshuo_asides_time: 1      # 侧边栏评论是否显示时间
duoshuo_asides_title: 1     # 侧边栏评论是否显示标题
duoshuo_asides_admin: 0     # 侧边栏评论是否显示作者评论
duoshuo_asides_length: 32   # 侧边栏评论截取的长度
permalink: /blog/:year:month:day/

效果就是 www.example.com/blog/20130403/ 。模仿的是豆瓣的URL格式。

参考官方文档 jekyll Permalinks。

<section>
 <h1>友情链接</h1>
 <ul>
   <li>
     <a href="http://coolshell.cn/">酷壳CoolShell</a>
   </li>
   <li>
     <a href="http://mindhacks.cn/">刘未鹏MIND HACKS</a>
   </li>
   <li>
     <a href="http://blog.codingnow.com/">云风</a>
   </li>
   <li>
     <a href="http://www.cnblogs.com/Solstice/">陈硕</a>
   </li>
 </ul>
</section>

然后在 _config.yml 文件中,在 default_asides 的数组中添加custom/asides/blogroll.html

首先,将head.html中的两行代码注释掉,省去了加载字体,加快网页加载速度。

<!--Fonts from Google"s Web font directory at http://google.com/webfonts -->
<!-- <link href="http://fonts.googleapis.com/css?family=PT+Serif:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css"> -->
<!-- <link href="http://fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css"> -->

参考 这篇博客 最佳 Web 中文默认字体 ,在 sass/custom/_fonts.scss 中添加如下三行代码:

$heading-font-family: arial, sans-serif;
$header-title-font-family: arial, sans-serif;
$header-subtitle-font-family: arial, sans-serif;

刷新网页,可以看见中文的粗体变黑了。

在 _config.yml中,把Read on改为“继续阅读”。在source/_includes/custom/asides目录下,将”Recent Comments”改为“最新评论”,”Categories”改为“分类目录”,将source/_includes/asides/recent_posts.html 中”Recent Posts”改为“最新文章”。

在_config.yml填入 Google Analytics Tracking ID,例如 UA-7583537-4。

主题: 3rd Party Octopress Themes
插件: 3rd party plugins

如果换了一台电脑,怎样迅速恢复环境呢?参考 Clone Your Octopress to Blog From Two Places。

注意,在windows上,要首先安装python,否则,虽然所有操作可以成功,不报错误,但是你发现打开后首页一篇空白,我当时百思不得其解,因为没有任何错误信息,最后去看生成的文件,所有index.html都是0字节,就猜测应该是编译出了问题。安装python就好了,linux默认是有Python的,就没有这个问题,windows真是坑爹!以后只在windows下做编辑类的工作,编译和运行都放到Linux下。

见官方文档 Sharing Code Snippets。

Octopress是一款为hacker量身定制的博客系统,当然内置了代码高亮的功能!它的代码高亮功能是通过Pygments实现的,配色方案用的是Solarized,堪称完美。

Octopress支持多种方式嵌入代码,可以直接嵌入代码,也可以引用github上的gist。

开头用三个反引号空格加bash,结尾三个反引号,直接嵌入代码,比codeblock要简洁。

在 source/_includes/custom/footer.html 的第一行加入如下代码:

<!-- mathjax config similar to math.stackexchange -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
 jax: ["input/TeX", "output/HTML-CSS"],
 tex2jax: {
   inlineMath: [ ['$', '$'] ],
   displayMath: [ ['$$', '$$']],
   processEscapes: true,
   skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
 },
 messageStyle: "none",
 "HTML-CSS": { preferredFont: "TeX", availableFonts: ["STIX","TeX"] }
});
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML"

这样就引入了MathJax的JS包,可以直接在markdown文件里直接写公式了,例如 $\dfrac {\pi}{2}$

上面的代码也可以在 source/_includes/custom/header.html 里添加,不过这样会使得页面的加载速度变慢。还可以在 source/_layouts/default.html里添加。

有一个问题,rdiscount这个解析器,对 mathjax 大部分支持,某些细节处理的不好,举个例子,它会在动把公式中的 ^n 转换成 n ,例如 $2^n$ 会解析成 $2n$ ,这样就破坏了整个公式,导致公式无法解析。参考这里一段话:
> as discount for example automatically replaces x^2 withx2 which interrupts the MathJax rendering.

因此要换一个解析器, Maruku 和 Kramdown 都可以,由于Maruku主页PR=4,Kramdown的主页PR=5,因此选择Kramdown。

上一篇 下一篇

猜你喜欢

热点阅读